import py, pytest

import _pytest._code
from _pytest.config import getcfg, get_common_ancestor, determine_setup
from _pytest.main import EXIT_NOTESTSCOLLECTED

class TestParseIni:
    def test_getcfg_and_config(self, testdir, tmpdir):
        sub = tmpdir.mkdir("sub")
        sub.chdir()
        tmpdir.join("setup.cfg").write(_pytest._code.Source("""
            [pytest]
            name = value
        """))
        rootdir, inifile, cfg = getcfg([sub], ["setup.cfg"])
        assert cfg['name'] == "value"
        config = testdir.parseconfigure(sub)
        assert config.inicfg['name'] == 'value'

    def test_getcfg_empty_path(self, tmpdir):
        getcfg([''], ['setup.cfg']) #happens on py.test ""

    def test_append_parse_args(self, testdir, tmpdir, monkeypatch):
        monkeypatch.setenv('PYTEST_ADDOPTS', '--color no -rs --tb="short"')
        tmpdir.join("setup.cfg").write(_pytest._code.Source("""
            [pytest]
            addopts = --verbose
        """))
        config = testdir.parseconfig(tmpdir)
        assert config.option.color == 'no'
        assert config.option.reportchars == 's'
        assert config.option.tbstyle == 'short'
        assert config.option.verbose
        #config = testdir.Config()
        #args = [tmpdir,]
        #config._preparse(args, addopts=False)
        #assert len(args) == 1

    def test_tox_ini_wrong_version(self, testdir):
        testdir.makefile('.ini', tox="""
            [pytest]
            minversion=9.0
        """)
        result = testdir.runpytest()
        assert result.ret != 0
        result.stderr.fnmatch_lines([
            "*tox.ini:2*requires*9.0*actual*"
        ])

    @pytest.mark.parametrize("name", "setup.cfg tox.ini pytest.ini".split())
    def test_ini_names(self, testdir, name):
        testdir.tmpdir.join(name).write(py.std.textwrap.dedent("""
            [pytest]
            minversion = 1.0
        """))
        config = testdir.parseconfig()
        assert config.getini("minversion") == "1.0"

    def test_toxini_before_lower_pytestini(self, testdir):
        sub = testdir.tmpdir.mkdir("sub")
        sub.join("tox.ini").write(py.std.textwrap.dedent("""
            [pytest]
            minversion = 2.0
        """))
        testdir.tmpdir.join("pytest.ini").write(py.std.textwrap.dedent("""
            [pytest]
            minversion = 1.5
        """))
        config = testdir.parseconfigure(sub)
        assert config.getini("minversion") == "2.0"

    @pytest.mark.xfail(reason="probably not needed")
    def test_confcutdir(self, testdir):
        sub = testdir.mkdir("sub")
        sub.chdir()
        testdir.makeini("""
            [pytest]
            addopts = --qwe
        """)
        result = testdir.inline_run("--confcutdir=.")
        assert result.ret == 0
        
class TestConfigCmdlineParsing:
    def test_parsing_again_fails(self, testdir):
        config = testdir.parseconfig()
        pytest.raises(AssertionError, lambda: config.parse([]))

    def test_explicitly_specified_config_file_is_loaded(self, testdir):
        testdir.makeconftest("""
            def pytest_addoption(parser):
                parser.addini("custom", "")
        """)
        testdir.makeini("""
            [pytest]
            custom = 0
        """)
        testdir.makefile(".cfg", custom = """
            [pytest]
            custom = 1
        """)
        config = testdir.parseconfig("-c", "custom.cfg")
        assert config.getini("custom") == "1"

    def test_absolute_win32_path(self, testdir):
        temp_cfg_file = testdir.makefile(".cfg", custom="""
            [pytest]
            addopts = --version
        """)
        from os.path import normpath
        temp_cfg_file = normpath(str(temp_cfg_file))
        ret = pytest.main("-c " + temp_cfg_file)
        assert ret == _pytest.main.EXIT_OK

class TestConfigAPI:
    def test_config_trace(self, testdir):
        config = testdir.parseconfig()
        l = []
        config.trace.root.setwriter(l.append)
        config.trace("hello")
        assert len(l) == 1
        assert l[0] == "hello [config]\n"

    def test_config_getoption(self, testdir):
        testdir.makeconftest("""
            def pytest_addoption(parser):
                parser.addoption("--hello", "-X", dest="hello")
        """)
        config = testdir.parseconfig("--hello=this")
        for x in ("hello", "--hello", "-X"):
            assert config.getoption(x) == "this"
        pytest.raises(ValueError, "config.getoption('qweqwe')")

    @pytest.mark.skipif('sys.version_info[:2] not in [(2, 6), (2, 7)]')
    def test_config_getoption_unicode(self, testdir):
        testdir.makeconftest("""
            from __future__ import unicode_literals

            def pytest_addoption(parser):
                parser.addoption('--hello', type='string')
        """)
        config = testdir.parseconfig('--hello=this')
        assert config.getoption('hello') == 'this'

    def test_config_getvalueorskip(self, testdir):
        config = testdir.parseconfig()
        pytest.raises(pytest.skip.Exception,
            "config.getvalueorskip('hello')")
        verbose = config.getvalueorskip("verbose")
        assert verbose == config.option.verbose

    def test_config_getvalueorskip_None(self, testdir):
        testdir.makeconftest("""
            def pytest_addoption(parser):
                parser.addoption("--hello")
        """)
        config = testdir.parseconfig()
        with pytest.raises(pytest.skip.Exception):
            config.getvalueorskip('hello')

    def test_getoption(self, testdir):
        config = testdir.parseconfig()
        with pytest.raises(ValueError):
            config.getvalue('x')
        assert config.getoption("x", 1) == 1

    def test_getconftest_pathlist(self, testdir, tmpdir):
        somepath = tmpdir.join("x", "y", "z")
        p = tmpdir.join("conftest.py")
        p.write("pathlist = ['.', %r]" % str(somepath))
        config = testdir.parseconfigure(p)
        assert config._getconftest_pathlist('notexist', path=tmpdir) is None
        pl = config._getconftest_pathlist('pathlist', path=tmpdir)
        print(pl)
        assert len(pl) == 2
        assert pl[0] == tmpdir
        assert pl[1] == somepath

    def test_addini(self, testdir):
        testdir.makeconftest("""
            def pytest_addoption(parser):
                parser.addini("myname", "my new ini value")
        """)
        testdir.makeini("""
            [pytest]
            myname=hello
        """)
        config = testdir.parseconfig()
        val = config.getini("myname")
        assert val == "hello"
        pytest.raises(ValueError, config.getini, 'other')

    def test_addini_pathlist(self, testdir):
        testdir.makeconftest("""
            def pytest_addoption(parser):
                parser.addini("paths", "my new ini value", type="pathlist")
                parser.addini("abc", "abc value")
        """)
        p = testdir.makeini("""
            [pytest]
            paths=hello world/sub.py
        """)
        config = testdir.parseconfig()
        l = config.getini("paths")
        assert len(l) == 2
        assert l[0] == p.dirpath('hello')
        assert l[1] == p.dirpath('world/sub.py')
        pytest.raises(ValueError, config.getini, 'other')

    def test_addini_args(self, testdir):
        testdir.makeconftest("""
            def pytest_addoption(parser):
                parser.addini("args", "new args", type="args")
                parser.addini("a2", "", "args", default="1 2 3".split())
        """)
        testdir.makeini("""