1"""PGPy conftest"""
2import pytest
3
4import glob
5try:
6    import gpg
7except ImportError:
8    gpg = None
9import os
10import sys
11
12from distutils.version import LooseVersion
13
14from cryptography.hazmat.backends import openssl
15
16openssl_ver = LooseVersion(openssl.backend.openssl_version_text().split(' ')[1])
17gpg_ver = LooseVersion('0')
18gnupghome = os.path.join(os.path.dirname(__file__), 'gnupghome')
19if gpg:
20    gpgme_ver = gpg.core.check_version()
21
22
23# ensure external commands we need to run exist
24
25# set the CWD and add to sys.path if we need to
26os.chdir(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir))
27
28if os.getcwd() not in sys.path:
29    sys.path.insert(0, os.getcwd())
30else:
31    sys.path.insert(0, sys.path.pop(sys.path.index(os.getcwd())))
32
33if os.path.join(os.getcwd(), 'tests') not in sys.path:
34    sys.path.insert(1, os.path.join(os.getcwd(), 'tests'))
35
36
37# pytest hooks
38
39# pytest_configure
40# called after command line options have been parsed and all plugins and initial conftest files been loaded.
41def pytest_configure(config):
42    print("== PGPy Test Suite ==")
43
44    if gpg:
45        # clear out gnupghome
46        clear_globs = [os.path.join(gnupghome, 'private-keys-v1.d', '*.key'),
47                       os.path.join(gnupghome, '*.kbx*'),
48                       os.path.join(gnupghome, '*.gpg*'),
49                       os.path.join(gnupghome, '.*'),
50                       os.path.join(gnupghome, 'random_seed')]
51        for fpath in iter(f for cg in clear_globs for f in glob.glob(cg)):
52            os.unlink(fpath)
53
54        # get the GnuPG version
55        gpg_ver.parse(gpg.core.get_engine_info()[0].version)
56
57        # check that there are no keys loaded, now
58        with gpg.Context(offline=True) as c:
59            c.set_engine_info(gpg.constants.PROTOCOL_OpenPGP, home_dir=gnupghome)
60
61            assert len(list(c.keylist())) == 0
62            assert len(list(c.keylist(secret=True))) == 0
63
64    else:
65        # we're not running integration tests
66        print("running without integration tests")
67        # if we're on Travis, this is an error
68        if os.getenv('TRAVIS_PYTHON_VERSION'):
69            sys.exit(1)
70
71    # display the working directory and the OpenSSL/GPG/pgpdump versions
72    print("Working Directory: " + os.getcwd())
73    print("Using OpenSSL " + str(openssl_ver))
74    print("Using GnuPG   " + str(gpg_ver))
75    print("")
76