|
| 1 | +import pytest |
| 2 | +from mpi4py import MPI |
| 3 | +from pytest_mpi.parallel_assert import parallel_assert |
| 4 | + |
| 5 | + |
| 6 | +@pytest.mark.parametrize('expression', [True, False]) |
| 7 | +def test_parallel_assert_equivalent_to_assert_in_serial(expression): |
| 8 | + try: |
| 9 | + parallel_assert(expression) |
| 10 | + parallel_raised_exception = False |
| 11 | + except AssertionError: |
| 12 | + parallel_raised_exception = True |
| 13 | + try: |
| 14 | + assert expression |
| 15 | + serial_raised_exception = False |
| 16 | + except AssertionError: |
| 17 | + serial_raised_exception = True |
| 18 | + |
| 19 | + assert serial_raised_exception == parallel_raised_exception |
| 20 | + |
| 21 | + |
| 22 | +@pytest.mark.parallel([1, 2, 3]) |
| 23 | +def test_parallel_assert_all_tasks(): |
| 24 | + comm = MPI.COMM_WORLD |
| 25 | + expression = comm.rank < comm.size // 2 # will be True on some tasks but False on others |
| 26 | + |
| 27 | + try: |
| 28 | + parallel_assert(expression, 'Failed') |
| 29 | + raised_exception = False |
| 30 | + except AssertionError: |
| 31 | + raised_exception = True |
| 32 | + |
| 33 | + assert raised_exception, f'No exception raised on rank {comm.rank}!' |
| 34 | + |
| 35 | + |
| 36 | +@pytest.mark.parallel([1, 2, 3]) |
| 37 | +def test_parallel_assert_participating_tasks_only(): |
| 38 | + comm = MPI.COMM_WORLD |
| 39 | + expression = comm.rank < comm.size // 2 # will be True on some tasks but False on others |
| 40 | + |
| 41 | + try: |
| 42 | + parallel_assert(expression, participating=expression) |
| 43 | + raised_exception = False |
| 44 | + except AssertionError: |
| 45 | + raised_exception = True |
| 46 | + |
| 47 | + assert not raised_exception, f'Exception raised on rank {comm.rank}!' |
| 48 | + |
| 49 | + |
| 50 | +@pytest.mark.parallel([1, 2, 3]) |
| 51 | +def test_legacy_parallel_assert(): |
| 52 | + comm = MPI.COMM_WORLD |
| 53 | + expression = comm.rank < comm.size // 2 # will be True on some tasks but False on others |
| 54 | + if expression: |
| 55 | + local_expression = expression # This variable is undefined on non-participating tasks |
| 56 | + |
| 57 | + try: |
| 58 | + parallel_assert(lambda: local_expression, participating=expression) |
| 59 | + raised_exception = False |
| 60 | + except AssertionError: |
| 61 | + raised_exception = True |
| 62 | + |
| 63 | + assert not raised_exception, f'Exception raised on rank {comm.rank}!' |
0 commit comments