This instance will be upgraded to Heptapod 0.21.0rc2 on 2021-04-16 at 11:00 UTC+2 (a few minutes of down time)

pytesthgenv.py 4.8 KB
Newer Older
1
"""Pytest plugin to set up test environment"""
Yuya Nishihara's avatar
Yuya Nishihara committed
2 3 4 5 6 7 8 9

from __future__ import absolute_import

import os
import shutil
import sys
import tempfile

10 11
import pytest

Yuya Nishihara's avatar
Yuya Nishihara committed
12

13
# don't import mercurial or tortoisehg before setting up test environment
14

15
class HgEnvPlugin(object):
16 17
    """Set up temporary environment"""

18 19 20 21 22 23
    def pytest_addoption(self, parser):
        parser.addoption('--keep-tmpdir', action='store_true', default=False,
                         help='Keep temporary directory after running tests')
        parser.addoption('--tmpdir',
                         help=('Put temporary files in the given directory '
                               '(implies --keep-tmpdir)'))
24

25 26
    def pytest_configure(self, config):
        options = config.known_args_namespace
27 28 29
        self.keep_tmpdir = options.keep_tmpdir or bool(options.tmpdir)
        self.tmpdir = options.tmpdir

30 31
    @pytest.hookimpl(tryfirst=True)
    def pytest_collection(self):
32 33 34 35
        if 'mercurial' in sys.modules:
            raise Exception('loaded mercurial module before setting up '
                            'test environment')
        self._setupsyspath()
36
        self._setuptmpdir()
37
        self._setupconfigdir()
38 39
        self._setuphgrc()
        self._setupmiscenv()
40
        self._setupqapp()
41 42 43 44 45 46 47 48 49 50 51 52 53 54

    def _setupsyspath(self):
        hgpath = os.environ.get('HGPATH')
        if hgpath:
            hgpath = os.path.abspath(hgpath)
            sys.path.insert(1, hgpath)
            os.environ['HGPATH'] = hgpath

        thgpath = os.environ.get('THGPATH')
        if not thgpath:
            thgpath = os.path.join(os.path.dirname(__file__), '..')
        thgpath = os.path.abspath(thgpath)
        sys.path.insert(1, thgpath)
        os.environ['THGPATH'] = thgpath
55

56 57 58 59 60 61
        # setup PYTHONPATH so that hg process can look up thg modules
        pypath = thgpath
        if 'PYTHONPATH' in os.environ:
            pypath += os.pathsep + os.environ['PYTHONPATH']
        os.environ['PYTHONPATH'] = pypath

62 63 64 65 66 67 68 69 70
    def _setuptmpdir(self):
        if self.tmpdir:
            if os.path.exists(self.tmpdir):
                raise Exception('temp dir %r already exists' % self.tmpdir)
            os.makedirs(self.tmpdir)
        else:
            self.tmpdir = tempfile.mkdtemp('', 'thgtests.')
        os.environ['HGTMP'] = self.tmpdir

71 72 73 74 75 76 77
    def _setupconfigdir(self):
        self.configdir = os.path.join(self.tmpdir, '.config')
        os.mkdir(self.configdir)
        # these environment variables seem not to affect the running process
        os.environ['APPDATA'] = self.configdir
        os.environ['XDG_CONFIG_HOME'] = self.configdir

78 79 80 81 82 83 84 85 86
    def _setuphgrc(self):
        """Create a fresh hgrc for repeatable result"""
        os.environ['HGRCPATH'] = hgrcpath = os.path.join(self.tmpdir, '.hgrc')
        f = open(hgrcpath, 'w')
        try:
            f.write('[defaults]\n')
            f.write('backout = -d "0 0"\n')
            f.write('commit = -d "0 0"\n')
            f.write('tag = -d "0 0"\n')
87 88 89
            # TODO: run mq-dependent tests in separate process?
            f.write('[extensions]\n')
            f.write('mq=\n')
90 91
            f.write('delaylock = %s\n'
                    % os.path.join(os.path.dirname(__file__), 'delaylock.py'))
92 93
            # register config defaults
            f.write('tortoisehg.util.configitems=\n')
94 95 96 97 98 99 100 101 102 103 104 105 106
        finally:
            f.close()

    def _setupmiscenv(self):
        """Reset some common environment variables for repeatable result"""
        os.environ['LANG'] = os.environ['LC_ALL'] = os.environ['LANGUAGE'] = 'C'
        os.environ['TZ'] = 'GMT'
        os.environ['HOME'] = self.tmpdir
        os.environ['EMAIL'] = 'Foo Bar <foo.bar@example.com>'
        os.environ['http_proxy'] = ''
        os.environ['HGUSER'] = 'test'
        os.environ['HGENCODING'] = 'ascii'
        os.environ['HGENCODINGMODE'] = 'strict'
107 108
        # suppress "Session management error" on X11
        os.environ['SESSION_MANAGER'] = ''
109

110
    def _setupqapp(self):
111
        from tortoisehg.hgqt.qtcore import QCoreApplication, QSettings
Yuya Nishihara's avatar
Yuya Nishihara committed
112 113
        from tortoisehg.hgqt.qtgui import QApplication

114 115
        # Make sure to hold single QApplication instance on memory. Multiple
        # instances will lead crash.
116 117
        guienabled = (os.name == 'nt' or sys.platform == 'darwin'
                      or bool(os.environ.get('DISPLAY')))
118 119
        appcls = [QCoreApplication, QApplication][guienabled]
        self._qapp = appcls([])
120

121 122 123 124 125 126 127
        # settings will be saved at $HGTMP/.config/TortoiseHg/TortoiseHgQt.ini
        self._qapp.setApplicationName('TortoiseHgQt')
        self._qapp.setOrganizationName('TortoiseHg')
        QSettings.setDefaultFormat(QSettings.IniFormat)
        QSettings.setPath(QSettings.IniFormat, QSettings.UserScope,
                          self.configdir)

128
    def pytest_sessionfinish(self):
129 130
        del self._qapp

131 132
        if not self.keep_tmpdir:
            shutil.rmtree(self.tmpdir)