使用 python-gnupg 删除密钥

Deleting keys using python-gnupg

这是我的工作流程的快速测试用例:

from tempfile import gettempdir
from os import path
from shutil import rmtree

from gnupg import GPG

gnupghome = path.join(gettempdir(), 'foo')
gpg = GPG(gnupghome=gnupghome)
gpg.encoding = 'utf-8'


def raise_f(error):
    raise error


assert_equal = lambda first, second: first == second or raise_f(
    AssertionError('Expected {first!r} to be {second!r}'.format(
        first=first, second=second)
    )
)

try:
    assert_equal(len(gpg.list_keys()), 0)
    key = gpg.gen_key(
        gpg.gen_key_input(key_type='RSA', key_length=2048, name_real=u'foo')
    )
    assert gpg.export_keys(key.fingerprint).startswith(
        '-----BEGIN PGP PUBLIC KEY BLOCK-----'
    )
    assert_equal(len(gpg.list_keys()), 1)
    assert_equal(
        gpg.delete_keys(fingerprints=key.fingerprint, secret=True).status, 'ok')
    assert_equal(len(gpg.list_keys()), 0)
finally:
    rmtree(gnupghome)

最终 assert_equal(len(gpg.list_keys()), 0) 引发了 AssertionError

我做错了什么?

您正在删除密钥(您正在使用 secret=True 调用 delete_keys),但您正在检查 public 的列表键。考虑:

assert_equal(len(gpg.list_keys(secret=True)), 1)
assert_equal(gpg.delete_keys(fingerprints=key.fingerprint,
                             secret=True).status, 'ok')
assert_equal(len(gpg.list_keys(secret=True)), 0)

这不会产生任何错误。