import sys
import os
import types
import pytest
from pypy.conftest import APPLEVEL_FN

THIS_DIR = os.path.dirname(__file__)

# ================================
# Customization of applevel tests
# ================================
#
# The various AppTestFoo classes are automatically collected and generated by
# make_hpy_apptest below. Additionally, it is possible to customize the body
# of the generated AppTest* classes by creating extra_AppTest* classes below

# to skip a specific test, you can do the following:
## class extra_AppTestBasic:
##     def test_exception_occurred(self):
##         import pytest
##         pytest.skip('fixme')

disable = False

if sys.platform.startswith('linux') and sys.maxsize <= 2**31:
    # skip all tests on linux32
    disable = True
if sys.platform == "win32":
    # skip all tests on windows, they take around 2 hours
    disable = True


# Monkeypatch distutils.sysconfig.get_config_var for the parse_ext_suffix
# check in devel/abitag.py. Needed for "cross-compilation" when
# untranslated so the distutils machinery can get at the "pypy39-pp73"
# ABI tag. Note EXT_SUFFIX does not exist in python2
from distutils import sysconfig
d = sysconfig.get_config_vars()
d['EXT_SUFFIX'] = ".pypy39-pp73-x86_64-linux-gnu.so"

 
# ========================================================================
# pytest hooks to automatically generate AppTests from HPy vendored tests
# ========================================================================

def pytest_pycollect_makemodule(path, parent):
    if path.fnmatch(APPLEVEL_FN):
        if parent.config.getoption('direct_apptest'):
            return

        from pypy.tool.pytest.apptest2 import AppTestModule
        from ..state import State

        class AppTestModuleHPy(AppTestModule):
            def setup(self):
                space = None
                for item in self.session.items:
                    try:
                        space = item.w_obj.space
                        break
                    except AttributeError:
                        continue
                else:
                    # cannot happen: there must be at least one apptest test
                    raise ValueError("no apptest but AppTestModuleHPy called??")
                state = space.fromcache(State)
                state.reset()

        rewrite = parent.config.getoption('applevel_rewrite')
        return AppTestModuleHPy(path, parent, rewrite_asserts=rewrite)
    # Let the default collect handle it
    return
    

def pytest_pycollect_makeitem(collector, name, obj):
    from pypy.tool.pytest.apptest import AppClassCollector
    from pypy.module._hpy_universal.test._vendored.support import HPyTest
    if (collector.istestclass(obj, name) and
            issubclass(obj, HPyTest) and
            not name.startswith('App')):
        appname = make_hpy_apptest(collector, name, obj)
        return AppClassCollector(appname, parent=collector)

def pytest_ignore_collect(path, config):
    if (config.getoption('runappdirect') or config.getoption('direct_apptest')
            or disable):
        # workaround for pytest issue #2016 (fixed in 3.0.5)
        if os.path.commonprefix([str(path), THIS_DIR]) == THIS_DIR:
            return True
    if path == config.rootdir.join('pypy', 'module', '_hpy_universal', 'test',
                                   '_vendored', 'test_support.py'):
        return True
    if "/trace/" in str(path) or r'\trace\t' in str(path):
        return True


def pytest_collect_file(path, parent):
    if (parent.config.getoption('runappdirect') or parent.config.getoption('direct_apptest')
            or disable):
        pytest.skip("_hpy_universal tests skipped, module not active")


def make_hpy_apptest(collector, name, cls):
    """
    Automatically create HPy AppTests from the _vendored tests.
    This is more or less equivalent of doing the following:

        from pypy.module._hpy_universal.test._vendored.test_basic import TestBasic
        class AppTestBasic(HPyAppTest, TestBasic):
            pass

    """
    from pypy.module._hpy_universal.test._vendored.support import HPyDebugTest
    from pypy.module._hpy_universal.test.support import (HPyAppTest, HPyCPyextAppTest,
                                                         HPyDebugAppTest)
    appname = 'App' + name

    # the original HPy test classes might contain helper methods such as
    # TestParseItem.make_parse_item: to make them available inside AppTests,
    # we need to prefix them with w_. Here it's a generic way to make
    # available at applevel all the non-test methods which are found
    d = {}
    for name, value in cls.__dict__.iteritems():
        if (not name.startswith('test_') and
            not name.startswith('__') and
            isinstance(value, types.FunctionType)):
            d['w_%s' % name] = value
    #
    # cpyext tests need a different base class
    use_cpyext = getattr(cls, 'USE_CPYEXT', False)
    use_hpydebug = issubclass(cls, HPyDebugTest)
    if use_cpyext:
        bases = (HPyCPyextAppTest, cls)
    elif use_hpydebug:
        bases = (HPyDebugAppTest, cls)
    else:
        bases = (HPyAppTest, cls)
    #
    # finally, we can create the new AppTest class
    appcls = type(appname, bases, d)
    setattr(collector.obj, appname, appcls)
    return appname

def pytest_sessionstart(session):
    from pypy.module._hpy_universal.test import support as _support
    from pypy.module._hpy_universal._vendored.hpy.devel import HPyDevel
    from pypy.module._hpy_universal.llapi import BASE_DIR
    if 'libs' not in _support._static_lib_cache:
        hpy_devel = HPyDevel(str(BASE_DIR))
        result = _support._try_build_static_lib(hpy_devel, 'universal')
        _support._static_lib_cache['libs'] = result
        if not result:
            import warnings
            warnings.warn(
                "HPy static-lib build failed; "
                "falling back to per-test source compilation.",
                stacklevel=1,
            )


@pytest.fixture(scope='class')
def python_subprocess(request):
    pytest.skip("no subprocess available")

@pytest.fixture(scope='class')
def fatal_exit_code(request):
    return -1


