import os

from pki import nssdb

import nss.nss as nss
import pytest
import subprocess

@pytest.fixture
def nss_db(tmpdir):
    nss_db = tmpdir
    nss_db.pwd_file = tmpdir.join('passwd.txt')
    nss_db.pwd_file.write('secretpassword')

    nss_db.pki = tmpdir.mkdir('pki')

    subprocess.check_call([
        'certutil',
        '-d', 'dbm:{}'.format(nss_db.pki),
        '-N',
        '-f', nss_db.pwd_file,
    ])

    return nss_db


def test_missing_mod_spec(nss_db):
    init_flags = 0 | nss.NSS_INIT_NOROOTINIT | nss.NSS_INIT_NOMODDB
    context = nss.nss_init_context(
        cert_dir=str(nss_db.pki),
        flags=init_flags)
    context.shutdown()

    db = nssdb.NSSDatabase(str(nss_db.pki), password_file=nss_db.pwd_file)
    db.convert_db()
    expected_list = [
        'cert8.db.migrated', 'key3.db.migrated', 'secmod.db.migrated',
        'cert9.db', 'key4.db', 'pkcs11.txt']
    actual_list = list(
        map(lambda x: str(os.path.basename(x)), nss_db.pki.listdir()))
    assert sorted(actual_list) == sorted(expected_list)
