Search code examples
pythongnupg

Deleting keys using python-gnupg


Here's a quick test-case of my workflow:

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)

That final assert_equal(len(gpg.list_keys()), 0) raises an AssertionError.

What am I doing wrong?


Solution

  • You are deleting the secret key (you are calling delete_keys with secret=True), but you are examining the list of public keys. Consider:

    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)
    

    This generates no errors.