"""Exercise real child pytest sessions, including a deliberately failing shard."""
import json
from pathlib import Path
import subprocess
import sys

import pytest


RUNNER = Path(__file__).with_name('parallel_runner.py')


@pytest.mark.parametrize('reverse,fail', [(False, False), (True, False), (False, True), (False, 'abort')])
def test_real_shards_run_every_case_once_and_propagate_failures(tmp_path, reverse, fail):
    first = tmp_path / 'test_one.py'
    second = tmp_path / 'test_two.py'
    first.write_text('''def test_first(tmp_path):
    path=tmp_path/'private.txt'
    assert not path.exists()
    path.write_text('first')
    assert path.read_text() == 'first'
def test_second(tmp_path):
    assert not (tmp_path/'private.txt').exists()
''', encoding='utf-8')
    body = "__import__('os')._exit(7)" if fail == 'abort' else f'assert {not fail!r}, "expected prototype failure"'
    second.write_text(f'def test_other():\n    {body}\n', encoding='utf-8')
    arguments = ['--workers', '2', str(first), str(second)]
    if reverse:
        arguments.insert(0, '--reverse')
    script = f'''
import importlib.util
from pathlib import Path
spec=importlib.util.spec_from_file_location('parallel_probe', {str(RUNNER)!r})
module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
module.ROOT=Path({str(tmp_path)!r})
raise SystemExit(module.run({arguments!r}))
'''
    result = subprocess.run([sys.executable, '-B', '-c', script], capture_output=True,
                            text=True, encoding='utf-8', timeout=60)
    if fail == 'abort':
        assert result.returncode != 0
        assert 'No pytest report' in result.stderr
        return
    assert result.returncode == int(fail), result.stdout + result.stderr
    summary = json.loads(result.stdout.strip().splitlines()[-1])
    assert summary['collected'] == 3
    assert summary['counts'] == ({'passed': 2, 'failed': 1} if fail else {'passed': 3})
