import copy
import inspect
import json
import logging

import pytest
import re
import os
import shutil
import subprocess
import time

from datetime import datetime, timedelta
from configparser import ConfigParser, ExtendedInterpolation
from typing import Dict, List, Optional

from pyhttpd.certs import CertificateSpec
from .md_cert_util import MDCertUtil
from pyhttpd.env import HttpdTestSetup, HttpdTestEnv
from pyhttpd.result import ExecResult

log = logging.getLogger(__name__)


class MDTestSetup(HttpdTestSetup):

    def __init__(self, env: 'HttpdTestEnv'):
        super().__init__(env=env)

    def make(self):
        super().make(add_modules=["proxy_connect", "md"])
        if "pebble" == self.env.acme_server:
            self._make_pebble_conf()

    def _make_pebble_conf(self):
        our_dir = os.path.dirname(inspect.getfile(MDTestSetup))
        conf_src_dir = os.path.join(our_dir, 'pebble')
        conf_dest_dir = os.path.join(self.env.gen_dir, 'pebble')
        if not os.path.exists(conf_dest_dir):
            os.makedirs(conf_dest_dir)
        for name in os.listdir(conf_src_dir):
            src_path = os.path.join(conf_src_dir, name)
            m = re.match(r'(.+).template', name)
            if m:
                self._make_template(src_path, os.path.join(conf_dest_dir, m.group(1)))
            elif os.path.isfile(src_path):
                shutil.copy(src_path, os.path.join(conf_dest_dir, name))


class MDTestEnv(HttpdTestEnv):

    MD_S_UNKNOWN = 0
    MD_S_INCOMPLETE = 1
    MD_S_COMPLETE = 2
    MD_S_EXPIRED = 3
    MD_S_ERROR = 4

    EMPTY_JOUT = {'status': 0, 'output': []}

    DOMAIN_SUFFIX = "%d.org" % time.time()
    LOG_FMT_TIGHT = '%(levelname)s: %(message)s'

    @classmethod
    def get_acme_server(cls):
        return os.environ['ACME'] if 'ACME' in os.environ else "pebble"

    @classmethod
    def has_acme_server(cls):
        return cls.get_acme_server() != 'none'

    @classmethod
    def has_acme_eab(cls):
        return cls.get_acme_server() == 'pebble'

    @classmethod
    def is_pebble(cls) -> bool:
        return cls.get_acme_server() == 'pebble'

    @classmethod
    def lacks_ocsp(cls):
        return cls.is_pebble()

    def __init__(self, pytestconfig=None, setup_dirs=True):
        super().__init__(pytestconfig=pytestconfig,
                         local_dir=os.path.dirname(inspect.getfile(MDTestEnv)),
                         interesting_modules=["md"])
        self._acme_server = self.get_acme_server()
        self._acme_tos = "accepted"
        self._acme_ca_pemfile = os.path.join(self.gen_dir, "apache/acme-ca.pem")
        if "pebble" == self._acme_server:
            self._acme_url = "https://localhost:14000/dir"
            self._acme_eab_url = "https://localhost:14001/dir"
        elif "boulder" == self._acme_server:
            self._acme_url = "http://localhost:4001/directory"
            self._acme_eab_url = None
        else:
            raise Exception(f"unknown ACME server type: {self._acme_server}")
        self._acme_server_down = False
        self._acme_server_ok = False

        self._a2md_bin = os.path.join(self.bin_dir, 'a2md')
        self._default_domain = f"test1.{self.http_tld}"
        self._store_dir = "./md"
        self.set_store_dir_default()

        self.add_cert_specs([
            CertificateSpec(domains=[f"expired.{self._http_tld}"],
                            valid_from=timedelta(days=-100),
                            valid_to=timedelta(days=-10)),
            CertificateSpec(domains=["localhost"], key_type='rsa2048'),
        ])

        self.httpd_error_log.set_ignored_lognos([
            #"AH10045",  # mod_md complains that there is no vhost for an MDomain
            "AH10105",  # mod_md does not find a vhost with SSL enabled for an MDomain
            "AH10085"   # mod_ssl complains about fallback certificates
        ])
        if self.lacks_ocsp():
            self.httpd_error_log.set_ignored_patterns([
                re.compile(r'.*certificate with serial \S+ has no OCSP responder URL.*'),
            ])

        if setup_dirs:
            self._setup = MDTestSetup(env=self)
            self._setup.make()
            self.issue_certs()
            self.clear_store()

    def set_store_dir_default(self):
        dirpath = "md"
        if self.httpd_is_at_least("2.5.0"):
            dirpath = os.path.join("state", dirpath)
        self.set_store_dir(dirpath)

    def set_store_dir(self, dirpath):
        self._store_dir = os.path.join(self.server_dir, dirpath)
        if self.acme_url:
            self.a2md_stdargs([self.a2md_bin, "-a", self.acme_url, "-d", self._store_dir,  "-C", self.acme_ca_pemfile, "-j"])
            self.a2md_rawargs([self.a2md_bin, "-a", self.acme_url, "-d", self._store_dir,  "-C", self.acme_ca_pemfile])

    def get_apxs_var(self, name: str) -> str:
        p = subprocess.run([self._apxs, "-q", name], capture_output=True, text=True)
        if p.returncode != 0:
            return ""
        return p.stdout.strip()

    @property
    def acme_server(self):
        return self._acme_server

    @property
    def acme_url(self):
        return self._acme_url

    @property
    def acme_tos(self):
        return self._acme_tos

    @property
    def a2md_bin(self):
        return self._a2md_bin

    @property
    def acme_ca_pemfile(self):
        return self._acme_ca_pemfile

    @property
    def store_dir(self):
        return self._store_dir

    def get_request_domain(self, request):
        return "%s-%s" % (re.sub(r'[_]', '-', request.node.originalname), MDTestEnv.DOMAIN_SUFFIX)

    def get_method_domain(self, method):
        return "%s-%s" % (re.sub(r'[_]', '-', method.__name__.lower()), MDTestEnv.DOMAIN_SUFFIX)

    def get_module_domain(self, module):
        return "%s-%s" % (re.sub(r'[_]', '-', module.__name__.lower()), MDTestEnv.DOMAIN_SUFFIX)

    def get_class_domain(self, c):
        return "%s-%s" % (re.sub(r'[_]', '-', c.__name__.lower()), MDTestEnv.DOMAIN_SUFFIX)

    # --------- cmd execution ---------

    _a2md_args = []
    _a2md_args_raw = []

    def a2md_stdargs(self, args):
        self._a2md_args = [] + args

    def a2md_rawargs(self, args):
        self._a2md_args_raw = [] + args

    def a2md(self, args, raw=False) -> ExecResult:
        preargs = self._a2md_args
        if raw:
            preargs = self._a2md_args_raw
        log.debug("running: {0} {1}".format(preargs, args))
        return self.run(preargs + args)

    def check_acme(self):
        if self._acme_server_ok:
            return True
        if self._acme_server_down:
            pytest.skip(msg="ACME server not running")
            return False
        if self.is_live(self.acme_url, timeout=timedelta(seconds=0.5)):
            self._acme_server_ok = True
            return True
        else:
            self._acme_server_down = True
            pytest.fail(msg="ACME server not running", pytrace=False)
            return False

    def get_ca_pem_file(self, hostname: str) -> Optional[str]:
        pem_file = super().get_ca_pem_file(hostname)
        if pem_file is None:
            pem_file = self.acme_ca_pemfile
        return pem_file

    # --------- access local store ---------

    def purge_store(self):
        log.debug("purge store dir: %s" % self._store_dir)
        assert len(self._store_dir) > 1
        if os.path.exists(self._store_dir):
            shutil.rmtree(self._store_dir, ignore_errors=False)
        os.makedirs(self._store_dir)

    def clear_store(self):
        log.debug("clear store dir: %s" % self._store_dir)
        assert len(self._store_dir) > 1
        if not os.path.exists(self._store_dir):
            os.makedirs(self._store_dir)
        for dirpath in ["challenges", "tmp", "archive", "domains", "accounts", "staging", "ocsp"]:
            shutil.rmtree(os.path.join(self._store_dir, dirpath), ignore_errors=True)

    def clear_ocsp_store(self):
        assert len(self._store_dir) > 1
        dirpath = os.path.join(self._store_dir, "ocsp")
        log.debug("clear ocsp store dir: %s" % dir)
        if os.path.exists(dirpath):
            shutil.rmtree(dirpath, ignore_errors=True)

    def authz_save(self, name, content):
        dirpath = os.path.join(self._store_dir, 'staging', name)
        os.makedirs(dirpath)
        open(os.path.join(dirpath, 'authz.json'), "w").write(content)

    def path_store_json(self):
        return os.path.join(self._store_dir, 'md_store.json')

    def path_account(self, acct):
        return os.path.join(self._store_dir, 'accounts', acct, 'account.json')

    def path_account_key(self, acct):
        return os.path.join(self._store_dir, 'accounts', acct, 'account.pem')

    def store_domains(self):
        return os.path.join(self._store_dir, 'domains')

    def store_archives(self):
        return os.path.join(self._store_dir, 'archive')

    def store_stagings(self):
        return os.path.join(self._store_dir, 'staging')

    def store_challenges(self):
        return os.path.join(self._store_dir, 'challenges')

    def store_domain_file(self, domain, filename):
        return os.path.join(self.store_domains(), domain, filename)

    def store_archived_file(self, domain, version, filename):
        return os.path.join(self.store_archives(), "%s.%d" % (domain, version), filename)

    def store_staged_file(self, domain, filename):
        return os.path.join(self.store_stagings(), domain, filename)

    def path_fallback_cert(self, domain):
        return os.path.join(self._store_dir, 'domains', domain, 'fallback-pubcert.pem')

    def path_job(self, domain):
        return os.path.join(self._store_dir, 'staging', domain, 'job.json')

    def replace_store(self, src):
        shutil.rmtree(self._store_dir, ignore_errors=False)
        shutil.copytree(src, self._store_dir)

    def list_accounts(self):
        return os.listdir(os.path.join(self._store_dir, 'accounts'))

    def check_md(self, domain, md=None, state=-1, ca=None, protocol=None, agreement=None, contacts=None):
        domains = None
        if isinstance(domain, list):
            domains = domain
            domain = domains[0]
        if md:
            domain = md
        path = self.store_domain_file(domain, 'md.json')
        with open(path) as f:
            md = json.load(f)
        assert md
        if domains:
            assert md['domains'] == domains
        if state >= 0:
            assert md['state'] == state
        if ca:
            assert md['ca']['url'] == ca
        if protocol:
            assert md['ca']['proto'] == protocol
        if agreement:
            assert md['ca']['agreement'] == agreement
        if contacts:
            assert md['contacts'] == contacts

    def pkey_fname(self, pkeyspec=None):
        if pkeyspec and not re.match(r'^rsa( ?\d+)?$', pkeyspec.lower()):
            return "privkey.{0}.pem".format(pkeyspec)
        return 'privkey.pem'

    def cert_fname(self, pkeyspec=None):
        if pkeyspec and not re.match(r'^rsa( ?\d+)?$', pkeyspec.lower()):
            return "pubcert.{0}.pem".format(pkeyspec)
        return 'pubcert.pem'

    def check_md_complete(self, domain, pkey=None):
        md = self.get_md_status(domain)
        assert md
        assert 'state' in md, "md is unexpected: {0}".format(md)
        assert md['state'] is MDTestEnv.MD_S_COMPLETE, "unexpected state: {0}".format(md['state'])
        assert os.path.isfile(self.store_domain_file(domain, self.pkey_fname(pkey)))
        assert os.path.isfile(self.store_domain_file(domain, self.cert_fname(pkey)))

    def check_md_credentials(self, domain):
        if isinstance(domain, list):
            domains = domain
            domain = domains[0]
        else:
            domains = [domain]
        # check private key, validate certificate, etc
        MDCertUtil.validate_privkey(self.store_domain_file(domain, 'privkey.pem'))
        cert = MDCertUtil(self.store_domain_file(domain, 'pubcert.pem'))
        cert.validate_cert_matches_priv_key(self.store_domain_file(domain, 'privkey.pem'))
        # check SANs and CN
        assert cert.get_cn() == domain
        # compare lists twice in opposite directions: SAN may not respect ordering
        san_list = list(cert.get_san_list())
        assert len(san_list) == len(domains)
        assert set(san_list).issubset(domains)
        assert set(domains).issubset(san_list)
        # check valid dates interval
        not_before = cert.get_not_before()
        not_after = cert.get_not_after()
        assert not_before < datetime.now(not_before.tzinfo)
        assert not_after > datetime.now(not_after.tzinfo)

    # --------- check utilities ---------

    def check_json_contains(self, actual, expected):
        # write all expected key:value bindings to a copy of the actual data ... 
        # ... assert it stays unchanged 
        test_json = copy.deepcopy(actual)
        test_json.update(expected)
        assert actual == test_json

    def check_file_access(self, path, exp_mask):
        actual_mask = os.lstat(path).st_mode & 0o777
        assert oct(actual_mask) == oct(exp_mask)

    def check_dir_empty(self, path):
        assert os.listdir(path) == []

    def get_http_status(self, domain, path, use_https=True):
        r = self.get_meta(domain, path, use_https, insecure=True)
        return r.response['status']

    def get_cert(self, domain, tls=None, ciphers=None):
        return MDCertUtil.load_server_cert(self._httpd_addr, self.https_port,
                                           domain, tls=tls, ciphers=ciphers)

    def get_server_cert(self, domain, proto=None, ciphers=None):
        args = [
            "openssl", "s_client", "-status",
            "-connect", "%s:%s" % (self._httpd_addr, self.https_port),
            "-CAfile", self.acme_ca_pemfile,
            "-servername", domain,
            "-showcerts"
        ]
        if proto is not None:
            args.extend(["-{0}".format(proto)])
        if ciphers is not None:
            args.extend(["-cipher", ciphers])
        r = self.run(args)
        # noinspection PyBroadException
        try:
            return MDCertUtil.parse_pem_cert(r.stdout)
        except:
            return None

    def verify_cert_key_lenghts(self, domain, pkeys):
        for p in pkeys:
            cert = self.get_server_cert(domain, proto="tls1_2", ciphers=p['ciphers'])
            if 0 == p['keylen']:
                assert cert is None
            else:
                assert cert, "no cert returned for cipher: {0}".format(p['ciphers'])
                assert cert.get_key_length() == p['keylen'], "key length, expected {0}, got {1}".format(
                    p['keylen'], cert.get_key_length()
                )

    def get_meta(self, domain, path, use_https=True, insecure=False):
        schema = "https" if use_https else "http"
        port = self.https_port if use_https else self.http_port
        r = self.curl_get(f"{schema}://{domain}:{port}{path}", insecure=insecure)
        assert r.exit_code == 0
        assert r.response
        assert r.response['header']
        return r

    def get_content(self, domain, path, use_https=True):
        schema = "https" if use_https else "http"
        port = self.https_port if use_https else self.http_port
        r = self.curl_get(f"{schema}://{domain}:{port}{path}")
        assert r.exit_code == 0
        return r.stdout

    def get_json_content(self, domain, path, use_https=True, insecure=False,
                         debug_log=True):
        schema = "https" if use_https else "http"
        port = self.https_port if use_https else self.http_port
        url = f"{schema}://{domain}:{port}{path}"
        r = self.curl_get(url, insecure=insecure, debug_log=debug_log)
        if r.exit_code != 0:
            log.error(f"curl get on {url} returned {r.exit_code}"
                      f"\nstdout: {r.stdout}"
                      f"\nstderr: {r.stderr}")
        assert r.exit_code == 0, r.stderr
        return r.json

    def get_certificate_status(self, domain) -> Dict:
        return self.get_json_content(domain, "/.httpd/certificate-status", insecure=True)

    def get_md_status(self, domain, via_domain=None, use_https=True, debug_log=False) -> Dict:
        if via_domain is None:
            via_domain = self._default_domain
        return self.get_json_content(via_domain, f"/md-status/{domain}",
                                     use_https=use_https, debug_log=debug_log)

    def get_server_status(self, query="/", via_domain=None, use_https=True):
        if via_domain is None:
            via_domain = self._default_domain
        return self.get_content(via_domain, "/server-status%s" % query, use_https=use_https)

    def await_completion(self, names, must_renew=False, restart=True, timeout=60,
                         via_domain=None, use_https=True):
        try_until = time.time() + timeout
        renewals = {}
        names = names.copy()
        while len(names) > 0:
            if time.time() >= try_until:
                return False
            for name in names:
                mds = self.get_md_status(name, via_domain=via_domain, use_https=use_https)
                if mds is None:
                    log.debug("not managed by md: %s" % name)
                    return False

                if 'renewal' in mds:
                    renewal = mds['renewal']
                    renewals[name] = True
                    if 'finished' in renewal and renewal['finished'] is True:
                        if (not must_renew) or (name in renewals):
                            log.debug(f"domain cert was renewed: {name}")
                            names.remove(name)

            if len(names) != 0:
                time.sleep(0.1)
        if restart:
            time.sleep(0.1)
            return self.apache_restart() == 0
        return True

    def is_renewing(self, name):
        stat = self.get_certificate_status(name)
        return 'renewal' in stat

    def await_renewal(self, names, timeout=60):
        try_until = time.time() + timeout
        while len(names) > 0:
            if time.time() >= try_until:
                return False
            for name in names:
                md = self.get_md_status(name)
                if md is None:
                    log.debug("not managed by md: %s" % name)
                    return False

                if 'renewal' in md:
                    names.remove(name)

            if len(names) != 0:
                time.sleep(0.1)
        return True

    def await_error(self, domain, timeout=60, via_domain=None, use_https=True, errors=1):
        try_until = time.time() + timeout
        while True:
            if time.time() >= try_until:
                return False
            md = self.get_md_status(domain, via_domain=via_domain, use_https=use_https)
            if md:
                if 'state' in md and md['state'] == MDTestEnv.MD_S_ERROR:
                    return md
                if 'renewal' in md and 'errors' in md['renewal'] \
                        and md['renewal']['errors'] >= errors:
                    return md
            time.sleep(0.1)
        return None

    def await_file(self, fpath, timeout=60):
        try_until = time.time() + timeout
        while True:
            if time.time() >= try_until:
                return False
            if os.path.isfile(fpath):
                return True
            time.sleep(0.1)

    def check_file_permissions(self, domain):
        md = self.a2md(["list", domain]).json['output'][0]
        assert md
        acct = md['ca']['account']
        assert acct
        self.check_file_access(self.path_store_json(), 0o600)
        # domains
        self.check_file_access(self.store_domains(), 0o700)
        self.check_file_access(os.path.join(self.store_domains(), domain), 0o700)
        self.check_file_access(self.store_domain_file(domain, 'privkey.pem'), 0o600)
        self.check_file_access(self.store_domain_file(domain, 'pubcert.pem'), 0o600)
        self.check_file_access(self.store_domain_file(domain, 'md.json'), 0o600)
        # archive
        self.check_file_access(self.store_archived_file(domain, 1, 'md.json'), 0o600)
        # accounts
        self.check_file_access(os.path.join(self._store_dir, 'accounts'), 0o755)
        self.check_file_access(os.path.join(self._store_dir, 'accounts', acct), 0o755)
        self.check_file_access(self.path_account(acct), 0o644)
        self.check_file_access(self.path_account_key(acct), 0o644)
        # staging
        self.check_file_access(self.store_stagings(), 0o755)

    def get_ocsp_status(self, domain, proto=None, cipher=None, ca_file=None):
        stat = {}
        args = [
            "openssl", "s_client", "-status",
            "-connect", "%s:%s" % (self._httpd_addr, self.https_port),
            "-CAfile", ca_file if ca_file else self.acme_ca_pemfile,
            "-servername", domain,
            "-showcerts"
        ]
        if proto is not None:
            args.extend(["-{0}".format(proto)])
        if cipher is not None:
            args.extend(["-cipher", cipher])
        r = self.run(args, debug_log=False)
        ocsp_regex = re.compile(r'OCSP response: +([^=\n]+)\n')
        matches = ocsp_regex.finditer(r.stdout)
        for m in matches:
            if m.group(1) != "":
                stat['ocsp'] = m.group(1)
        if 'ocsp' not in stat:
            ocsp_regex = re.compile(r'OCSP Response Status:\s*(.+)')
            matches = ocsp_regex.finditer(r.stdout)
            for m in matches:
                if m.group(1) != "":
                    stat['ocsp'] = m.group(1)
        verify_regex = re.compile(r'Verify return code:\s*(.+)')
        matches = verify_regex.finditer(r.stdout)
        for m in matches:
            if m.group(1) != "":
                stat['verify'] = m.group(1)
        return stat

    def await_ocsp_status(self, domain, timeout=10, ca_file=None):
        try_until = time.time() + timeout
        while True:
            if time.time() >= try_until:
                break
            stat = self.get_ocsp_status(domain, ca_file=ca_file)
            if 'ocsp' in stat and stat['ocsp'] != "no response sent":
                return stat
            time.sleep(0.1)
        raise TimeoutError(f"ocsp respopnse not available: {domain}")

    def create_self_signed_cert(self, name_list, valid_days, serial=1000, path=None):
        dirpath = path
        if not path:
            dirpath = os.path.join(self.store_domains(), name_list[0])
        return MDCertUtil.create_self_signed_cert(dirpath, name_list, valid_days, serial)
[((22, 6, 22, 33), 'logging.getLogger', 'logging.getLogger', ({(22, 24, 22, 32): '__name__'}, {}), '(__name__)', False, 'import logging\n'), ((37, 23, 37, 54), 'os.path.join', 'os.path.join', ({(37, 36, 37, 43): 'our_dir', (37, 45, 37, 53): '"""pebble"""'}, {}), "(our_dir, 'pebble')", False, 'import os\n'), ((38, 24, 38, 64), 'os.path.join', 'os.path.join', ({(38, 37, 38, 53): 'self.env.gen_dir', (38, 55, 38, 63): '"""pebble"""'}, {}), "(self.env.gen_dir, 'pebble')", False, 'import os\n'), ((41, 20, 41, 44), 'os.listdir', 'os.listdir', ({(41, 31, 41, 43): 'conf_src_dir'}, {}), '(conf_src_dir)', False, 'import os\n'), ((60, 31, 60, 42), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((89, 32, 89, 80), 'os.path.join', 'os.path.join', ({(89, 45, 89, 57): 'self.gen_dir', (89, 59, 89, 79): '"""apache/acme-ca.pem"""'}, {}), "(self.gen_dir, 'apache/acme-ca.pem')", False, 'import os\n'), ((101, 25, 101, 59), 'os.path.join', 'os.path.join', ({(101, 38, 101, 50): 'self.bin_dir', (101, 52, 101, 58): '"""a2md"""'}, {}), "(self.bin_dir, 'a2md')", False, 'import os\n'), ((136, 26, 136, 64), 'os.path.join', 'os.path.join', ({(136, 39, 136, 54): 'self.server_dir', (136, 56, 136, 63): 'dirpath'}, {}), '(self.server_dir, dirpath)', False, 'import os\n'), ((142, 12, 142, 84), 'subprocess.run', 'subprocess.run', (), '', False, 'import subprocess\n'), ((226, 11, 226, 42), 'os.path.exists', 'os.path.exists', ({(226, 26, 226, 41): 'self._store_dir'}, {}), '(self._store_dir)', False, 'import os\n'), ((228, 8, 228, 36), 'os.makedirs', 'os.makedirs', ({(228, 20, 228, 35): 'self._store_dir'}, {}), '(self._store_dir)', False, 'import os\n'), ((240, 18, 240, 55), 'os.path.join', 'os.path.join', ({(240, 31, 240, 46): 'self._store_dir', (240, 48, 240, 54): '"""ocsp"""'}, {}), "(self._store_dir, 'ocsp')", False, 'import os\n'), ((242, 11, 242, 34), 'os.path.exists', 'os.path.exists', ({(242, 26, 242, 33): 'dirpath'}, {}), '(dirpath)', False, 'import os\n'), ((246, 18, 246, 64), 'os.path.join', 'os.path.join', ({(246, 31, 246, 46): 'self._store_dir', (246, 48, 246, 57): '"""staging"""', (246, 59, 246, 63): 'name'}, {}), "(self._store_dir, 'staging', name)", False, 'import os\n'), ((247, 8, 247, 28), 'os.makedirs', 'os.makedirs', ({(247, 20, 247, 27): 'dirpath'}, {}), '(dirpath)', False, 'import os\n'), ((251, 15, 251, 61), 'os.path.join', 'os.path.join', ({(251, 28, 251, 43): 'self._store_dir', (251, 45, 251, 60): '"""md_store.json"""'}, {}), "(self._store_dir, 'md_store.json')", False, 'import os\n'), ((254, 15, 254, 78), 'os.path.join', 'os.path.join', ({(254, 28, 254, 43): 'self._store_dir', (254, 45, 254, 55): '"""accounts"""', (254, 57, 254, 61): 'acct', (254, 63, 254, 77): '"""account.json"""'}, {}), "(self._store_dir, 'accounts', acct, 'account.json')", False, 'import os\n'), ((257, 15, 257, 77), 'os.path.join', 'os.path.join', ({(257, 28, 257, 43): 'self._store_dir', (257, 45, 257, 55): '"""accounts"""', (257, 57, 257, 61): 'acct', (257, 63, 257, 76): '"""account.pem"""'}, {}), "(self._store_dir, 'accounts', acct, 'account.pem')", False, 'import os\n'), ((260, 15, 260, 55), 'os.path.join', 'os.path.join', ({(260, 28, 260, 43): 'self._store_dir', (260, 45, 260, 54): '"""domains"""'}, {}), "(self._store_dir, 'domains')", False, 'import os\n'), ((263, 15, 263, 55), 'os.path.join', 'os.path.join', ({(263, 28, 263, 43): 'self._store_dir', (263, 45, 263, 54): '"""archive"""'}, {}), "(self._store_dir, 'archive')", False, 'import os\n'), ((266, 15, 266, 55), 'os.path.join', 'os.path.join', ({(266, 28, 266, 43): 'self._store_dir', (266, 45, 266, 54): '"""staging"""'}, {}), "(self._store_dir, 'staging')", False, 'import os\n'), ((269, 15, 269, 58), 'os.path.join', 'os.path.join', ({(269, 28, 269, 43): 'self._store_dir', (269, 45, 269, 57): '"""challenges"""'}, {}), "(self._store_dir, 'challenges')", False, 'import os\n'), ((281, 15, 281, 87), 'os.path.join', 'os.path.join', ({(281, 28, 281, 43): 'self._store_dir', (281, 45, 281, 54): '"""domains"""', (281, 56, 281, 62): 'domain', (281, 64, 281, 86): '"""fallback-pubcert.pem"""'}, {}), "(self._store_dir, 'domains', domain, 'fallback-pubcert.pem')", False, 'import os\n'), ((284, 15, 284, 75), 'os.path.join', 'os.path.join', ({(284, 28, 284, 43): 'self._store_dir', (284, 45, 284, 54): '"""staging"""', (284, 56, 284, 62): 'domain', (284, 64, 284, 74): '"""job.json"""'}, {}), "(self._store_dir, 'staging', domain, 'job.json')", False, 'import os\n'), ((287, 8, 287, 59), 'shutil.rmtree', 'shutil.rmtree', (), '', False, 'import shutil\n'), ((288, 8, 288, 45), 'shutil.copytree', 'shutil.copytree', ({(288, 24, 288, 27): 'src', (288, 29, 288, 44): 'self._store_dir'}, {}), '(src, self._store_dir)', False, 'import shutil\n'), ((363, 20, 363, 41), 'copy.deepcopy', 'copy.deepcopy', ({(363, 34, 363, 40): 'actual'}, {}), '(actual)', False, 'import copy\n'), ((566, 21, 566, 63), 're.compile', 're.compile', ({(566, 32, 566, 62): '"""OCSP response: +([^=\\\\n]+)\\\\n"""'}, {}), "('OCSP response: +([^=\\\\n]+)\\\\n')", False, 'import re\n'), ((577, 23, 577, 64), 're.compile', 're.compile', ({(577, 34, 577, 63): '"""Verify return code:\\\\s*(.+)"""'}, {}), "('Verify return code:\\\\s*(.+)')", False, 'import re\n'), ((36, 34, 36, 62), 'inspect.getfile', 'inspect.getfile', ({(36, 50, 36, 61): 'MDTestSetup'}, {}), '(MDTestSetup)', False, 'import inspect\n'), ((39, 15, 39, 44), 'os.path.exists', 'os.path.exists', ({(39, 30, 39, 43): 'conf_dest_dir'}, {}), '(conf_dest_dir)', False, 'import os\n'), ((40, 12, 40, 38), 'os.makedirs', 'os.makedirs', ({(40, 24, 40, 37): 'conf_dest_dir'}, {}), '(conf_dest_dir)', False, 'import os\n'), ((42, 23, 42, 55), 'os.path.join', 'os.path.join', ({(42, 36, 42, 48): 'conf_src_dir', (42, 50, 42, 54): 'name'}, {}), '(conf_src_dir, name)', False, 'import os\n'), ((43, 16, 43, 48), 're.match', 're.match', ({(43, 25, 43, 41): '"""(.+).template"""', (43, 43, 43, 47): 'name'}, {}), "('(.+).template', name)", False, 'import re\n'), ((132, 22, 132, 52), 'os.path.join', 'os.path.join', ({(132, 35, 132, 42): '"""state"""', (132, 44, 132, 51): 'dirpath'}, {}), "('state', dirpath)", False, 'import os\n'), ((205, 12, 205, 54), 'pytest.skip', 'pytest.skip', (), '', False, 'import pytest\n'), ((212, 12, 212, 69), 'pytest.fail', 'pytest.fail', (), '', False, 'import pytest\n'), ((227, 12, 227, 63), 'shutil.rmtree', 'shutil.rmtree', (), '', False, 'import shutil\n'), ((233, 15, 233, 46), 'os.path.exists', 'os.path.exists', ({(233, 30, 233, 45): 'self._store_dir'}, {}), '(self._store_dir)', False, 'import os\n'), ((234, 12, 234, 40), 'os.makedirs', 'os.makedirs', ({(234, 24, 234, 39): 'self._store_dir'}, {}), '(self._store_dir)', False, 'import os\n'), ((243, 12, 243, 54), 'shutil.rmtree', 'shutil.rmtree', (), '', False, 'import shutil\n'), ((291, 26, 291, 67), 'os.path.join', 'os.path.join', ({(291, 39, 291, 54): 'self._store_dir', (291, 56, 291, 66): '"""accounts"""'}, {}), "(self._store_dir, 'accounts')", False, 'import os\n'), ((302, 17, 302, 29), 'json.load', 'json.load', ({(302, 27, 302, 28): 'f'}, {}), '(f)', False, 'import json\n'), ((355, 28, 355, 59), 'datetime.datetime.now', 'datetime.now', ({(355, 41, 355, 58): 'not_before.tzinfo'}, {}), '(not_before.tzinfo)', False, 'from datetime import datetime, timedelta\n'), ((356, 27, 356, 57), 'datetime.datetime.now', 'datetime.now', ({(356, 40, 356, 56): 'not_after.tzinfo'}, {}), '(not_after.tzinfo)', False, 'from datetime import datetime, timedelta\n'), ((372, 15, 372, 31), 'os.listdir', 'os.listdir', ({(372, 26, 372, 30): 'path'}, {}), '(path)', False, 'import os\n'), ((457, 20, 457, 31), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((480, 12, 480, 27), 'time.sleep', 'time.sleep', ({(480, 23, 480, 26): '(0.1)'}, {}), '(0.1)', False, 'import time\n'), ((489, 20, 489, 31), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((507, 20, 507, 31), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((518, 12, 518, 27), 'time.sleep', 'time.sleep', ({(518, 23, 518, 26): '(0.1)'}, {}), '(0.1)', False, 'import time\n'), ((522, 20, 522, 31), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((526, 15, 526, 36), 'os.path.isfile', 'os.path.isfile', ({(526, 30, 526, 35): 'fpath'}, {}), '(fpath)', False, 'import os\n'), ((528, 12, 528, 27), 'time.sleep', 'time.sleep', ({(528, 23, 528, 26): '(0.1)'}, {}), '(0.1)', False, 'import time\n'), ((545, 31, 545, 72), 'os.path.join', 'os.path.join', ({(545, 44, 545, 59): 'self._store_dir', (545, 61, 545, 71): '"""accounts"""'}, {}), "(self._store_dir, 'accounts')", False, 'import os\n'), ((546, 31, 546, 78), 'os.path.join', 'os.path.join', ({(546, 44, 546, 59): 'self._store_dir', (546, 61, 546, 71): '"""accounts"""', (546, 73, 546, 77): 'acct'}, {}), "(self._store_dir, 'accounts', acct)", False, 'import os\n'), ((572, 25, 572, 68), 're.compile', 're.compile', ({(572, 36, 572, 67): '"""OCSP Response Status:\\\\s*(.+)"""'}, {}), "('OCSP Response Status:\\\\s*(.+)')", False, 'import re\n'), ((585, 20, 585, 31), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((592, 12, 592, 27), 'time.sleep', 'time.sleep', ({(592, 23, 592, 26): '(0.1)'}, {}), '(0.1)', False, 'import time\n'), ((46, 17, 46, 41), 'os.path.isfile', 'os.path.isfile', ({(46, 32, 46, 40): 'src_path'}, {}), '(src_path)', False, 'import os\n'), ((110, 12, 110, 70), 'pyhttpd.certs.CertificateSpec', 'CertificateSpec', (), '', False, 'from pyhttpd.certs import CertificateSpec\n'), ((172, 26, 172, 72), 're.sub', 're.sub', ({(172, 33, 172, 39): '"""[_]"""', (172, 41, 172, 44): '"""-"""', (172, 46, 172, 71): 'request.node.originalname'}, {}), "('[_]', '-', request.node.originalname)", False, 'import re\n'), ((207, 47, 207, 69), 'datetime.timedelta', 'timedelta', (), '', False, 'from datetime import datetime, timedelta\n'), ((236, 26, 236, 64), 'os.path.join', 'os.path.join', ({(236, 39, 236, 54): 'self._store_dir', (236, 56, 236, 63): 'dirpath'}, {}), '(self._store_dir, dirpath)', False, 'import os\n'), ((368, 22, 368, 36), 'os.lstat', 'os.lstat', ({(368, 31, 368, 35): 'path'}, {}), '(path)', False, 'import os\n'), ((461, 15, 461, 26), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((478, 16, 478, 31), 'time.sleep', 'time.sleep', ({(478, 27, 478, 30): '(0.1)'}, {}), '(0.1)', False, 'import time\n'), ((491, 15, 491, 26), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((503, 16, 503, 31), 'time.sleep', 'time.sleep', ({(503, 27, 503, 30): '(0.1)'}, {}), '(0.1)', False, 'import time\n'), ((509, 15, 509, 26), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((524, 15, 524, 26), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((587, 15, 587, 26), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((85, 51, 85, 77), 'inspect.getfile', 'inspect.getfile', ({(85, 67, 85, 76): 'MDTestEnv'}, {}), '(MDTestEnv)', False, 'import inspect\n'), ((120, 16, 120, 88), 're.compile', 're.compile', ({(120, 27, 120, 87): '""".*certificate with serial \\\\S+ has no OCSP responder URL.*"""'}, {}), "('.*certificate with serial \\\\S+ has no OCSP responder URL.*')", False, 'import re\n'), ((248, 13, 248, 48), 'os.path.join', 'os.path.join', ({(248, 26, 248, 33): 'dirpath', (248, 35, 248, 47): '"""authz.json"""'}, {}), "(dirpath, 'authz.json')", False, 'import os\n'), ((47, 38, 47, 71), 'os.path.join', 'os.path.join', ({(47, 51, 47, 64): 'conf_dest_dir', (47, 66, 47, 70): 'name'}, {}), '(conf_dest_dir, name)', False, 'import os\n'), ((108, 39, 108, 59), 'datetime.timedelta', 'timedelta', (), '', False, 'from datetime import datetime, timedelta\n'), ((109, 37, 109, 56), 'datetime.timedelta', 'timedelta', (), '', False, 'from datetime import datetime, timedelta\n')]