import sys
import subprocess
import textwrap
import os

import pytest

from rwt import launch


def test_with_path(tmpdir, capfd):
	params = ['-c', 'import sys; print(sys.path)']
	launch.with_path(str(tmpdir), params)
	out, err = capfd.readouterr()
	assert str(tmpdir) in out


@pytest.mark.xfail(reason="cleanup can't occur with execv; #4")
def test_with_path_overlay(tmpdir, capfd):
	params = ['-c', 'import sys; print(sys.path)']
	# launch subprocess so as not to overlay the test process
	script = textwrap.dedent("""
		import rwt.launch
		rwt.launch.with_path_overlay({tmpdir!r}, {params!r})
		print("cleanup")
	""").strip().replace('\n', '; ').format(tmpdir=str(tmpdir), params=params)
	subprocess.Popen([sys.executable, '-c', script]).wait()
	out, err = capfd.readouterr()
	assert str(tmpdir) in out
	assert "cleanup" in out


@pytest.fixture
def clean_pythonpath(monkeypatch):
	monkeypatch.delitem(os.environ, 'PYTHONPATH', raising=False)


def test_build_env(clean_pythonpath):
	os.environ['PYTHONPATH'] = 'something'
	env = launch._build_env('else')
	expected = os.pathsep.join(('else', 'something'))
	assert env['PYTHONPATH'] == expected

	os.environ['PYTHONPATH'] = ''
	env = launch._build_env('something')
	assert env['PYTHONPATH'] == 'something'

	initial = os.pathsep.join(['something', 'else'])
	os.environ['PYTHONPATH'] = initial
	env = launch._build_env('a')
	expected = os.pathsep.join(['a', 'something', 'else'])
	assert env['PYTHONPATH'] == expected

@@ -1444,28 +1444,467 @@
 v%5B'PYTHONPATH'%5D == expected%0A
+%0A%0Adef test_build_env_includes_pth_files(tmpdir, clean_pythonpath):%0A%09%22%22%22%0A%09If during _build_env, there are .pth files in the target directory,%0A%09they should be processed to include any paths indicated there.%0A%09See #6 for rationale.%0A%09%22%22%22%0A%09(tmpdir / 'foo.pth').write_text('pkg-1.0', encoding='utf-8')%0A%09env = launch._build_env(str(tmpdir))%0A%09expected = os.pathsep.join(%5Bstr(tmpdir), str(tmpdir / 'pkg-1.0')%5D)%0A%09assert env%5B'PYTHONPATH'%5D == expected%0A

Add test capturing #7