|
| 1 | +import csv |
| 2 | +import io |
| 3 | +import unittest |
| 4 | + |
| 5 | +from test.support import threading_helper |
| 6 | +from test.support.threading_helper import run_concurrently |
| 7 | + |
| 8 | + |
| 9 | +NTHREADS = 10 |
| 10 | + |
| 11 | + |
| 12 | +@threading_helper.requires_working_threading() |
| 13 | +class TestCSV(unittest.TestCase): |
| 14 | + def test_concurrent_reader_next(self): |
| 15 | + input_rows = [f"{i},{i},{i}" for i in range(50)] |
| 16 | + input_stream = io.StringIO("\n".join(input_rows)) |
| 17 | + reader = csv.reader(input_stream) |
| 18 | + output_rows = [] |
| 19 | + |
| 20 | + def read_row(): |
| 21 | + for row in reader: |
| 22 | + self.assertEqual(len(row), 3) |
| 23 | + output_rows.append(",".join(row)) |
| 24 | + |
| 25 | + run_concurrently(worker_func=read_row, nthreads=NTHREADS) |
| 26 | + self.assertSetEqual(set(input_rows), set(output_rows)) |
| 27 | + |
| 28 | + def test_concurrent_writer_writerow(self): |
| 29 | + output_stream = io.StringIO() |
| 30 | + writer = csv.writer(output_stream) |
| 31 | + row_per_thread = 10 |
| 32 | + expected_rows = [] |
| 33 | + |
| 34 | + def write_row(): |
| 35 | + for i in range(row_per_thread): |
| 36 | + writer.writerow([i, i, i]) |
| 37 | + expected_rows.append(f"{i},{i},{i}") |
| 38 | + |
| 39 | + run_concurrently(worker_func=write_row, nthreads=NTHREADS) |
| 40 | + |
| 41 | + # Rewind to the start of the stream and parse the rows |
| 42 | + output_stream.seek(0) |
| 43 | + output_rows = [line.strip() for line in output_stream.readlines()] |
| 44 | + |
| 45 | + self.assertEqual(len(output_rows), NTHREADS * row_per_thread) |
| 46 | + self.assertListEqual(sorted(output_rows), sorted(expected_rows)) |
| 47 | + |
| 48 | + |
| 49 | +if __name__ == "__main__": |
| 50 | + unittest.main() |
0 commit comments