Skip to main content

Add some tests for concurrently

ID
34f5644
date
2021-10-25 07:00:25+00:00
author
Alex Chan <alex@alexwlchan.net>
parent
19ea71b
message
Add some tests for concurrently
changed files
4 files, 51 additions, 17 deletions

Changed files

.coveragerc (0) → .coveragerc (122)

diff --git a/.coveragerc b/.coveragerc
new file mode 100644
index 0000000..4e72b86
--- /dev/null
+++ b/.coveragerc
@@ -0,0 +1,9 @@
+[run]
+branch = True
+include =
+    concurrently.py
+    test_concurrently.py
+
+[report]
+show_missing = True
+fail_under = 100

.gitignore (6) → .gitignore (16)

diff --git a/.gitignore b/.gitignore
index 0d20b64..004a8d7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1,2 @@
 *.pyc
+.coverage

concurrently.py (1350) → concurrently.py (1161)

diff --git a/concurrently.py b/concurrently.py
index a960c37..dea62fb 100644
--- a/concurrently.py
+++ b/concurrently.py
@@ -12,6 +12,8 @@ def concurrently(fn, fn_inputs, *, max_concurrency=5):
     Generates (input, output) tuples as the calls to ``fn`` complete.
 
     """
+    # Make sure we get a consistent iterator throughout, rather than
+    # getting the first element repeatedly.
     fn_inputs = iter(fn_inputs)
 
     with concurrent.futures.ThreadPoolExecutor() as executor:
@@ -32,18 +34,3 @@ def concurrently(fn, fn_inputs, *, max_concurrency=5):
             for input in itertools.islice(fn_inputs, len(done)):
                 fut = executor.submit(fn, input)
                 futures[fut] = input
-
-
-import time
-import random
-
-def doubler(input):
-    print(f"Started {input}")
-    time.sleep(random.randint(1, 10) / 100)
-    print(f"Finished {input}")
-    return input * 2
-
-
-if __name__ == '__main__':
-    for (input, output) in concurrently(doubler, range(10)):
-        print(f"{input} ~> {output}")
\ No newline at end of file

test_concurrently.py (142) → test_concurrently.py (673)

diff --git a/test_concurrently.py b/test_concurrently.py
index 722d41d..8cf539a 100644
--- a/test_concurrently.py
+++ b/test_concurrently.py
@@ -1,4 +1,41 @@
+import random
+import time
+
 from concurrently import concurrently
 
-for input, output in concurrently(lambda x: x, range(100), max_concurrency=1):
-    print(input, output)
\ No newline at end of file
+
+def double(x):
+    time.sleep(random.random() / 100)
+    return x * 2
+
+
+def test_handles_iterator():
+    result = set(concurrently(double, fn_inputs=range(10)))
+
+    assert result == {
+        (0, 0),
+        (1, 2),
+        (2, 4),
+        (3, 6),
+        (4, 8),
+        (5, 10),
+        (6, 12),
+        (7, 14),
+        (8, 16),
+        (9, 18),
+    }
+
+
+def test_handles_list():
+    result = set(concurrently(double, fn_inputs=[1, 3, 5, 7, 9, 11, 13]))
+
+    assert result == {
+        (1, 2),
+        (3, 6),
+        (5, 10),
+        (7, 14),
+        (9, 18),
+        (11, 22),
+        (13, 26)
+    }
+