Python bindings tests: Near PEP8 compliance

* PEP8 compliance for the vast majoeity of the tests.
This commit is contained in:
Ben McGinnes 2018-08-18 20:29:14 +10:00
parent b5fbe90676
commit 5facba45c8
31 changed files with 771 additions and 498 deletions

View File

@ -18,12 +18,15 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import os import os
import subprocess import subprocess
import support import support
_ = support # to appease pyflakes. _ = support # to appease pyflakes.
subprocess.check_call([os.path.join(os.getenv('top_srcdir'), del absolute_import, print_function, unicode_literals
"tests", "start-stop-agent"), "--stop"])
subprocess.check_call([
os.path.join(os.getenv('top_srcdir'), "tests", "start-stop-agent"),
"--stop"
])

View File

@ -18,17 +18,20 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import os import os
import subprocess import subprocess
import gpg import gpg
import support import support
del absolute_import, print_function, unicode_literals
print("Using gpg module from {0!r}.".format(os.path.dirname(gpg.__file__))) print("Using gpg module from {0!r}.".format(os.path.dirname(gpg.__file__)))
subprocess.check_call([os.path.join(os.getenv('top_srcdir'), subprocess.check_call([
"tests", "start-stop-agent"), "--start"]) os.path.join(os.getenv('top_srcdir'), "tests", "start-stop-agent"),
"--start"
])
with gpg.Context() as c: with gpg.Context() as c:
alpha = c.get_key("A0FF4590BB6122EDEF6E3C542D727CC768697734", False) alpha = c.get_key("A0FF4590BB6122EDEF6E3C542D727CC768697734", False)

View File

@ -17,10 +17,8 @@
# You should have received a copy of the GNU Lesser General Public # You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import from __future__ import absolute_import, division
from __future__ import division from __future__ import print_function, unicode_literals
from __future__ import print_function
from __future__ import unicode_literals
import argparse import argparse
import glob import glob
@ -28,34 +26,50 @@ import os
import subprocess import subprocess
import sys import sys
del absolute_import, division, print_function, unicode_literals
class SplitAndAccumulate(argparse.Action): class SplitAndAccumulate(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None): def __call__(self, parser, namespace, values, option_string=None):
current = getattr(namespace, self.dest, list()) current = getattr(namespace, self.dest, list())
current.extend(values.split()) current.extend(values.split())
setattr(namespace, self.dest, current) setattr(namespace, self.dest, current)
parser = argparse.ArgumentParser(description='Run tests.') parser = argparse.ArgumentParser(description='Run tests.')
parser.add_argument('tests', metavar='TEST', type=str, nargs='+', parser.add_argument(
help='A test to run') 'tests', metavar='TEST', type=str, nargs='+', help='A test to run')
parser.add_argument('-v', '--verbose', action="store_true", default=False, parser.add_argument(
help='Be verbose.') '-v', '--verbose', action="store_true", default=False, help='Be verbose.')
parser.add_argument('-q', '--quiet', action="store_true", default=False, parser.add_argument(
help='Be quiet.') '-q', '--quiet', action="store_true", default=False, help='Be quiet.')
parser.add_argument('--interpreters', metavar='PYTHON', type=str, parser.add_argument(
default=[], action=SplitAndAccumulate, '--interpreters',
help='Use these interpreters to run the tests, ' + metavar='PYTHON',
'separated by spaces.') type=str,
parser.add_argument('--srcdir', type=str, default=[],
default=os.environ.get("srcdir", ""), action=SplitAndAccumulate,
help='Location of the tests.') help='Use these interpreters to run the tests, ' + 'separated by spaces.')
parser.add_argument('--builddir', type=str, parser.add_argument(
default=os.environ.get("abs_builddir", ""), '--srcdir',
help='Location of the tests.') type=str,
parser.add_argument('--python-libdir', type=str, default=os.environ.get("srcdir", ""),
default=None, help='Location of the tests.')
help='Optional location of the in-tree module lib directory.') parser.add_argument(
parser.add_argument('--parallel', action="store_true", default=False, '--builddir',
help='Ignored. For compatibility with run-tests.scm.') type=str,
default=os.environ.get("abs_builddir", ""),
help='Location of the tests.')
parser.add_argument(
'--python-libdir',
type=str,
default=None,
help='Optional location of the in-tree module lib directory.')
parser.add_argument(
'--parallel',
action="store_true",
default=False,
help='Ignored. For compatibility with run-tests.scm.')
args = parser.parse_args() args = parser.parse_args()
if not args.interpreters: if not args.interpreters:
@ -64,26 +78,31 @@ if not args.interpreters:
out = sys.stdout if args.verbose else None out = sys.stdout if args.verbose else None
err = sys.stderr if args.verbose else None err = sys.stderr if args.verbose else None
def status_to_str(code): def status_to_str(code):
return {0: "PASS", 77: "SKIP", 99: "ERROR"}.get(code, "FAIL") return {0: "PASS", 77: "SKIP", 99: "ERROR"}.get(code, "FAIL")
results = list() results = list()
for interpreter in args.interpreters: for interpreter in args.interpreters:
version = subprocess.check_output( version = subprocess.check_output([
[interpreter, "-c", "import sys; print('{0}.{1}'.format(sys.version_info[0], sys.version_info[1]))"]).strip().decode() interpreter, "-c",
"import sys; print('{0}.{1}'.format(sys.version_info[0], sys.version_info[1]))"
]).strip().decode()
if args.python_libdir: if args.python_libdir:
python_libdir = args.python_libdir python_libdir = args.python_libdir
else: else:
pattern = os.path.join(args.builddir, "..", pattern = os.path.join(args.builddir, "..", "{0}-gpg".format(
"{0}-gpg".format(os.path.basename(interpreter)), os.path.basename(interpreter)), "lib*")
"lib*")
libdirs = glob.glob(pattern) libdirs = glob.glob(pattern)
if len(libdirs) == 0: if len(libdirs) == 0:
sys.exit("Build directory matching {0!r} not found.".format(pattern)) sys.exit(
"Build directory matching {0!r} not found.".format(pattern))
elif len(libdirs) > 1: elif len(libdirs) > 1:
sys.exit("Multiple build directories matching {0!r} found: {1}".format( sys.exit(
pattern, libdirs)) "Multiple build directories matching {0!r} found: {1}".format(
pattern, libdirs))
python_libdir = libdirs[0] python_libdir = libdirs[0]
env = dict(os.environ) env = dict(os.environ)
@ -95,16 +114,22 @@ for interpreter in args.interpreters:
for test in args.tests: for test in args.tests:
status = subprocess.call( status = subprocess.call(
[interpreter, os.path.join(args.srcdir, test)], [interpreter, os.path.join(args.srcdir, test)],
env=env, stdout=out, stderr=err) env=env,
stdout=out,
stderr=err)
if not args.quiet: if not args.quiet:
print("{0}: {1}".format(status_to_str(status), test)) print("{0}: {1}".format(status_to_str(status), test))
results.append(status) results.append(status)
def count(status): def count(status):
return len(list(filter(lambda x: x == status, results))) return len(list(filter(lambda x: x == status, results)))
def failed(): def failed():
return len(list(filter(lambda x: x not in (0, 77, 99), results))) return len(list(filter(lambda x: x not in (0, 77, 99), results)))
if not args.quiet: if not args.quiet:
print("{0} tests run, {1} succeeded, {2} failed, {3} skipped.".format( print("{0} tests run, {1} succeeded, {2} failed, {3} skipped.".format(
len(results), count(0), failed(), count(77))) len(results), count(0), failed(), count(77)))

View File

@ -16,7 +16,6 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import contextlib import contextlib
import shutil import shutil
@ -27,20 +26,28 @@ import tempfile
import time import time
import gpg import gpg
del absolute_import, print_function, unicode_literals
def assert_gpg_version(version=(2, 1, 0)): def assert_gpg_version(version=(2, 1, 0)):
with gpg.Context() as c: with gpg.Context() as c:
clean_version = re.match(r'\d+\.\d+\.\d+', c.engine_info.version).group(0) clean_version = re.match(r'\d+\.\d+\.\d+',
c.engine_info.version).group(0)
if tuple(map(int, clean_version.split('.'))) < version: if tuple(map(int, clean_version.split('.'))) < version:
print("GnuPG too old: have {0}, need {1}.".format( print("GnuPG too old: have {0}, need {1}.".format(
c.engine_info.version, '.'.join(map(str, version)))) c.engine_info.version, '.'.join(map(str, version))))
sys.exit(77) sys.exit(77)
def have_tofu_support(ctx, some_uid): def have_tofu_support(ctx, some_uid):
keys = list(ctx.keylist(some_uid, keys = list(
mode=(gpg.constants.keylist.mode.LOCAL ctx.keylist(
|gpg.constants.keylist.mode.WITH_TOFU))) some_uid,
mode=(gpg.constants.keylist.mode.LOCAL |
gpg.constants.keylist.mode.WITH_TOFU)))
return len(keys) > 0 return len(keys) > 0
# Skip the Python tests for GnuPG < 2.1.12. Prior versions do not # Skip the Python tests for GnuPG < 2.1.12. Prior versions do not
# understand the command line flags that we assume exist. C.f. issue # understand the command line flags that we assume exist. C.f. issue
# 3008. # 3008.
@ -53,13 +60,18 @@ encrypt_only = "F52770D5C4DB41408D918C9F920572769B9FE19C"
sign_only = "7CCA20CCDE5394CEE71C9F0BFED153F12F18F45D" sign_only = "7CCA20CCDE5394CEE71C9F0BFED153F12F18F45D"
no_such_key = "A" * 40 no_such_key = "A" * 40
def make_filename(name): def make_filename(name):
return os.path.join(os.environ['top_srcdir'], 'tests', 'gpg', name) return os.path.join(os.environ['top_srcdir'], 'tests', 'gpg', name)
def in_srcdir(name): def in_srcdir(name):
return os.path.join(os.environ['srcdir'], name) return os.path.join(os.environ['srcdir'], name)
verbose = int(os.environ.get('verbose', 0)) > 1 verbose = int(os.environ.get('verbose', 0)) > 1
def print_data(data): def print_data(data):
if verbose: if verbose:
try: try:
@ -75,10 +87,12 @@ def print_data(data):
else: else:
sys.stdout.write(data) sys.stdout.write(data)
def mark_key_trusted(ctx, key): def mark_key_trusted(ctx, key):
class Editor(object): class Editor(object):
def __init__(self): def __init__(self):
self.steps = ["trust", "save"] self.steps = ["trust", "save"]
def edit(self, status, args, out): def edit(self, status, args, out):
if args == "keyedit.prompt": if args == "keyedit.prompt":
result = self.steps.pop(0) result = self.steps.pop(0)
@ -91,6 +105,7 @@ def mark_key_trusted(ctx, key):
else: else:
result = None result = None
return result return result
with gpg.Data() as sink: with gpg.Data() as sink:
ctx.op_edit(key, Editor().edit, sink, sink) ctx.op_edit(key, Editor().edit, sink, sink)
@ -103,9 +118,11 @@ class TemporaryDirectory(object):
def __enter__(self): def __enter__(self):
self.path = tempfile.mkdtemp() self.path = tempfile.mkdtemp()
return self.path return self.path
def __exit__(self, *args): def __exit__(self, *args):
shutil.rmtree(self.path, ignore_errors=True) shutil.rmtree(self.path, ignore_errors=True)
@contextlib.contextmanager @contextlib.contextmanager
def EphemeralContext(): def EphemeralContext():
with TemporaryDirectory() as tmp: with TemporaryDirectory() as tmp:
@ -124,7 +141,7 @@ def EphemeralContext():
ctx.assuan_transact(["KILLAGENT"]) ctx.assuan_transact(["KILLAGENT"])
except gpg.errors.GPGMEError as e: except gpg.errors.GPGMEError as e:
if e.getcode() == gpg.errors.ASS_CONNECT_FAILED: if e.getcode() == gpg.errors.ASS_CONNECT_FAILED:
pass # the agent was not running pass # the agent was not running
else: else:
raise raise

View File

@ -18,12 +18,13 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import os import os
import gpg import gpg
import support import support
_ = support # to appease pyflakes. _ = support # to appease pyflakes.
del absolute_import, print_function, unicode_literals
c = gpg.Context() c = gpg.Context()
c.set_pinentry_mode(gpg.constants.PINENTRY_MODE_LOOPBACK) c.set_pinentry_mode(gpg.constants.PINENTRY_MODE_LOOPBACK)
@ -33,6 +34,7 @@ sink = gpg.Data()
# Valid passphrases, both as string and bytes. # Valid passphrases, both as string and bytes.
for passphrase in ('foo', b'foo'): for passphrase in ('foo', b'foo'):
def passphrase_cb(hint, desc, prev_bad, hook=None): def passphrase_cb(hint, desc, prev_bad, hook=None):
assert hook == passphrase assert hook == passphrase
return hook return hook
@ -40,10 +42,12 @@ for passphrase in ('foo', b'foo'):
c.set_passphrase_cb(passphrase_cb, passphrase) c.set_passphrase_cb(passphrase_cb, passphrase)
c.op_encrypt([], 0, source, sink) c.op_encrypt([], 0, source, sink)
# Returning an invalid type. # Returning an invalid type.
def passphrase_cb(hint, desc, prev_bad, hook=None): def passphrase_cb(hint, desc, prev_bad, hook=None):
return 0 return 0
c.set_passphrase_cb(passphrase_cb, None) c.set_passphrase_cb(passphrase_cb, None)
try: try:
c.op_encrypt([], 0, source, sink) c.op_encrypt([], 0, source, sink)
@ -55,9 +59,12 @@ else:
# Raising an exception inside callback. # Raising an exception inside callback.
myException = Exception() myException = Exception()
def passphrase_cb(hint, desc, prev_bad, hook=None): def passphrase_cb(hint, desc, prev_bad, hook=None):
raise myException raise myException
c.set_passphrase_cb(passphrase_cb, None) c.set_passphrase_cb(passphrase_cb, None)
try: try:
c.op_encrypt([], 0, source, sink) c.op_encrypt([], 0, source, sink)
@ -66,10 +73,12 @@ except Exception as e:
else: else:
assert False, "Expected an error, got none" assert False, "Expected an error, got none"
# Wrong kind of callback function. # Wrong kind of callback function.
def bad_passphrase_cb(): def bad_passphrase_cb():
pass pass
c.set_passphrase_cb(bad_passphrase_cb, None) c.set_passphrase_cb(bad_passphrase_cb, None)
try: try:
c.op_encrypt([], 0, source, sink) c.op_encrypt([], 0, source, sink)
@ -78,8 +87,6 @@ except Exception as e:
else: else:
assert False, "Expected an error, got none" assert False, "Expected an error, got none"
# Test the progress callback. # Test the progress callback.
parms = """<GnupgKeyParms format="internal"> parms = """<GnupgKeyParms format="internal">
Key-Type: RSA Key-Type: RSA
@ -93,21 +100,26 @@ Expire-Date: 2099-12-31
""" """
messages = [] messages = []
def progress_cb(what, typ, current, total, hook=None): def progress_cb(what, typ, current, total, hook=None):
assert hook == messages assert hook == messages
messages.append( messages.append(
"PROGRESS UPDATE: what = {}, type = {}, current = {}, total = {}" "PROGRESS UPDATE: what = {}, type = {}, current = {}, total = {}"
.format(what, typ, current, total)) .format(what, typ, current, total))
c = gpg.Context() c = gpg.Context()
c.set_progress_cb(progress_cb, messages) c.set_progress_cb(progress_cb, messages)
c.op_genkey(parms, None, None) c.op_genkey(parms, None, None)
assert len(messages) > 0 assert len(messages) > 0
# Test exception handling. # Test exception handling.
def progress_cb(what, typ, current, total, hook=None): def progress_cb(what, typ, current, total, hook=None):
raise myException raise myException
c = gpg.Context() c = gpg.Context()
c.set_progress_cb(progress_cb, None) c.set_progress_cb(progress_cb, None)
try: try:
@ -117,7 +129,6 @@ except Exception as e:
else: else:
assert False, "Expected an error, got none" assert False, "Expected an error, got none"
# Test the edit callback. # Test the edit callback.
c = gpg.Context() c = gpg.Context()
c.set_pinentry_mode(gpg.constants.PINENTRY_MODE_LOOPBACK) c.set_pinentry_mode(gpg.constants.PINENTRY_MODE_LOOPBACK)
@ -127,11 +138,15 @@ alpha = c.get_key("A0FF4590BB6122EDEF6E3C542D727CC768697734", False)
cookie = object() cookie = object()
edit_cb_called = False edit_cb_called = False
def edit_cb(status, args, hook): def edit_cb(status, args, hook):
global edit_cb_called global edit_cb_called
edit_cb_called = True edit_cb_called = True
assert hook == cookie assert hook == cookie
return "quit" if args == "keyedit.prompt" else None return "quit" if args == "keyedit.prompt" else None
c.op_edit(alpha, edit_cb, cookie, sink) c.op_edit(alpha, edit_cb, cookie, sink)
assert edit_cb_called assert edit_cb_called
@ -141,8 +156,11 @@ c.set_pinentry_mode(gpg.constants.PINENTRY_MODE_LOOPBACK)
c.set_passphrase_cb(lambda *args: "abc") c.set_passphrase_cb(lambda *args: "abc")
sink = gpg.Data() sink = gpg.Data()
def edit_cb(status, args): def edit_cb(status, args):
raise myException raise myException
try: try:
c.op_edit(alpha, edit_cb, None, sink) c.op_edit(alpha, edit_cb, None, sink)
except Exception as e: except Exception as e:
@ -150,18 +168,19 @@ except Exception as e:
else: else:
assert False, "Expected an error, got none" assert False, "Expected an error, got none"
# Test the status callback. # Test the status callback.
source = gpg.Data("Hallo Leute\n") source = gpg.Data("Hallo Leute\n")
sink = gpg.Data() sink = gpg.Data()
status_cb_called = False status_cb_called = False
def status_cb(keyword, args, hook=None): def status_cb(keyword, args, hook=None):
global status_cb_called global status_cb_called
status_cb_called = True status_cb_called = True
assert hook == cookie assert hook == cookie
c = gpg.Context() c = gpg.Context()
c.set_status_cb(status_cb, cookie) c.set_status_cb(status_cb, cookie)
c.set_ctx_flag("full-status", "1") c.set_ctx_flag("full-status", "1")
@ -172,9 +191,11 @@ assert status_cb_called
source = gpg.Data("Hallo Leute\n") source = gpg.Data("Hallo Leute\n")
sink = gpg.Data() sink = gpg.Data()
def status_cb(keyword, args): def status_cb(keyword, args):
raise myException raise myException
c = gpg.Context() c = gpg.Context()
c.set_status_cb(status_cb, None) c.set_status_cb(status_cb, None)
c.set_ctx_flag("full-status", "1") c.set_ctx_flag("full-status", "1")
@ -186,13 +207,16 @@ else:
assert False, "Expected an error, got none" assert False, "Expected an error, got none"
# Test the data callbacks. # Test the data callbacks.
def read_cb(amount, hook=None): def read_cb(amount, hook=None):
assert hook == cookie assert hook == cookie
return 0 return 0
def release_cb(hook=None): def release_cb(hook=None):
assert hook == cookie assert hook == cookie
data = gpg.Data(cbs=(read_cb, None, None, release_cb, cookie)) data = gpg.Data(cbs=(read_cb, None, None, release_cb, cookie))
try: try:
data.read() data.read()
@ -201,8 +225,11 @@ except Exception as e:
else: else:
assert False, "Expected an error, got none" assert False, "Expected an error, got none"
def read_cb(amount): def read_cb(amount):
raise myException raise myException
data = gpg.Data(cbs=(read_cb, None, None, lambda: None)) data = gpg.Data(cbs=(read_cb, None, None, lambda: None))
try: try:
data.read() data.read()
@ -215,6 +242,8 @@ else:
def write_cb(what, hook=None): def write_cb(what, hook=None):
assert hook == cookie assert hook == cookie
return "wrong type" return "wrong type"
data = gpg.Data(cbs=(None, write_cb, None, release_cb, cookie)) data = gpg.Data(cbs=(None, write_cb, None, release_cb, cookie))
try: try:
data.write(b'stuff') data.write(b'stuff')
@ -223,8 +252,11 @@ except Exception as e:
else: else:
assert False, "Expected an error, got none" assert False, "Expected an error, got none"
def write_cb(what): def write_cb(what):
raise myException raise myException
data = gpg.Data(cbs=(None, write_cb, None, lambda: None)) data = gpg.Data(cbs=(None, write_cb, None, lambda: None))
try: try:
data.write(b'stuff') data.write(b'stuff')
@ -237,6 +269,8 @@ else:
def seek_cb(offset, whence, hook=None): def seek_cb(offset, whence, hook=None):
assert hook == cookie assert hook == cookie
return "wrong type" return "wrong type"
data = gpg.Data(cbs=(None, None, seek_cb, release_cb, cookie)) data = gpg.Data(cbs=(None, None, seek_cb, release_cb, cookie))
try: try:
data.seek(0, os.SEEK_SET) data.seek(0, os.SEEK_SET)
@ -245,8 +279,11 @@ except Exception as e:
else: else:
assert False, "Expected an error, got none" assert False, "Expected an error, got none"
def seek_cb(offset, whence): def seek_cb(offset, whence):
raise myException raise myException
data = gpg.Data(cbs=(None, None, seek_cb, lambda: None)) data = gpg.Data(cbs=(None, None, seek_cb, lambda: None))
try: try:
data.seek(0, os.SEEK_SET) data.seek(0, os.SEEK_SET)

View File

@ -18,14 +18,15 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import io import io
import os import os
import tempfile import tempfile
import gpg import gpg
import support import support
_ = support # to appease pyflakes. _ = support # to appease pyflakes.
del absolute_import, print_function, unicode_literals
data = gpg.Data('Hello world!') data = gpg.Data('Hello world!')
assert data.read() == b'Hello world!' assert data.read() == b'Hello world!'
@ -94,7 +95,8 @@ with tempfile.NamedTemporaryFile() as tmp:
# Open using name, offset, and length. # Open using name, offset, and length.
data = gpg.Data(file=tmp.name, offset=23, length=42) data = gpg.Data(file=tmp.name, offset=23, length=42)
assert data.read() == binjunk[23:23+42] assert data.read() == binjunk[23:23 + 42]
# Test callbacks. # Test callbacks.
class DataObject(object): class DataObject(object):
@ -118,6 +120,7 @@ class DataObject(object):
assert not self.released assert not self.released
self.released = True self.released = True
do = DataObject() do = DataObject()
cookie = object() cookie = object()
data = gpg.Data(cbs=(do.read, do.write, do.seek, do.release, cookie)) data = gpg.Data(cbs=(do.read, do.write, do.seek, do.release, cookie))

View File

@ -18,11 +18,13 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import gpg import gpg
import support import support
del absolute_import, print_function, unicode_literals
def check_verify_result(result, summary, fpr, status): def check_verify_result(result, summary, fpr, status):
assert len(result.signatures) == 1, "Unexpected number of signatures" assert len(result.signatures) == 1, "Unexpected number of signatures"
sig = result.signatures[0] sig = result.signatures[0]
@ -32,7 +34,9 @@ def check_verify_result(result, summary, fpr, status):
assert len(sig.notations) == 0 assert len(sig.notations) == 0
assert not sig.wrong_key_usage assert not sig.wrong_key_usage
assert sig.validity == gpg.constants.validity.FULL assert sig.validity == gpg.constants.validity.FULL
assert gpg.errors.GPGMEError(sig.validity_reason).getcode() == gpg.errors.NO_ERROR assert gpg.errors.GPGMEError(
sig.validity_reason).getcode() == gpg.errors.NO_ERROR
c = gpg.Context() c = gpg.Context()
@ -47,10 +51,9 @@ assert not result.unsupported_algorithm, \
support.print_data(sink) support.print_data(sink)
verify_result = c.op_verify_result() verify_result = c.op_verify_result()
check_verify_result(verify_result, check_verify_result(
gpg.constants.sigsum.VALID | gpg.constants.sigsum.GREEN, verify_result, gpg.constants.sigsum.VALID | gpg.constants.sigsum.GREEN,
"A0FF4590BB6122EDEF6E3C542D727CC768697734", "A0FF4590BB6122EDEF6E3C542D727CC768697734", gpg.errors.NO_ERROR)
gpg.errors.NO_ERROR)
# Idiomatic interface. # Idiomatic interface.
with gpg.Context() as c: with gpg.Context() as c:
@ -60,14 +63,13 @@ with gpg.Context() as c:
c.decrypt(open(support.make_filename("cipher-2.asc")), verify=[alpha]) c.decrypt(open(support.make_filename("cipher-2.asc")), verify=[alpha])
assert plaintext.find(b'Wenn Sie dies lesen k') >= 0, \ assert plaintext.find(b'Wenn Sie dies lesen k') >= 0, \
'Plaintext not found' 'Plaintext not found'
check_verify_result(verify_result, check_verify_result(
gpg.constants.sigsum.VALID | gpg.constants.sigsum.GREEN, verify_result, gpg.constants.sigsum.VALID | gpg.constants.sigsum.GREEN,
"A0FF4590BB6122EDEF6E3C542D727CC768697734", "A0FF4590BB6122EDEF6E3C542D727CC768697734", gpg.errors.NO_ERROR)
gpg.errors.NO_ERROR)
try: try:
c.decrypt(open(support.make_filename("cipher-2.asc")), c.decrypt(
verify=[alpha, bob]) open(support.make_filename("cipher-2.asc")), verify=[alpha, bob])
except gpg.errors.MissingSignatures as e: except gpg.errors.MissingSignatures as e:
assert len(e.missing) == 1 assert len(e.missing) == 1
assert e.missing[0] == bob assert e.missing[0] == bob

View File

@ -18,11 +18,12 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import gpg import gpg
import support import support
del absolute_import, print_function, unicode_literals
c = gpg.Context() c = gpg.Context()
source = gpg.Data(file=support.make_filename("cipher-1.asc")) source = gpg.Data(file=support.make_filename("cipher-1.asc"))

View File

@ -19,13 +19,15 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import sys import sys
import os import os
import gpg import gpg
import support import support
_ = support # to appease pyflakes. _ = support # to appease pyflakes.
del absolute_import, print_function, unicode_literals
class KeyEditor(object): class KeyEditor(object):
def __init__(self): def __init__(self):
@ -47,11 +49,12 @@ class KeyEditor(object):
result = None result = None
if self.verbose: if self.verbose:
sys.stderr.write("Code: {}, args: {!r}, Returning: {!r}\n" sys.stderr.write("Code: {}, args: {!r}, Returning: {!r}\n".format(
.format(status, args, result)) status, args, result))
return result return result
c = gpg.Context() c = gpg.Context()
c.set_pinentry_mode(gpg.constants.PINENTRY_MODE_LOOPBACK) c.set_pinentry_mode(gpg.constants.PINENTRY_MODE_LOOPBACK)
c.set_passphrase_cb(lambda *args: "abc") c.set_passphrase_cb(lambda *args: "abc")
@ -59,13 +62,15 @@ c.set_armor(True)
# The deprecated interface. # The deprecated interface.
editor = KeyEditor() editor = KeyEditor()
c.interact(c.get_key("A0FF4590BB6122EDEF6E3C542D727CC768697734", False), c.interact(
editor.edit_fnc) c.get_key("A0FF4590BB6122EDEF6E3C542D727CC768697734", False),
editor.edit_fnc)
assert editor.done assert editor.done
# The deprecated interface. # The deprecated interface.
sink = gpg.Data() sink = gpg.Data()
editor = KeyEditor() editor = KeyEditor()
c.op_edit(c.get_key("A0FF4590BB6122EDEF6E3C542D727CC768697734", False), c.op_edit(
editor.edit_fnc, sink, sink) c.get_key("A0FF4590BB6122EDEF6E3C542D727CC768697734", False),
editor.edit_fnc, sink, sink)
assert editor.done assert editor.done

View File

@ -18,13 +18,14 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import sys import sys
import random import random
import gpg import gpg
import support import support
del absolute_import, print_function, unicode_literals
if len(sys.argv) == 2: if len(sys.argv) == 2:
nbytes = int(sys.argv[1]) nbytes = int(sys.argv[1])
else: else:
@ -33,6 +34,8 @@ else:
c = gpg.Context() c = gpg.Context()
ntoread = nbytes ntoread = nbytes
def read_cb(amount): def read_cb(amount):
global ntoread global ntoread
chunk = ntoread if ntoread < amount else amount chunk = ntoread if ntoread < amount else amount
@ -41,12 +44,16 @@ def read_cb(amount):
assert chunk >= 0 assert chunk >= 0
return bytes(bytearray(random.randrange(256) for i in range(chunk))) return bytes(bytearray(random.randrange(256) for i in range(chunk)))
nwritten = 0 nwritten = 0
def write_cb(data): def write_cb(data):
global nwritten global nwritten
nwritten += len(data) nwritten += len(data)
return len(data) return len(data)
source = gpg.Data(cbs=(read_cb, None, None, lambda: None)) source = gpg.Data(cbs=(read_cb, None, None, lambda: None))
sink = gpg.Data(cbs=(None, write_cb, None, lambda: None)) sink = gpg.Data(cbs=(None, write_cb, None, lambda: None))
@ -61,5 +68,5 @@ assert not result.invalid_recipients, \
assert ntoread == 0 assert ntoread == 0
if support.verbose: if support.verbose:
sys.stderr.write( sys.stderr.write("plaintext={} bytes, ciphertext={} bytes\n".format(
"plaintext={} bytes, ciphertext={} bytes\n".format(nbytes, nwritten)) nbytes, nwritten))

View File

@ -18,15 +18,17 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import sys import sys
import gpg import gpg
import support import support
del absolute_import, print_function, unicode_literals
c = gpg.Context() c = gpg.Context()
c.set_armor(True) c.set_armor(True)
def check_result(r, typ): def check_result(r, typ):
if r.invalid_signers: if r.invalid_signers:
sys.exit("Invalid signer found: {}".format(r.invalid_signers.fpr)) sys.exit("Invalid signer found: {}".format(r.invalid_signers.fpr))
@ -42,7 +44,8 @@ def check_result(r, typ):
sys.exit("Wrong pubkey algorithm reported: {}".format( sys.exit("Wrong pubkey algorithm reported: {}".format(
signature.pubkey_algo)) signature.pubkey_algo))
if signature.hash_algo not in (gpg.constants.md.SHA1, gpg.constants.md.RMD160): if signature.hash_algo not in (gpg.constants.md.SHA1,
gpg.constants.md.RMD160):
sys.exit("Wrong hash algorithm reported: {}".format( sys.exit("Wrong hash algorithm reported: {}".format(
signature.hash_algo)) signature.hash_algo))
@ -53,6 +56,7 @@ def check_result(r, typ):
if signature.fpr != "A0FF4590BB6122EDEF6E3C542D727CC768697734": if signature.fpr != "A0FF4590BB6122EDEF6E3C542D727CC768697734":
sys.exit("Wrong fingerprint reported: {}".format(signature.fpr)) sys.exit("Wrong fingerprint reported: {}".format(signature.fpr))
keys = [] keys = []
keys.append(c.get_key("A0FF4590BB6122EDEF6E3C542D727CC768697734", False)) keys.append(c.get_key("A0FF4590BB6122EDEF6E3C542D727CC768697734", False))
keys.append(c.get_key("D695676BDCEDCC2CDD6152BCFE180B1DA9E3B0B2", False)) keys.append(c.get_key("D695676BDCEDCC2CDD6152BCFE180B1DA9E3B0B2", False))
@ -61,7 +65,8 @@ for recipients in (keys, []):
source = gpg.Data("Hallo Leute\n") source = gpg.Data("Hallo Leute\n")
sink = gpg.Data() sink = gpg.Data()
c.op_encrypt_sign(recipients, gpg.constants.ENCRYPT_ALWAYS_TRUST, source, sink) c.op_encrypt_sign(recipients, gpg.constants.ENCRYPT_ALWAYS_TRUST, source,
sink)
result = c.op_encrypt_result() result = c.op_encrypt_result()
assert not result.invalid_recipients, \ assert not result.invalid_recipients, \
"Invalid recipient encountered: {}".format( "Invalid recipient encountered: {}".format(
@ -72,13 +77,11 @@ for recipients in (keys, []):
support.print_data(sink) support.print_data(sink)
# Idiomatic interface. # Idiomatic interface.
with gpg.Context(armor=True) as c: with gpg.Context(armor=True) as c:
message = "Hallo Leute\n".encode() message = "Hallo Leute\n".encode()
ciphertext, _, sig_result = c.encrypt(message, ciphertext, _, sig_result = c.encrypt(
recipients=keys, message, recipients=keys, always_trust=True)
always_trust=True)
assert len(ciphertext) > 0 assert len(ciphertext) > 0
assert ciphertext.find(b'BEGIN PGP MESSAGE') > 0, 'Marker not found' assert ciphertext.find(b'BEGIN PGP MESSAGE') > 0, 'Marker not found'
check_result(sig_result, gpg.constants.sig.mode.NORMAL) check_result(sig_result, gpg.constants.sig.mode.NORMAL)

View File

@ -18,12 +18,13 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import os import os
import gpg import gpg
import support import support
_ = support # to appease pyflakes. _ = support # to appease pyflakes.
del absolute_import, print_function, unicode_literals
for passphrase in ("abc", b"abc"): for passphrase in ("abc", b"abc"):
c = gpg.Context() c = gpg.Context()
@ -34,6 +35,7 @@ for passphrase in ("abc", b"abc"):
cipher = gpg.Data() cipher = gpg.Data()
passphrase_cb_called = 0 passphrase_cb_called = 0
def passphrase_cb(hint, desc, prev_bad, hook=None): def passphrase_cb(hint, desc, prev_bad, hook=None):
global passphrase_cb_called global passphrase_cb_called
passphrase_cb_called += 1 passphrase_cb_called += 1
@ -55,7 +57,7 @@ for passphrase in ("abc", b"abc"):
c.op_decrypt(cipher, plain) c.op_decrypt(cipher, plain)
# Seems like the passphrase is cached. # Seems like the passphrase is cached.
#assert passphrase_cb_called == 2, \ # assert passphrase_cb_called == 2, \
# "Callback called {} times".format(passphrase_cb_called) # "Callback called {} times".format(passphrase_cb_called)
support.print_data(plain) support.print_data(plain)
@ -70,12 +72,12 @@ for passphrase in ("abc", b"abc"):
# Check that the passphrase callback is not altered. # Check that the passphrase callback is not altered.
def f(*args): def f(*args):
assert False assert False
c.set_passphrase_cb(f) c.set_passphrase_cb(f)
message = "Hallo Leute\n".encode() message = "Hallo Leute\n".encode()
ciphertext, _, _ = c.encrypt(message, ciphertext, _, _ = c.encrypt(
passphrase=passphrase, message, passphrase=passphrase, sign=False)
sign=False)
assert ciphertext.find(b'BEGIN PGP MESSAGE') > 0, 'Marker not found' assert ciphertext.find(b'BEGIN PGP MESSAGE') > 0, 'Marker not found'
plaintext, _, _ = c.decrypt(ciphertext, passphrase=passphrase) plaintext, _, _ = c.decrypt(ciphertext, passphrase=passphrase)

View File

@ -18,11 +18,12 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import gpg import gpg
import support import support
del absolute_import, print_function, unicode_literals
c = gpg.Context() c = gpg.Context()
c.set_armor(True) c.set_armor(True)
@ -41,36 +42,37 @@ support.print_data(sink)
# Idiomatic interface. # Idiomatic interface.
with gpg.Context(armor=True) as c: with gpg.Context(armor=True) as c:
ciphertext, _, _ = c.encrypt("Hallo Leute\n".encode(), ciphertext, _, _ = c.encrypt(
recipients=keys, "Hallo Leute\n".encode(),
sign=False, recipients=keys,
always_trust=True) sign=False,
always_trust=True)
assert len(ciphertext) > 0 assert len(ciphertext) > 0
assert ciphertext.find(b'BEGIN PGP MESSAGE') > 0, 'Marker not found' assert ciphertext.find(b'BEGIN PGP MESSAGE') > 0, 'Marker not found'
c.encrypt("Hallo Leute\n".encode(), c.encrypt(
recipients=[c.get_key(support.encrypt_only, False)], "Hallo Leute\n".encode(),
sign=False, always_trust=True) recipients=[c.get_key(support.encrypt_only, False)],
sign=False,
always_trust=True)
try: try:
c.encrypt("Hallo Leute\n".encode(), c.encrypt(
recipients=[c.get_key(support.sign_only, False)], "Hallo Leute\n".encode(),
sign=False, always_trust=True) recipients=[c.get_key(support.sign_only, False)],
sign=False,
always_trust=True)
except gpg.errors.InvalidRecipients as e: except gpg.errors.InvalidRecipients as e:
assert len(e.recipients) == 1 assert len(e.recipients) == 1
assert support.sign_only.endswith(e.recipients[0].fpr) assert support.sign_only.endswith(e.recipients[0].fpr)
else: else:
assert False, "Expected an InvalidRecipients error, got none" assert False, "Expected an InvalidRecipients error, got none"
try: try:
# People might be tempted to provide strings. # People might be tempted to provide strings.
# We should raise something useful. # We should raise something useful.
ciphertext, _, _ = c.encrypt("Hallo Leute\n", ciphertext, _, _ = c.encrypt(
recipients=keys, "Hallo Leute\n", recipients=keys, sign=False, always_trust=True)
sign=False,
always_trust=True)
except TypeError as e: except TypeError as e:
# This test is a bit fragile, because the message # This test is a bit fragile, because the message
# may very well change. So if the behaviour will change # may very well change. So if the behaviour will change

View File

@ -18,11 +18,12 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import gpg import gpg
import support import support
del absolute_import, print_function, unicode_literals
c = gpg.Context() c = gpg.Context()
c.set_armor(True) c.set_armor(True)
@ -32,8 +33,8 @@ support.print_data(sink)
# Again. Now using a key array. # Again. Now using a key array.
keys = [] keys = []
keys.append(c.get_key("0x68697734", False)) # Alpha keys.append(c.get_key("0x68697734", False)) # Alpha
keys.append(c.get_key("0xA9E3B0B2", False)) # Bob keys.append(c.get_key("0xA9E3B0B2", False)) # Bob
sink = gpg.Data() sink = gpg.Data()
c.op_export_keys(keys, 0, sink) c.op_export_keys(keys, 0, sink)
support.print_data(sink) support.print_data(sink)

View File

@ -18,12 +18,13 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import os import os
import gpg import gpg
import support import support
_ = support # to appease pyflakes. _ = support # to appease pyflakes.
del absolute_import, print_function, unicode_literals
testname = "abcde12345" testname = "abcde12345"

View File

@ -18,7 +18,6 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import sys import sys
import io import io
@ -26,7 +25,9 @@ import os
import tempfile import tempfile
import gpg import gpg
import support import support
_ = support # to appease pyflakes. _ = support # to appease pyflakes.
del absolute_import, print_function, unicode_literals
# Both Context and Data can be used as context manager: # Both Context and Data can be used as context manager:
with gpg.Context() as c, gpg.Data() as d: with gpg.Context() as c, gpg.Data() as d:
@ -34,8 +35,9 @@ with gpg.Context() as c, gpg.Data() as d:
d.write(b"Halloechen") d.write(b"Halloechen")
leak_c = c leak_c = c
leak_d = d leak_d = d
assert leak_c.wrapped == None assert leak_c.wrapped is None
assert leak_d.wrapped == None assert leak_d.wrapped is None
def sign_and_verify(source, signed, sink): def sign_and_verify(source, signed, sink):
with gpg.Context() as c: with gpg.Context() as c:
@ -53,6 +55,7 @@ def sign_and_verify(source, signed, sink):
sink.seek(0, os.SEEK_SET) sink.seek(0, os.SEEK_SET)
assert sink.read() == b"Hallo Leute\n" assert sink.read() == b"Hallo Leute\n"
# Demonstrate automatic wrapping of file-like objects with 'fileno' # Demonstrate automatic wrapping of file-like objects with 'fileno'
# method. # method.
with tempfile.TemporaryFile() as source, \ with tempfile.TemporaryFile() as source, \
@ -73,7 +76,7 @@ if sys.version_info[0] == 3:
bio.truncate(1) bio.truncate(1)
if len(bio.getvalue()) != 1: if len(bio.getvalue()) != 1:
# This version of Python is affected, preallocate buffer. # This version of Python is affected, preallocate buffer.
preallocate = 128*b'\x00' preallocate = 128 * b'\x00'
else: else:
preallocate = b'' preallocate = b''

View File

@ -18,45 +18,47 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import gpg import gpg
import support import support
del absolute_import, print_function, unicode_literals
def check_result(result, fpr, secret): def check_result(result, fpr, secret):
assert result.considered == 1 or (secret and result.considered == 3) assert result.considered == 1 or (secret and result.considered == 3)
assert result.no_user_id == 0 assert result.no_user_id == 0
assert not ((secret and result.imported != 0) assert not ((secret and result.imported != 0) or
or (not secret and (result.imported != 0 (not secret and
and result.imported != 1))) (result.imported != 0 and result.imported != 1)))
assert result.imported_rsa == 0 assert result.imported_rsa == 0
assert not ((secret and (result.unchanged != 0 and result.unchanged != 1)) assert not ((secret and
or (not secret and ((result.imported == 0 (result.unchanged != 0 and result.unchanged != 1)) or
and result.unchanged != 1) (not secret and
or (result.imported == 1 ((result.imported == 0 and result.unchanged != 1) or
and result.unchanged != 0)))) (result.imported == 1 and result.unchanged != 0))))
assert result.new_user_ids == 0 assert result.new_user_ids == 0
assert result.new_sub_keys == 0 assert result.new_sub_keys == 0
assert not ((secret assert not ((secret and (
and ((result.secret_imported == 0 (result.secret_imported == 0 and result.new_signatures != 0) or
and result.new_signatures != 0) (result.secret_imported == 1 and result.new_signatures > 1))) or
or (result.secret_imported == 1 (not secret and result.new_signatures != 0))
and result.new_signatures > 1)))
or (not secret and result.new_signatures != 0))
assert result.new_revocations == 0 assert result.new_revocations == 0
assert not ((secret and result.secret_read != 1 and result.secret_read != 3) assert not (
or (not secret and result.secret_read != 0)) (secret and result.secret_read != 1 and result.secret_read != 3) or
assert not ((secret and result.secret_imported != 0 (not secret and result.secret_read != 0))
and result.secret_imported != 1 assert not (
and result.secret_imported != 2) (secret and result.secret_imported != 0 and result.
or (not secret and result.secret_imported != 0)) secret_imported != 1 and result.
assert not ((secret secret_imported != 2) or (not secret and result.
and ((result.secret_imported == 0 secret_imported != 0))
and result.secret_unchanged != 1 assert not ((secret and
and result.secret_unchanged != 2) ((result.secret_imported == 0 and result.
or (result.secret_imported == 1 secret_unchanged != 1 and result.
and result.secret_unchanged != 0))) secret_unchanged != 2) or (result.
or (not secret and result.secret_unchanged != 0)) secret_imported == 1 and result.
secret_unchanged != 0))) or
(not secret and result.secret_unchanged != 0))
assert result.not_imported == 0 assert result.not_imported == 0
if secret: if secret:
assert not (len(result.imports) in (0, 3)) assert not (len(result.imports) in (0, 3))
@ -67,6 +69,7 @@ def check_result(result, fpr, secret):
assert len(result.imports) == 1 or fpr == result.imports[1].fpr assert len(result.imports) == 1 or fpr == result.imports[1].fpr
assert result.imports[0].result == 0 assert result.imports[0].result == 0
c = gpg.Context() c = gpg.Context()
result = c.key_import(open(support.make_filename("pubkey-1.asc"), 'rb').read()) result = c.key_import(open(support.make_filename("pubkey-1.asc"), 'rb').read())

View File

@ -18,87 +18,142 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import gpg import gpg
import support import support
del absolute_import, print_function, unicode_literals
support.assert_gpg_version((2, 1, 14)) support.assert_gpg_version((2, 1, 14))
# Check expration of keys. This test assumes three subkeys of which # Check expration of keys. This test assumes three subkeys of which
# 2 are expired; it is used with the "Whisky" test key. It has # 2 are expired; it is used with the "Whisky" test key. It has
# already been checked that these 3 subkeys are available. # already been checked that these 3 subkeys are available.
def check_whisky(name, key): def check_whisky(name, key):
sub1 = key.subkeys[2] sub1 = key.subkeys[2]
sub2 = key.subkeys[3] sub2 = key.subkeys[3]
assert sub1.expired and sub2.expired, \
"Subkey of `{}' not flagged as expired".format(name)
assert sub1.expires == 1129636886 and sub2.expires == 1129636939, \
"Subkey of `{}' has wrong expiration date".format(name)
assert sub1.expired and sub2.expired, \
"Subkey of `{}' not flagged as expired".format(name)
assert sub1.expires == 1129636886 and sub2.expires == 1129636939, \
"Subkey of `{}' has wrong expiration date".format(name)
keys = [ keys = [
[ "A0FF4590BB6122EDEF6E3C542D727CC768697734", "6AE6D7EE46A871F8", [
[ [ "Alfa Test", "demo key", "alfa@example.net" ], "A0FF4590BB6122EDEF6E3C542D727CC768697734", "6AE6D7EE46A871F8",
[ "Alpha Test", "demo key", "alpha@example.net" ], [["Alfa Test", "demo key", "alfa@example.net"],
[ "Alice", "demo key", "" ] ], 1 ], ["Alpha Test", "demo key", "alpha@example.net"],
[ "D695676BDCEDCC2CDD6152BCFE180B1DA9E3B0B2", "5381EA4EE29BA37F", ["Alice", "demo key", ""]], 1
[ [ "Bob", "demo key", "" ], ],
[ "Bravo Test", "demo key", "bravo@example.net" ] ], 1 ], [
[ "61EE841A2A27EB983B3B3C26413F4AF31AFDAB6C", "E71E72ACBC43DA60", "D695676BDCEDCC2CDD6152BCFE180B1DA9E3B0B2", "5381EA4EE29BA37F",
[ [ "Charlie Test", "demo key", "charlie@example.net" ] ], 1 ], [["Bob", "demo key", ""],
[ "6560C59C43D031C54D7C588EEBA9F240EB9DC9E6", "06F22880B0C45424", ["Bravo Test", "demo key", "bravo@example.net"]], 1
[ [ "Delta Test", "demo key", "delta@example.net" ] ], 1 ], ],
[ "3531152DE293E26A07F504BC318C1FAEFAEF6D1B", "B5C79E1A7272144D", [
[ [ "Echelon", "demo key", "" ], "61EE841A2A27EB983B3B3C26413F4AF31AFDAB6C", "E71E72ACBC43DA60",
[ "Echo Test", "demo key", "echo@example.net" ], [["Charlie Test", "demo key", "charlie@example.net"]], 1
[ "Eve", "demo key", "" ] ], 1 ], ],
[ "56D33268F7FE693FBB594762D4BF57F37372E243", "0A32EE79EE45198E", [
[ [ "Foxtrot Test", "demo key", "foxtrot@example.net" ] ], 1 ], "6560C59C43D031C54D7C588EEBA9F240EB9DC9E6", "06F22880B0C45424",
[ "C9C07DCC6621B9FB8D071B1D168410A48FC282E6", "247491CC9DCAD354", [["Delta Test", "demo key", "delta@example.net"]], 1
[ [ "Golf Test", "demo key", "golf@example.net" ] ], 1 ], ],
[ "9E91CBB11E4D4135583EF90513DB965534C6E3F1", "76E26537D622AD0A", [
[ [ "Hotel Test", "demo key", "hotel@example.net" ] ], 1 ], "3531152DE293E26A07F504BC318C1FAEFAEF6D1B", "B5C79E1A7272144D",
[ "CD538D6CC9FB3D745ECDA5201FE8FC6F04259677", "C1C8EFDE61F76C73", [["Echelon", "demo key",
[ [ "India Test", "demo key", "india@example.net" ] ], 1 ], ""], ["Echo Test", "demo key", "echo@example.net"],
[ "F8F1EDC73995AB739AD54B380C820C71D2699313", "BD0B108735F8F136", ["Eve", "demo key", ""]], 1
[ [ "Juliet Test", "demo key", "juliet@example.net" ] ], 1 ], ],
[ "3FD11083779196C2ECDD9594AD1B0FAD43C2D0C7", "86CBB34A9AF64D02", [
[ [ "Kilo Test", "demo key", "kilo@example.net" ] ], 1 ], "56D33268F7FE693FBB594762D4BF57F37372E243", "0A32EE79EE45198E",
[ "1DDD28CEF714F5B03B8C246937CAB51FB79103F8", "0363B449FE56350C", [["Foxtrot Test", "demo key", "foxtrot@example.net"]], 1
[ [ "Lima Test", "demo key", "lima@example.net" ] ], 1 ], ],
[ "2686AA191A278013992C72EBBE794852BE5CF886", "5F600A834F31EAE8", [
[ [ "Mallory", "demo key", "" ], "C9C07DCC6621B9FB8D071B1D168410A48FC282E6", "247491CC9DCAD354",
[ "Mike Test", "demo key", "mike@example.net" ] ], 1 ], [["Golf Test", "demo key", "golf@example.net"]], 1
[ "5AB9D6D7BAA1C95B3BAA3D9425B00FD430CEC684", "4C1D63308B70E472", ],
[ [ "November Test", "demo key", "november@example.net" ] ], 1 ], [
[ "43929E89F8F79381678CAE515F6356BA6D9732AC", "FF0785712681619F", "9E91CBB11E4D4135583EF90513DB965534C6E3F1", "76E26537D622AD0A",
[ [ "Oscar Test", "demo key", "oscar@example.net" ] ], 1 ], [["Hotel Test", "demo key", "hotel@example.net"]], 1
[ "6FAA9C201E5E26DCBAEC39FD5D15E01D3FF13206", "2764E18263330D9C", ],
[ [ "Papa test", "demo key", "papa@example.net" ] ], 1 ], [
[ "A7969DA1C3297AA96D49843F1C67EC133C661C84", "6CDCFC44A029ACF4", "CD538D6CC9FB3D745ECDA5201FE8FC6F04259677", "C1C8EFDE61F76C73",
[ [ "Quebec Test", "demo key", "quebec@example.net" ] ], 1 ], [["India Test", "demo key", "india@example.net"]], 1
[ "38FBE1E4BF6A5E1242C8F6A13BDBEDB1777FBED3", "9FAB805A11D102EA", ],
[ [ "Romeo Test", "demo key", "romeo@example.net" ] ], 1 ], [
[ "045B2334ADD69FC221076841A5E67F7FA3AE3EA1", "93B88B0F0F1B50B4", "F8F1EDC73995AB739AD54B380C820C71D2699313", "BD0B108735F8F136",
[ [ "Sierra Test", "demo key", "sierra@example.net" ] ], 1 ], [["Juliet Test", "demo key", "juliet@example.net"]], 1
[ "ECAC774F4EEEB0620767044A58CB9A4C85A81F38", "97B60E01101C0402", ],
[ [ "Tango Test", "demo key", "tango@example.net" ] ], 1 ], [
[ "0DBCAD3F08843B9557C6C4D4A94C0F75653244D6", "93079B915522BDB9", "3FD11083779196C2ECDD9594AD1B0FAD43C2D0C7", "86CBB34A9AF64D02",
[ [ "Uniform Test", "demo key", "uniform@example.net" ] ], 1 ], [["Kilo Test", "demo key", "kilo@example.net"]], 1
[ "E8143C489C8D41124DC40D0B47AF4B6961F04784", "04071FB807287134", ],
[ [ "Victor Test", "demo key", "victor@example.org" ] ], 1 ], [
[ "E8D6C90B683B0982BD557A99DEF0F7B8EC67DBDE", "D7FBB421FD6E27F6", "1DDD28CEF714F5B03B8C246937CAB51FB79103F8", "0363B449FE56350C",
[ [ "Whisky Test", "demo key", "whisky@example.net" ] ], 3, [["Lima Test", "demo key", "lima@example.net"]], 1
check_whisky ], ],
[ "04C1DF62EFA0EBB00519B06A8979A6C5567FB34A", "5CC6F87F41E408BE", [
[ [ "XRay Test", "demo key", "xray@example.net" ] ], 1 ], "2686AA191A278013992C72EBBE794852BE5CF886", "5F600A834F31EAE8",
[ "ED9B316F78644A58D042655A9EEF34CD4B11B25F", "5ADFD255F7B080AD", [["Mallory", "demo key", ""],
[ [ "Yankee Test", "demo key", "yankee@example.net" ] ], 1 ], ["Mike Test", "demo key", "mike@example.net"]], 1
[ "23FD347A419429BACCD5E72D6BC4778054ACD246", "EF9DC276A172C881", ],
[ [ "Zulu Test", "demo key", "zulu@example.net" ] ], 1 ], [
"5AB9D6D7BAA1C95B3BAA3D9425B00FD430CEC684", "4C1D63308B70E472",
[["November Test", "demo key", "november@example.net"]], 1
],
[
"43929E89F8F79381678CAE515F6356BA6D9732AC", "FF0785712681619F",
[["Oscar Test", "demo key", "oscar@example.net"]], 1
],
[
"6FAA9C201E5E26DCBAEC39FD5D15E01D3FF13206", "2764E18263330D9C",
[["Papa test", "demo key", "papa@example.net"]], 1
],
[
"A7969DA1C3297AA96D49843F1C67EC133C661C84", "6CDCFC44A029ACF4",
[["Quebec Test", "demo key", "quebec@example.net"]], 1
],
[
"38FBE1E4BF6A5E1242C8F6A13BDBEDB1777FBED3", "9FAB805A11D102EA",
[["Romeo Test", "demo key", "romeo@example.net"]], 1
],
[
"045B2334ADD69FC221076841A5E67F7FA3AE3EA1", "93B88B0F0F1B50B4",
[["Sierra Test", "demo key", "sierra@example.net"]], 1
],
[
"ECAC774F4EEEB0620767044A58CB9A4C85A81F38", "97B60E01101C0402",
[["Tango Test", "demo key", "tango@example.net"]], 1
],
[
"0DBCAD3F08843B9557C6C4D4A94C0F75653244D6", "93079B915522BDB9",
[["Uniform Test", "demo key", "uniform@example.net"]], 1
],
[
"E8143C489C8D41124DC40D0B47AF4B6961F04784", "04071FB807287134",
[["Victor Test", "demo key", "victor@example.org"]], 1
],
[
"E8D6C90B683B0982BD557A99DEF0F7B8EC67DBDE", "D7FBB421FD6E27F6",
[["Whisky Test", "demo key", "whisky@example.net"]], 3, check_whisky
],
[
"04C1DF62EFA0EBB00519B06A8979A6C5567FB34A", "5CC6F87F41E408BE",
[["XRay Test", "demo key", "xray@example.net"]], 1
],
[
"ED9B316F78644A58D042655A9EEF34CD4B11B25F", "5ADFD255F7B080AD",
[["Yankee Test", "demo key", "yankee@example.net"]], 1
],
[
"23FD347A419429BACCD5E72D6BC4778054ACD246", "EF9DC276A172C881",
[["Zulu Test", "demo key", "zulu@example.net"]], 1
],
] ]
def check_global(key, uids, n_subkeys): def check_global(key, uids, n_subkeys):
assert not key.revoked, "Key unexpectedly revoked" assert not key.revoked, "Key unexpectedly revoked"
assert not key.expired, "Key unexpectedly expired" assert not key.expired, "Key unexpectedly expired"
@ -107,18 +162,18 @@ def check_global(key, uids, n_subkeys):
assert key.can_sign, "Key unexpectedly unusable for signing" assert key.can_sign, "Key unexpectedly unusable for signing"
assert key.can_certify, "Key unexpectedly unusable for certifications" assert key.can_certify, "Key unexpectedly unusable for certifications"
assert not key.secret, "Key unexpectedly secret" assert not key.secret, "Key unexpectedly secret"
assert not key.protocol != gpg.constants.protocol.OpenPGP, \ assert not key.protocol != gpg.constants.protocol.
"Key has unexpected protocol: {}".format(key.protocol) OpenPGP, "Key has unexpected protocol: {}".format(key.protocol)
assert not key.issuer_serial, \ assert not key.issuer_serial,
"Key unexpectedly carries issuer serial: {}".format(key.issuer_serial) "Key unexpectedly carries issuer serial: {}".format(key.issuer_serial)
assert not key.issuer_name, \ assert not key.issuer_name,
"Key unexpectedly carries issuer name: {}".format(key.issuer_name) "Key unexpectedly carries issuer name: {}".format(key.issuer_name)
assert not key.chain_id, \ assert not key.chain_id,
"Key unexpectedly carries chain ID: {}".format(key.chain_id) "Key unexpectedly carries chain ID: {}".format(key.chain_id)
assert key.owner_trust == gpg.constants.validity.UNKNOWN, \ assert key.owner_trust == gpg.constants.validity.UNKNOWN,
"Key has unexpected owner trust: {}".format(key.owner_trust) "Key has unexpected owner trust: {}".format(key.owner_trust)
assert len(key.subkeys) - 1 == n_subkeys, \ assert len(key.subkeys) - 1 == n_subkeys,
"Key `{}' has unexpected number of subkeys".format(uids[0][0]) "Key `{}' has unexpected number of subkeys".format(uids[0][0])
def check_subkey(fpr, which, subkey): def check_subkey(fpr, which, subkey):
@ -128,54 +183,55 @@ def check_subkey(fpr, which, subkey):
assert not subkey.invalid, which + " key unexpectedly invalid" assert not subkey.invalid, which + " key unexpectedly invalid"
if which == "Primary": if which == "Primary":
assert not subkey.can_encrypt, \ assert not subkey.can_encrypt,
which + " key unexpectedly usable for encryption" which + " key unexpectedly usable for encryption"
assert subkey.can_sign, \ assert subkey.can_sign,
which + " key unexpectedly unusable for signing" which + " key unexpectedly unusable for signing"
assert subkey.can_certify, \ assert subkey.can_certify,
which + " key unexpectedly unusable for certifications" which + " key unexpectedly unusable for certifications"
else: else:
assert subkey.can_encrypt, \ assert subkey.can_encrypt,
which + " key unexpectedly unusable for encryption" which + " key unexpectedly unusable for encryption"
assert not subkey.can_sign, \ assert not subkey.can_sign,
which + " key unexpectedly usable for signing" which + " key unexpectedly usable for signing"
assert not subkey.can_certify, \ assert not subkey.can_certify,
which + " key unexpectedly usable for certifications" which + " key unexpectedly usable for certifications"
assert not subkey.secret, which + " key unexpectedly secret" assert not subkey.secret, which + " key unexpectedly secret"
assert not subkey.is_cardkey, "Public key marked as card key" assert not subkey.is_cardkey, "Public key marked as card key"
assert not subkey.card_number, "Public key with card number set" assert not subkey.card_number, "Public key with card number set"
assert not subkey.pubkey_algo != (gpg.constants.pk.DSA if which == "Primary" assert not subkey.pubkey_algo !=
else gpg.constants.pk.ELG_E), \ (gpg.constants.pk.DSA if which == "Primary" else gpg.constants.pk.ELG_E),
which + " key has unexpected public key algo: {}".\ which + " key has unexpected public key algo: {}".format(subkey.
format(subkey.pubkey_algo) pubkey_algo)
assert subkey.length == 1024, \ assert subkey.length == 1024,
which + " key has unexpected length: {}".format(subkey.length) which + " key has unexpected length: {}".format(subkey.length)
assert fpr.endswith(subkey.keyid), \ assert fpr.endswith(subkey.keyid),
which + " key has unexpected key ID: {}".format(subkey.keyid) which + " key has unexpected key ID: {}".format(subkey.keyid)
assert which == "Secondary" or subkey.fpr == fpr, \ assert which == "Secondary" or subkey.fpr == fpr,
which + " key has unexpected fingerprint: {}".format(subkey.fpr) which + " key has unexpected fingerprint: {}".format(subkey.fpr)
assert not subkey.expires, \ assert not subkey.expires,
which + " key unexpectedly expires: {}".format(subkey.expires) which + " key unexpectedly expires: {}".format(subkey.expires)
def check_uid(which, ref, uid): def check_uid(which, ref, uid):
assert not uid.revoked, which + " user ID unexpectedly revoked" assert not uid.revoked, which + " user ID unexpectedly revoked"
assert not uid.invalid, which + " user ID unexpectedly invalid" assert not uid.invalid, which + " user ID unexpectedly invalid"
assert uid.validity == gpg.constants.validity.UNKNOWN, \ assert uid.validity == gpg.constants.validity.UNKNOWN,
which + " user ID has unexpected validity: {}".format(uid.validity) which + " user ID has unexpected validity: {}".format(uid.validity)
assert not uid.signatures, which + " user ID unexpectedly signed" assert not uid.signatures, which + " user ID unexpectedly signed"
assert uid.name == ref[0], \ assert uid.name == ref[0],
"Unexpected name in {} user ID: {!r}".format(which.lower(), uid.name) "Unexpected name in {} user ID: {!r}".format(which.lower(), uid.name)
assert uid.comment == ref[1], \ assert uid.comment == ref[1],
"Unexpected comment in {} user ID: {!r}".format(which.lower(), "Unexpected comment in {} user ID: {!r}".format(which.lower(), uid.comment)
uid.comment) assert uid.email == ref[2],
assert uid.email == ref[2], \ "Unexpected email in {} user ID: {!r}".format(which.lower(), uid.email)
"Unexpected email in {} user ID: {!r}".format(which.lower(), uid.email)
# Export all the data from our keyring... # Export all the data from our keyring...
key_data = gpg.Data() key_data = gpg.Data()
with gpg.Context() as c: with gpg.Context() as c:
c.op_export_keys([c.get_key(k[0]) for k in keys], 0, key_data) c.op_export_keys([c.get_key(k[0]) for k in keys], 0, key_data)
# ... rewind the tape... # ... rewind the tape...
key_data.rewind() key_data.rewind()
@ -201,11 +257,11 @@ with support.EphemeralContext() as c:
assert len(key.uids) == len(uids) assert len(key.uids) == len(uids)
check_uid("First", uids[0], key.uids[0]) check_uid("First", uids[0], key.uids[0])
if len(key.uids) > 1: if len(key.uids) > 1:
check_uid("Second", uids[1], key.uids[1]) check_uid("Second", uids[1], key.uids[1])
if len(key.uids) > 2: if len(key.uids) > 2:
check_uid("Third", uids[2], key.uids[2]) check_uid("Third", uids[2], key.uids[2])
if misc_check: if misc_check:
misc_check (uids[0][0], key) misc_check(uids[0][0], key)
assert len(list(c.keylist())) == 0, "Keys were imported" assert len(list(c.keylist())) == 0, "Keys were imported"

View File

@ -18,87 +18,142 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import gpg import gpg
import support import support
del absolute_import, print_function, unicode_literals
c = gpg.Context() c = gpg.Context()
# Check expration of keys. This test assumes three subkeys of which # Check expration of keys. This test assumes three subkeys of which
# 2 are expired; it is used with the "Whisky" test key. It has # 2 are expired; it is used with the "Whisky" test key. It has
# already been checked that these 3 subkeys are available. # already been checked that these 3 subkeys are available.
def check_whisky(name, key): def check_whisky(name, key):
sub1 = key.subkeys[2] sub1 = key.subkeys[2]
sub2 = key.subkeys[3] sub2 = key.subkeys[3]
assert sub1.expired and sub2.expired, \
"Subkey of `{}' not flagged as expired".format(name)
assert sub1.expires == 1129636886 and sub2.expires == 1129636939, \
"Subkey of `{}' has wrong expiration date".format(name)
assert sub1.expired and sub2.expired, \
"Subkey of `{}' not flagged as expired".format(name)
assert sub1.expires == 1129636886 and sub2.expires == 1129636939, \
"Subkey of `{}' has wrong expiration date".format(name)
keys = [ keys = [
[ "A0FF4590BB6122EDEF6E3C542D727CC768697734", "6AE6D7EE46A871F8", [
[ [ "Alfa Test", "demo key", "alfa@example.net" ], "A0FF4590BB6122EDEF6E3C542D727CC768697734", "6AE6D7EE46A871F8",
[ "Alpha Test", "demo key", "alpha@example.net" ], [["Alfa Test", "demo key",
[ "Alice", "demo key", "" ] ], 1 ], "alfa@example.net"], ["Alpha Test", "demo key", "alpha@example.net"],
[ "D695676BDCEDCC2CDD6152BCFE180B1DA9E3B0B2", "5381EA4EE29BA37F", ["Alice", "demo key", ""]], 1
[ [ "Bob", "demo key", "" ], ],
[ "Bravo Test", "demo key", "bravo@example.net" ] ], 1 ], [
[ "61EE841A2A27EB983B3B3C26413F4AF31AFDAB6C", "E71E72ACBC43DA60", "D695676BDCEDCC2CDD6152BCFE180B1DA9E3B0B2", "5381EA4EE29BA37F",
[ [ "Charlie Test", "demo key", "charlie@example.net" ] ], 1 ], [["Bob", "demo key", ""],
[ "6560C59C43D031C54D7C588EEBA9F240EB9DC9E6", "06F22880B0C45424", ["Bravo Test", "demo key", "bravo@example.net"]], 1
[ [ "Delta Test", "demo key", "delta@example.net" ] ], 1 ], ],
[ "3531152DE293E26A07F504BC318C1FAEFAEF6D1B", "B5C79E1A7272144D", [
[ [ "Echelon", "demo key", "" ], "61EE841A2A27EB983B3B3C26413F4AF31AFDAB6C", "E71E72ACBC43DA60",
[ "Echo Test", "demo key", "echo@example.net" ], [["Charlie Test", "demo key", "charlie@example.net"]], 1
[ "Eve", "demo key", "" ] ], 1 ], ],
[ "56D33268F7FE693FBB594762D4BF57F37372E243", "0A32EE79EE45198E", [
[ [ "Foxtrot Test", "demo key", "foxtrot@example.net" ] ], 1 ], "6560C59C43D031C54D7C588EEBA9F240EB9DC9E6", "06F22880B0C45424",
[ "C9C07DCC6621B9FB8D071B1D168410A48FC282E6", "247491CC9DCAD354", [["Delta Test", "demo key", "delta@example.net"]], 1
[ [ "Golf Test", "demo key", "golf@example.net" ] ], 1 ], ],
[ "9E91CBB11E4D4135583EF90513DB965534C6E3F1", "76E26537D622AD0A", [
[ [ "Hotel Test", "demo key", "hotel@example.net" ] ], 1 ], "3531152DE293E26A07F504BC318C1FAEFAEF6D1B", "B5C79E1A7272144D",
[ "CD538D6CC9FB3D745ECDA5201FE8FC6F04259677", "C1C8EFDE61F76C73", [["Echelon", "demo key",
[ [ "India Test", "demo key", "india@example.net" ] ], 1 ], ""], ["Echo Test", "demo key", "echo@example.net"],
[ "F8F1EDC73995AB739AD54B380C820C71D2699313", "BD0B108735F8F136", ["Eve", "demo key", ""]], 1
[ [ "Juliet Test", "demo key", "juliet@example.net" ] ], 1 ], ],
[ "3FD11083779196C2ECDD9594AD1B0FAD43C2D0C7", "86CBB34A9AF64D02", [
[ [ "Kilo Test", "demo key", "kilo@example.net" ] ], 1 ], "56D33268F7FE693FBB594762D4BF57F37372E243", "0A32EE79EE45198E",
[ "1DDD28CEF714F5B03B8C246937CAB51FB79103F8", "0363B449FE56350C", [["Foxtrot Test", "demo key", "foxtrot@example.net"]], 1
[ [ "Lima Test", "demo key", "lima@example.net" ] ], 1 ], ],
[ "2686AA191A278013992C72EBBE794852BE5CF886", "5F600A834F31EAE8", [
[ [ "Mallory", "demo key", "" ], "C9C07DCC6621B9FB8D071B1D168410A48FC282E6", "247491CC9DCAD354",
[ "Mike Test", "demo key", "mike@example.net" ] ], 1 ], [["Golf Test", "demo key", "golf@example.net"]], 1
[ "5AB9D6D7BAA1C95B3BAA3D9425B00FD430CEC684", "4C1D63308B70E472", ],
[ [ "November Test", "demo key", "november@example.net" ] ], 1 ], [
[ "43929E89F8F79381678CAE515F6356BA6D9732AC", "FF0785712681619F", "9E91CBB11E4D4135583EF90513DB965534C6E3F1", "76E26537D622AD0A",
[ [ "Oscar Test", "demo key", "oscar@example.net" ] ], 1 ], [["Hotel Test", "demo key", "hotel@example.net"]], 1
[ "6FAA9C201E5E26DCBAEC39FD5D15E01D3FF13206", "2764E18263330D9C", ],
[ [ "Papa test", "demo key", "papa@example.net" ] ], 1 ], [
[ "A7969DA1C3297AA96D49843F1C67EC133C661C84", "6CDCFC44A029ACF4", "CD538D6CC9FB3D745ECDA5201FE8FC6F04259677", "C1C8EFDE61F76C73",
[ [ "Quebec Test", "demo key", "quebec@example.net" ] ], 1 ], [["India Test", "demo key", "india@example.net"]], 1
[ "38FBE1E4BF6A5E1242C8F6A13BDBEDB1777FBED3", "9FAB805A11D102EA", ],
[ [ "Romeo Test", "demo key", "romeo@example.net" ] ], 1 ], [
[ "045B2334ADD69FC221076841A5E67F7FA3AE3EA1", "93B88B0F0F1B50B4", "F8F1EDC73995AB739AD54B380C820C71D2699313", "BD0B108735F8F136",
[ [ "Sierra Test", "demo key", "sierra@example.net" ] ], 1 ], [["Juliet Test", "demo key", "juliet@example.net"]], 1
[ "ECAC774F4EEEB0620767044A58CB9A4C85A81F38", "97B60E01101C0402", ],
[ [ "Tango Test", "demo key", "tango@example.net" ] ], 1 ], [
[ "0DBCAD3F08843B9557C6C4D4A94C0F75653244D6", "93079B915522BDB9", "3FD11083779196C2ECDD9594AD1B0FAD43C2D0C7", "86CBB34A9AF64D02",
[ [ "Uniform Test", "demo key", "uniform@example.net" ] ], 1 ], [["Kilo Test", "demo key", "kilo@example.net"]], 1
[ "E8143C489C8D41124DC40D0B47AF4B6961F04784", "04071FB807287134", ],
[ [ "Victor Test", "demo key", "victor@example.org" ] ], 1 ], [
[ "E8D6C90B683B0982BD557A99DEF0F7B8EC67DBDE", "D7FBB421FD6E27F6", "1DDD28CEF714F5B03B8C246937CAB51FB79103F8", "0363B449FE56350C",
[ [ "Whisky Test", "demo key", "whisky@example.net" ] ], 3, [["Lima Test", "demo key", "lima@example.net"]], 1
check_whisky ], ],
[ "04C1DF62EFA0EBB00519B06A8979A6C5567FB34A", "5CC6F87F41E408BE", [
[ [ "XRay Test", "demo key", "xray@example.net" ] ], 1 ], "2686AA191A278013992C72EBBE794852BE5CF886", "5F600A834F31EAE8",
[ "ED9B316F78644A58D042655A9EEF34CD4B11B25F", "5ADFD255F7B080AD", [["Mallory", "demo key", ""],
[ [ "Yankee Test", "demo key", "yankee@example.net" ] ], 1 ], ["Mike Test", "demo key", "mike@example.net"]], 1
[ "23FD347A419429BACCD5E72D6BC4778054ACD246", "EF9DC276A172C881", ],
[ [ "Zulu Test", "demo key", "zulu@example.net" ] ], 1 ], [
"5AB9D6D7BAA1C95B3BAA3D9425B00FD430CEC684", "4C1D63308B70E472",
[["November Test", "demo key", "november@example.net"]], 1
],
[
"43929E89F8F79381678CAE515F6356BA6D9732AC", "FF0785712681619F",
[["Oscar Test", "demo key", "oscar@example.net"]], 1
],
[
"6FAA9C201E5E26DCBAEC39FD5D15E01D3FF13206", "2764E18263330D9C",
[["Papa test", "demo key", "papa@example.net"]], 1
],
[
"A7969DA1C3297AA96D49843F1C67EC133C661C84", "6CDCFC44A029ACF4",
[["Quebec Test", "demo key", "quebec@example.net"]], 1
],
[
"38FBE1E4BF6A5E1242C8F6A13BDBEDB1777FBED3", "9FAB805A11D102EA",
[["Romeo Test", "demo key", "romeo@example.net"]], 1
],
[
"045B2334ADD69FC221076841A5E67F7FA3AE3EA1", "93B88B0F0F1B50B4",
[["Sierra Test", "demo key", "sierra@example.net"]], 1
],
[
"ECAC774F4EEEB0620767044A58CB9A4C85A81F38", "97B60E01101C0402",
[["Tango Test", "demo key", "tango@example.net"]], 1
],
[
"0DBCAD3F08843B9557C6C4D4A94C0F75653244D6", "93079B915522BDB9",
[["Uniform Test", "demo key", "uniform@example.net"]], 1
],
[
"E8143C489C8D41124DC40D0B47AF4B6961F04784", "04071FB807287134",
[["Victor Test", "demo key", "victor@example.org"]], 1
],
[
"E8D6C90B683B0982BD557A99DEF0F7B8EC67DBDE", "D7FBB421FD6E27F6",
[["Whisky Test", "demo key", "whisky@example.net"]], 3, check_whisky
],
[
"04C1DF62EFA0EBB00519B06A8979A6C5567FB34A", "5CC6F87F41E408BE",
[["XRay Test", "demo key", "xray@example.net"]], 1
],
[
"ED9B316F78644A58D042655A9EEF34CD4B11B25F", "5ADFD255F7B080AD",
[["Yankee Test", "demo key", "yankee@example.net"]], 1
],
[
"23FD347A419429BACCD5E72D6BC4778054ACD246", "EF9DC276A172C881",
[["Zulu Test", "demo key", "zulu@example.net"]], 1
],
] ]
def check_global(key, uids, n_subkeys): def check_global(key, uids, n_subkeys):
assert not key.revoked, "Key unexpectedly revoked" assert not key.revoked, "Key unexpectedly revoked"
assert not key.expired, "Key unexpectedly expired" assert not key.expired, "Key unexpectedly expired"
@ -107,25 +162,25 @@ def check_global(key, uids, n_subkeys):
assert key.can_sign, "Key unexpectedly unusable for signing" assert key.can_sign, "Key unexpectedly unusable for signing"
assert key.can_certify, "Key unexpectedly unusable for certifications" assert key.can_certify, "Key unexpectedly unusable for certifications"
assert not key.secret, "Key unexpectedly secret" assert not key.secret, "Key unexpectedly secret"
assert not key.protocol != gpg.constants.protocol.OpenPGP, \ assert not key.protocol != gpg.constants.protocol.OpenPGP,
"Key has unexpected protocol: {}".format(key.protocol) "Key has unexpected protocol: {}".format(key.protocol)
assert not key.issuer_serial, \ assert not key.issuer_serial,
"Key unexpectedly carries issuer serial: {}".format(key.issuer_serial) "Key unexpectedly carries issuer serial: {}".format(key.issuer_serial)
assert not key.issuer_name, \ assert not key.issuer_name,
"Key unexpectedly carries issuer name: {}".format(key.issuer_name) "Key unexpectedly carries issuer name: {}".format(key.issuer_name)
assert not key.chain_id, \ assert not key.chain_id,
"Key unexpectedly carries chain ID: {}".format(key.chain_id) "Key unexpectedly carries chain ID: {}".format(key.chain_id)
# Only key Alfa is trusted # Only key Alfa is trusted
assert key.uids[0].name == 'Alfa Test' \ assert key.uids[0].name == 'Alfa Test' or
or key.owner_trust == gpg.constants.validity.UNKNOWN, \ key.owner_trust == gpg.constants.validity.UNKNOWN,
"Key has unexpected owner trust: {}".format(key.owner_trust) "Key has unexpected owner trust: {}".format(key.owner_trust)
assert key.uids[0].name != 'Alfa Test' \ assert key.uids[0].name != 'Alfa Test' or key.owner_trust == gpg.constants.
or key.owner_trust == gpg.constants.validity.ULTIMATE, \ validity.ULTIMATE, "Key has unexpected owner trust: {}".
"Key has unexpected owner trust: {}".format(key.owner_trust) format(key.owner_trust)
assert len(key.subkeys) - 1 == n_subkeys, \ assert len(key.subkeys) - 1 == n_subkeys,
"Key `{}' has unexpected number of subkeys".format(uids[0][0]) "Key `{}' has unexpected number of subkeys".format(uids[0][0])
def check_subkey(fpr, which, subkey): def check_subkey(fpr, which, subkey):
@ -152,18 +207,19 @@ def check_subkey(fpr, which, subkey):
assert not subkey.secret, which + " key unexpectedly secret" assert not subkey.secret, which + " key unexpectedly secret"
assert not subkey.is_cardkey, "Public key marked as card key" assert not subkey.is_cardkey, "Public key marked as card key"
assert not subkey.card_number, "Public key with card number set" assert not subkey.card_number, "Public key with card number set"
assert not subkey.pubkey_algo != (gpg.constants.pk.DSA if which == "Primary" assert not subkey.pubkey_algo !=
else gpg.constants.pk.ELG_E), \ (gpg.constants.pk.DSA if which == "Primary" else gpg.constants.pk.ELG_E),
which + " key has unexpected public key algo: {}".\ which + " key has unexpected public key algo: {}".format(subkey.
format(subkey.pubkey_algo) pubkey_algo)
assert subkey.length == 1024, \ assert subkey.length == 1024,
which + " key has unexpected length: {}".format(subkey.length) which + " key has unexpected length: {}".format(subkey.length)
assert fpr.endswith(subkey.keyid), \ assert fpr.endswith(subkey.keyid),
which + " key has unexpected key ID: {}".format(subkey.keyid) which + " key has unexpected key ID: {}".format(subkey.keyid)
assert which == "Secondary" or subkey.fpr == fpr, \ assert which == "Secondary" or subkey.fpr == fpr,
which + " key has unexpected fingerprint: {}".format(subkey.fpr) which + " key has unexpected fingerprint: {}".format(subkey.fpr)
assert not subkey.expires, \ assert not subkey.expires,
which + " key unexpectedly expires: {}".format(subkey.expires) which + " key unexpectedly expires: {}".format(subkey.expires)
def check_uid(which, ref, uid): def check_uid(which, ref, uid):
assert not uid.revoked, which + " user ID unexpectedly revoked" assert not uid.revoked, which + " user ID unexpectedly revoked"
@ -171,20 +227,21 @@ def check_uid(which, ref, uid):
assert uid.validity == (gpg.constants.validity.UNKNOWN assert uid.validity == (gpg.constants.validity.UNKNOWN
if uid.name.split()[0] if uid.name.split()[0]
not in {'Alfa', 'Alpha', 'Alice'} else not in {'Alfa', 'Alpha', 'Alice'} else
gpg.constants.validity.ULTIMATE), \ gpg.constants.validity.ULTIMATE),
which + " user ID has unexpectedly validity: {}".format(uid.validity) which + " user ID has unexpectedly validity: {}".format(uid.validity)
assert not uid.signatures, which + " user ID unexpectedly signed" assert not uid.signatures, which + " user ID unexpectedly signed"
assert uid.name == ref[0], \ assert uid.name == ref[0],
"Unexpected name in {} user ID: {!r}".format(which.lower(), uid.name) "Unexpected name in {} user ID: {!r}".format(which.lower(), uid.name)
assert uid.comment == ref[1], \ assert uid.comment == ref[1],
"Unexpected comment in {} user ID: {!r}".format(which.lower(), "Unexpected comment in {} user ID: {!r}".format(which.lower(),
uid.comment) uid.comment)
assert uid.email == ref[2], \ assert uid.email == ref[2],
"Unexpected email in {} user ID: {!r}".format(which.lower(), uid.email) "Unexpected email in {} user ID: {!r}".format(which.lower(), uid.email)
i = 0 i = 0
c.op_keylist_start(None, False) c.op_keylist_start(None, False)
key = c.op_keylist_next () key = c.op_keylist_next()
while key: while key:
try: try:
if len(keys[i]) == 4: if len(keys[i]) == 4:
@ -204,20 +261,19 @@ while key:
assert len(key.uids) == len(uids) assert len(key.uids) == len(uids)
check_uid("First", uids[0], key.uids[0]) check_uid("First", uids[0], key.uids[0])
if len(key.uids) > 1: if len(key.uids) > 1:
check_uid("Second", uids[1], key.uids[1]) check_uid("Second", uids[1], key.uids[1])
if len(key.uids) > 2: if len(key.uids) > 2:
check_uid("Third", uids[2], key.uids[2]) check_uid("Third", uids[2], key.uids[2])
if misc_check: if misc_check:
misc_check (uids[0][0], key) misc_check(uids[0][0], key)
key = c.op_keylist_next () key = c.op_keylist_next()
i += 1 i += 1
c.op_keylist_end() c.op_keylist_end()
result = c.op_keylist_result() result = c.op_keylist_result()
assert not result.truncated, "Key listing unexpectedly truncated" assert not result.truncated, "Key listing unexpectedly truncated"
# We test for a parameter-less keylist # We test for a parameter-less keylist
keyring_length = len(list(c.op_keylist_all())) keyring_length = len(list(c.op_keylist_all()))
assert keyring_length > 1,\ assert keyring_length > 1,\
@ -226,13 +282,12 @@ assert keyring_length > 1,\
# Then we do want to call with a pattern, only # Then we do want to call with a pattern, only
# i.e. without giving secret=0 # i.e. without giving secret=0
alpha_keys = list(c.op_keylist_all(b"Alpha")) alpha_keys = list(c.op_keylist_all(b"Alpha"))
assert len(alpha_keys) == 1, "Expected only one key for 'Alpha', got %r" % len(alpha_keys) assert len(alpha_keys) == 1, "Expected only one key for 'Alpha', got %r" % len(
alpha_keys)
# Check negative result. # Check negative result.
assert len(list(c.keylist("no such key in sight"))) == 0 assert len(list(c.keylist("no such key in sight"))) == 0
for i, key in enumerate(c.keylist()): for i, key in enumerate(c.keylist()):
try: try:
if len(keys[i]) == 4: if len(keys[i]) == 4:
@ -252,31 +307,30 @@ for i, key in enumerate(c.keylist()):
assert len(key.uids) == len(uids) assert len(key.uids) == len(uids)
check_uid("First", uids[0], key.uids[0]) check_uid("First", uids[0], key.uids[0])
if len(key.uids) > 1: if len(key.uids) > 1:
check_uid("Second", uids[1], key.uids[1]) check_uid("Second", uids[1], key.uids[1])
if len(key.uids) > 2: if len(key.uids) > 2:
check_uid("Third", uids[2], key.uids[2]) check_uid("Third", uids[2], key.uids[2])
if misc_check: if misc_check:
misc_check (uids[0][0], key) misc_check(uids[0][0], key)
# check get_key() # check get_key()
with gpg.Context() as c: with gpg.Context() as c:
c.get_key(support.alpha) c.get_key(support.alpha)
c.get_key(support.alpha, secret=True) c.get_key(support.alpha, secret=True)
c.get_key(support.bob) c.get_key(support.bob)
try: try:
c.get_key(support.bob, secret=True) c.get_key(support.bob, secret=True)
except KeyError: except KeyError:
pass pass
else: else:
assert False, "Expected KeyError" assert False, "Expected KeyError"
# Legacy error # Legacy error
try: try:
c.get_key(support.no_such_key) c.get_key(support.no_such_key)
except gpg.errors.GPGMEError: except gpg.errors.GPGMEError:
pass pass
else: else:
assert False, "Expected GPGMEError" assert False, "Expected GPGMEError"

View File

@ -18,20 +18,21 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import gpg import gpg
import support import support
_ = support # to appease pyflakes. _ = support # to appease pyflakes.
del absolute_import, print_function, unicode_literals
with gpg.Context(protocol=gpg.constants.protocol.ASSUAN) as c: with gpg.Context(protocol=gpg.constants.protocol.ASSUAN) as c:
# Do nothing. # Do nothing.
err = c.assuan_transact('nop') err = c.assuan_transact('nop')
assert err == None assert err is None
err = c.assuan_transact(b'NOP') err = c.assuan_transact(b'NOP')
assert err == None assert err is None
err = c.assuan_transact(['NOP']) err = c.assuan_transact(['NOP'])
assert err == None assert err is None
err = c.assuan_transact('idontexist') err = c.assuan_transact('idontexist')
assert err.getsource() == gpg.errors.SOURCE_GPGAGENT assert err.getsource() == gpg.errors.SOURCE_GPGAGENT
@ -41,6 +42,7 @@ with gpg.Context(protocol=gpg.constants.protocol.ASSUAN) as c:
c.assuan_transact(['GET_CONFIRMATION', 'Hello there']) c.assuan_transact(['GET_CONFIRMATION', 'Hello there'])
data = [] data = []
def data_cb(line): def data_cb(line):
data.append(line) data.append(line)
@ -57,6 +59,7 @@ with gpg.Context(protocol=gpg.constants.protocol.ASSUAN) as c:
# XXX HELP sends status lines if we could use ASSUAN_CONVEY_COMMENTS. # XXX HELP sends status lines if we could use ASSUAN_CONVEY_COMMENTS.
status = [] status = []
def status_cb(line, args): def status_cb(line, args):
status.append((line, args)) status.append((line, args))

View File

@ -18,7 +18,6 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import gpg import gpg
import itertools import itertools
@ -27,6 +26,8 @@ import time
import support import support
support.assert_gpg_version((2, 1, 2)) support.assert_gpg_version((2, 1, 2))
del absolute_import, print_function, unicode_literals
alpha = "Alpha <alpha@invalid.example.net>" alpha = "Alpha <alpha@invalid.example.net>"
with support.EphemeralContext() as ctx: with support.EphemeralContext() as ctx:
@ -51,14 +52,16 @@ with support.EphemeralContext() as ctx:
res2 = ctx.create_key(alpha, force=True) res2 = ctx.create_key(alpha, force=True)
assert res.fpr != res2.fpr assert res.fpr != res2.fpr
# From here on, we use one context, and create unique UIDs # From here on, we use one context, and create unique UIDs
uid_counter = 0 uid_counter = 0
def make_uid(): def make_uid():
global uid_counter global uid_counter
uid_counter += 1 uid_counter += 1
return "user{0}@invalid.example.org".format(uid_counter) return "user{0}@invalid.example.org".format(uid_counter)
with support.EphemeralContext() as ctx: with support.EphemeralContext() as ctx:
# Check gpg.constants.create.NOEXPIRE... # Check gpg.constants.create.NOEXPIRE...
res = ctx.create_key(make_uid(), expires=False) res = ctx.create_key(make_uid(), expires=False)
@ -77,10 +80,8 @@ with support.EphemeralContext() as ctx:
"Primary keys expiration time is off" "Primary keys expiration time is off"
# Check capabilities # Check capabilities
for sign, encrypt, certify, authenticate in itertools.product([False, True], for sign, encrypt, certify, authenticate in itertools.
[False, True], product([False, True], [False, True], [False, True], [False, True]):
[False, True],
[False, True]):
# Filter some out # Filter some out
if not (sign or encrypt or certify or authenticate): if not (sign or encrypt or certify or authenticate):
# This triggers the default capabilities tested before. # This triggers the default capabilities tested before.
@ -89,9 +90,13 @@ with support.EphemeralContext() as ctx:
# The primary key always certifies. # The primary key always certifies.
continue continue
res = ctx.create_key(make_uid(), algorithm="rsa", res = ctx.create_key(
sign=sign, encrypt=encrypt, certify=certify, make_uid(),
authenticate=authenticate) algorithm="rsa",
sign=sign,
encrypt=encrypt,
certify=certify,
authenticate=authenticate)
key = ctx.get_key(res.fpr, secret=True) key = ctx.get_key(res.fpr, secret=True)
assert key.fpr == res.fpr assert key.fpr == res.fpr
assert len(key.subkeys) == 1, \ assert len(key.subkeys) == 1, \
@ -125,13 +130,16 @@ with support.EphemeralContext() as ctx:
recipient = make_uid() recipient = make_uid()
passphrase = "streng geheim" passphrase = "streng geheim"
res = ctx.create_key(recipient, passphrase=passphrase) res = ctx.create_key(recipient, passphrase=passphrase)
ciphertext, _, _ = ctx.encrypt(b"hello there", recipients=[ctx.get_key(res.fpr)]) ciphertext, _, _ = ctx.encrypt(
b"hello there", recipients=[ctx.get_key(res.fpr)])
cb_called = False cb_called = False
def cb(*args): def cb(*args):
global cb_called global cb_called
cb_called = True cb_called = True
return passphrase return passphrase
ctx.pinentry_mode = gpg.constants.PINENTRY_MODE_LOOPBACK ctx.pinentry_mode = gpg.constants.PINENTRY_MODE_LOOPBACK
ctx.set_passphrase_cb(cb) ctx.set_passphrase_cb(cb)

View File

@ -18,7 +18,6 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import os import os
import gpg import gpg
@ -27,6 +26,8 @@ import sys
import support import support
support.assert_gpg_version((2, 1, 14)) support.assert_gpg_version((2, 1, 14))
del absolute_import, print_function, unicode_literals
alpha = "Alpha <alpha@invalid.example.net>" alpha = "Alpha <alpha@invalid.example.net>"
bravo = "Bravo <bravo@invalid.example.net>" bravo = "Bravo <bravo@invalid.example.net>"
@ -111,9 +112,11 @@ with support.EphemeralContext() as ctx:
ctx.key_tofu_policy(key, policy) ctx.key_tofu_policy(key, policy)
keys = list(ctx.keylist(key.uids[0].uid, keys = list(
mode=(gpg.constants.keylist.mode.LOCAL ctx.keylist(
|gpg.constants.keylist.mode.WITH_TOFU))) key.uids[0].uid,
mode=(gpg.constants.keylist.mode.LOCAL |
gpg.constants.keylist.mode.WITH_TOFU)))
assert len(keys) == 1 assert len(keys) == 1
if policy == gpg.constants.tofu.policy.AUTO: if policy == gpg.constants.tofu.policy.AUTO:

View File

@ -18,7 +18,6 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import gpg import gpg
import itertools import itertools
@ -27,8 +26,11 @@ import time
import support import support
support.assert_gpg_version((2, 1, 1)) support.assert_gpg_version((2, 1, 1))
del absolute_import, print_function, unicode_literals
with support.EphemeralContext() as ctx: with support.EphemeralContext() as ctx:
uid_counter = 0 uid_counter = 0
def make_uid(): def make_uid():
global uid_counter global uid_counter
uid_counter += 1 uid_counter += 1
@ -43,10 +45,16 @@ with support.EphemeralContext() as ctx:
return key, uids return key, uids
def check_sigs(key, expected_sigs): def check_sigs(key, expected_sigs):
keys = list(ctx.keylist(key.fpr, mode=(gpg.constants.keylist.mode.LOCAL keys = list(
|gpg.constants.keylist.mode.SIGS))) ctx.keylist(
key.fpr,
mode=(gpg.constants.keylist.mode.LOCAL |
gpg.constants.keylist.mode.SIGS)))
assert len(keys) == 1 assert len(keys) == 1
key_uids = {uid.uid: [s for s in uid.signatures] for uid in keys[0].uids} key_uids = {
uid.uid: [s for s in uid.signatures]
for uid in keys[0].uids
}
expected = list(expected_sigs) expected = list(expected_sigs)
while key_uids and expected: while key_uids and expected:
@ -76,9 +84,12 @@ with support.EphemeralContext() as ctx:
assert s.exportable assert s.exportable
assert s.expires == 0 assert s.expires == 0
check_sigs(key_b, itertools.product(uids_b, [key_b], [exportable_non_expiring])) check_sigs(key_b,
itertools.product(uids_b, [key_b], [exportable_non_expiring]))
ctx.key_sign(key_b) ctx.key_sign(key_b)
check_sigs(key_b, itertools.product(uids_b, [key_b, key_a], [exportable_non_expiring])) check_sigs(
key_b,
itertools.product(uids_b, [key_b, key_a], [exportable_non_expiring]))
# Create a non-exportable signature, and explicitly name all uids. # Create a non-exportable signature, and explicitly name all uids.
key_c, uids_c = make_key() key_c, uids_c = make_key()
@ -89,11 +100,12 @@ with support.EphemeralContext() as ctx:
assert s.expires == 0 assert s.expires == 0
ctx.key_sign(key_c, local=True, uids=uids_c) ctx.key_sign(key_c, local=True, uids=uids_c)
check_sigs(key_c, check_sigs(
list(itertools.product(uids_c, [key_c], key_c,
[exportable_non_expiring])) list(itertools.product(uids_c, [key_c], [exportable_non_expiring])) +
+ list(itertools.product(uids_c, [key_b, key_a], list(
[non_exportable_non_expiring]))) itertools.product(uids_c, [key_b, key_a],
[non_exportable_non_expiring])))
# Create a non-exportable, expiring signature for a single uid. # Create a non-exportable, expiring signature for a single uid.
key_d, uids_d = make_key() key_d, uids_d = make_key()
@ -106,16 +118,16 @@ with support.EphemeralContext() as ctx:
assert abs(time.time() + expires_in - s.expires) < slack assert abs(time.time() + expires_in - s.expires) < slack
ctx.key_sign(key_d, local=True, expires_in=expires_in, uids=uids_d[0]) ctx.key_sign(key_d, local=True, expires_in=expires_in, uids=uids_d[0])
check_sigs(key_d, check_sigs(
list(itertools.product(uids_d, [key_d], key_d,
[exportable_non_expiring])) list(itertools.product(uids_d, [key_d], [exportable_non_expiring])) +
+ list(itertools.product(uids_d[:1], [key_c], list(
[non_exportable_expiring]))) itertools.product(uids_d[:1], [key_c], [non_exportable_expiring])))
# Now sign the second in the same fashion, but use a singleton list. # Now sign the second in the same fashion, but use a singleton list.
ctx.key_sign(key_d, local=True, expires_in=expires_in, uids=uids_d[1:2]) ctx.key_sign(key_d, local=True, expires_in=expires_in, uids=uids_d[1:2])
check_sigs(key_d, check_sigs(
list(itertools.product(uids_d, [key_d], key_d,
[exportable_non_expiring])) list(itertools.product(uids_d, [key_d], [exportable_non_expiring])) +
+ list(itertools.product(uids_d[:2], [key_c], list(
[non_exportable_expiring]))) itertools.product(uids_d[:2], [key_c], [non_exportable_expiring])))

View File

@ -18,7 +18,6 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import gpg import gpg
import itertools import itertools
@ -26,6 +25,8 @@ import time
import support import support
del absolute_import, print_function, unicode_literals
alpha = "Alpha <alpha@invalid.example.net>" alpha = "Alpha <alpha@invalid.example.net>"
bravo = "Bravo <bravo@invalid.example.net>" bravo = "Bravo <bravo@invalid.example.net>"
@ -59,16 +60,15 @@ with support.EphemeralContext() as ctx:
"subkeys expiration time is off" "subkeys expiration time is off"
# Check capabilities # Check capabilities
for sign, encrypt, authenticate in itertools.product([False, True], for sign, encrypt, authenticate in itertools.
[False, True], product([False, True], [False, True], [False, True]):
[False, True]):
# Filter some out # Filter some out
if not (sign or encrypt or authenticate): if not (sign or encrypt or authenticate):
# This triggers the default capabilities tested before. # This triggers the default capabilities tested before.
continue continue
res = ctx.create_subkey(key, sign=sign, encrypt=encrypt, res = ctx.create_subkey(
authenticate=authenticate) key, sign=sign, encrypt=encrypt, authenticate=authenticate)
subkey = get_subkey(res.fpr) subkey = get_subkey(res.fpr)
assert sign == subkey.can_sign assert sign == subkey.can_sign
assert encrypt == subkey.can_encrypt assert encrypt == subkey.can_encrypt
@ -92,18 +92,21 @@ with support.EphemeralContext() as ctx:
# so that we have a key with just one encryption subkey. # so that we have a key with just one encryption subkey.
bravo_res = ctx.create_key(bravo, certify=True) bravo_res = ctx.create_key(bravo, certify=True)
bravo_key = ctx.get_key(bravo_res.fpr) bravo_key = ctx.get_key(bravo_res.fpr)
assert len(bravo_key.subkeys) == 1, "Expected one primary key and no subkeys" assert len(
bravo_key.subkeys) == 1, "Expected one primary key and no subkeys"
passphrase = "streng geheim" passphrase = "streng geheim"
res = ctx.create_subkey(bravo_key, passphrase=passphrase) res = ctx.create_subkey(bravo_key, passphrase=passphrase)
ciphertext, _, _ = ctx.encrypt(b"hello there", ciphertext, _, _ = ctx.encrypt(
recipients=[ctx.get_key(bravo_res.fpr)]) b"hello there", recipients=[ctx.get_key(bravo_res.fpr)])
cb_called = False cb_called = False
def cb(*args): def cb(*args):
global cb_called global cb_called
cb_called = True cb_called = True
return passphrase return passphrase
ctx.pinentry_mode = gpg.constants.PINENTRY_MODE_LOOPBACK ctx.pinentry_mode = gpg.constants.PINENTRY_MODE_LOOPBACK
ctx.set_passphrase_cb(cb) ctx.set_passphrase_cb(cb)

View File

@ -18,29 +18,30 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import os import os
import gpg import gpg
import support import support
_ = support # to appease pyflakes. _ = support # to appease pyflakes.
del absolute_import, print_function, unicode_literals
expected_notations = { expected_notations = {
"laughing@me": ("Just Squeeze Me", gpg.constants.sig.notation.HUMAN_READABLE), "laughing@me": ("Just Squeeze Me",
"preferred-email-encoding@pgp.com": ("pgpmime", gpg.constants.sig.notation.HUMAN_READABLE),
gpg.constants.sig.notation.HUMAN_READABLE "preferred-email-encoding@pgp.com":
| gpg.constants.sig.notation.CRITICAL), ("pgpmime", gpg.constants.sig.notation.HUMAN_READABLE |
gpg.constants.sig.notation.CRITICAL),
None: ("http://www.gnu.org/policy/", 0), None: ("http://www.gnu.org/policy/", 0),
} }
# GnuPG prior to 2.1.13 did not report the critical flag correctly. # GnuPG prior to 2.1.13 did not report the critical flag correctly.
with gpg.Context() as c: with gpg.Context() as c:
version = c.engine_info.version version = c.engine_info.version
have_correct_sig_data = not (version.startswith("1.") have_correct_sig_data = not (
or version.startswith("2.0.") version.startswith("1.") or version.startswith("2.0.") or
or version == "2.1.1" (version.startswith("2.1.") and int(version[4:]) < 13))
or (version.startswith("2.1.1")
and version[5] < '3'))
def check_result(result): def check_result(result):
assert len(result.signatures) == 1, "Unexpected number of signatures" assert len(result.signatures) == 1, "Unexpected number of signatures"
@ -48,8 +49,8 @@ def check_result(result):
assert len(sig.notations) == len(expected_notations) assert len(sig.notations) == len(expected_notations)
for r in sig.notations: for r in sig.notations:
assert not 'name_len' in dir(r) assert 'name_len' not in dir(r)
assert not 'value_len' in dir(r) assert 'value_len' not in dir(r)
assert r.name in expected_notations assert r.name in expected_notations
value, flags = expected_notations.pop(r.name) value, flags = expected_notations.pop(r.name)
@ -63,6 +64,7 @@ def check_result(result):
assert len(expected_notations) == 0 assert len(expected_notations) == 0
source = gpg.Data("Hallo Leute\n") source = gpg.Data("Hallo Leute\n")
signed = gpg.Data() signed = gpg.Data()

View File

@ -18,15 +18,18 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import os import os
import gpg import gpg
import support import support
del absolute_import, print_function, unicode_literals
def fail(msg): def fail(msg):
raise RuntimeError(msg) raise RuntimeError(msg)
def check_result(r, typ): def check_result(r, typ):
if r.invalid_signers: if r.invalid_signers:
fail("Invalid signer found: {}".format(r.invalid_signers.fpr)) fail("Invalid signer found: {}".format(r.invalid_signers.fpr))
@ -43,16 +46,15 @@ def check_result(r, typ):
signature.pubkey_algo)) signature.pubkey_algo))
if signature.hash_algo != gpg.constants.md.SHA1: if signature.hash_algo != gpg.constants.md.SHA1:
fail("Wrong hash algorithm reported: {}".format( fail("Wrong hash algorithm reported: {}".format(signature.hash_algo))
signature.hash_algo))
if signature.sig_class != 1: if signature.sig_class != 1:
fail("Wrong signature class reported: {}".format( fail("Wrong signature class reported: {}".format(signature.sig_class))
signature.sig_class))
if signature.fpr != "A0FF4590BB6122EDEF6E3C542D727CC768697734": if signature.fpr != "A0FF4590BB6122EDEF6E3C542D727CC768697734":
fail("Wrong fingerprint reported: {}".format(signature.fpr)) fail("Wrong fingerprint reported: {}".format(signature.fpr))
c = gpg.Context() c = gpg.Context()
c.set_textmode(True) c.set_textmode(True)
c.set_armor(True) c.set_armor(True)

View File

@ -18,14 +18,17 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import gpg import gpg
import support import support
del absolute_import, print_function, unicode_literals
def fail(msg): def fail(msg):
raise RuntimeError(msg) raise RuntimeError(msg)
def check_result(r, typ): def check_result(r, typ):
if r.invalid_signers: if r.invalid_signers:
fail("Invalid signer found: {}".format(r.invalid_signers.fpr)) fail("Invalid signer found: {}".format(r.invalid_signers.fpr))
@ -53,6 +56,7 @@ def check_result(r, typ):
"23FD347A419429BACCD5E72D6BC4778054ACD246"): "23FD347A419429BACCD5E72D6BC4778054ACD246"):
fail("Wrong fingerprint reported: {}".format(signature.fpr)) fail("Wrong fingerprint reported: {}".format(signature.fpr))
c = gpg.Context() c = gpg.Context()
c.set_textmode(True) c.set_textmode(True)
c.set_armor(True) c.set_armor(True)

View File

@ -18,18 +18,21 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import gpg import gpg
import support import support
_ = support # to appease pyflakes. _ = support # to appease pyflakes.
del absolute_import, print_function, unicode_literals
c = gpg.Context() c = gpg.Context()
def dump_item(item): def dump_item(item):
print("l={} k={} t={} o={} v={} u={}".format( print("l={} k={} t={} o={} v={} u={}".format(item.level, item.keyid,
item.level, item.keyid, item.type, item.owner_trust, item.type, item.owner_trust,
item.validity, item.name)) item.validity, item.name))
c.op_trustlist_start("alice", 0) c.op_trustlist_start("alice", 0)
while True: while True:

View File

@ -18,16 +18,17 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import sys import sys
import os import os
import gpg import gpg
import support import support
_ = support # to appease pyflakes. _ = support # to appease pyflakes.
del absolute_import, print_function, unicode_literals
test_text1 = b"Just GNU it!\n" test_text1 = b"Just GNU it!\n"
test_text1f= b"Just GNU it?\n" test_text1f = b"Just GNU it?\n"
test_sig1 = b"""-----BEGIN PGP SIGNATURE----- test_sig1 = b"""-----BEGIN PGP SIGNATURE-----
iN0EABECAJ0FAjoS+i9FFIAAAAAAAwA5YmFyw7bDpMO8w58gZGFzIHdhcmVuIFVt iN0EABECAJ0FAjoS+i9FFIAAAAAAAwA5YmFyw7bDpMO8w58gZGFzIHdhcmVuIFVt
@ -60,6 +61,7 @@ UqVooWlGXHwNw/xg/fVzt9VNbtjtJ/fhUqYo0/LyCGEA
-----END PGP MESSAGE----- -----END PGP MESSAGE-----
""" """
def check_result(result, summary, validity, fpr, status, notation): def check_result(result, summary, validity, fpr, status, notation):
assert len(result.signatures) == 1, "Unexpected number of signatures" assert len(result.signatures) == 1, "Unexpected number of signatures"
sig = result.signatures[0] sig = result.signatures[0]
@ -76,14 +78,16 @@ def check_result(result, summary, validity, fpr, status, notation):
if sys.version_info[0] < 3 else if sys.version_info[0] < 3 else
b"\xc3\xb6\xc3\xa4\xc3\xbc\xc3\x9f".decode() + b"\xc3\xb6\xc3\xa4\xc3\xbc\xc3\x9f".decode() +
" das waren Umlaute und jetzt ein prozent%-Zeichen"), " das waren Umlaute und jetzt ein prozent%-Zeichen"),
"foobar.1": "this is a notation data with 2 lines", "foobar.1":
None: "http://www.gu.org/policy/", "this is a notation data with 2 lines",
None:
"http://www.gu.org/policy/",
} }
assert len(sig.notations) == len(expected_notations) assert len(sig.notations) == len(expected_notations)
for r in sig.notations: for r in sig.notations:
assert not 'name_len' in dir(r) assert 'name_len' not in dir(r)
assert not 'value_len' in dir(r) assert 'value_len' not in dir(r)
assert r.name in expected_notations assert r.name in expected_notations
assert r.value == expected_notations[r.name], \ assert r.value == expected_notations[r.name], \
"Expected {!r}, got {!r}".format(expected_notations[r.name], "Expected {!r}, got {!r}".format(expected_notations[r.name],
@ -96,7 +100,9 @@ def check_result(result, summary, validity, fpr, status, notation):
assert sig.validity == validity, \ assert sig.validity == validity, \
"Unexpected signature validity: {}, want: {}".format( "Unexpected signature validity: {}, want: {}".format(
sig.validity, validity) sig.validity, validity)
assert gpg.errors.GPGMEError(sig.validity_reason).getcode() == gpg.errors.NO_ERROR assert gpg.errors.GPGMEError(
sig.validity_reason).getcode() == gpg.errors.NO_ERROR
c = gpg.Context() c = gpg.Context()
c.set_armor(True) c.set_armor(True)
@ -108,9 +114,8 @@ c.op_verify(sig, text, None)
result = c.op_verify_result() result = c.op_verify_result()
check_result(result, gpg.constants.sigsum.VALID | gpg.constants.sigsum.GREEN, check_result(result, gpg.constants.sigsum.VALID | gpg.constants.sigsum.GREEN,
gpg.constants.validity.FULL, gpg.constants.validity.FULL,
"A0FF4590BB6122EDEF6E3C542D727CC768697734", "A0FF4590BB6122EDEF6E3C542D727CC768697734", gpg.errors.NO_ERROR,
gpg.errors.NO_ERROR, True) True)
# Checking a manipulated message. # Checking a manipulated message.
text = gpg.Data(test_text1f) text = gpg.Data(test_text1f)
@ -127,8 +132,8 @@ c.op_verify(sig, None, text)
result = c.op_verify_result() result = c.op_verify_result()
check_result(result, gpg.constants.sigsum.VALID | gpg.constants.sigsum.GREEN, check_result(result, gpg.constants.sigsum.VALID | gpg.constants.sigsum.GREEN,
gpg.constants.validity.FULL, gpg.constants.validity.FULL,
"A0FF4590BB6122EDEF6E3C542D727CC768697734", "A0FF4590BB6122EDEF6E3C542D727CC768697734", gpg.errors.NO_ERROR,
gpg.errors.NO_ERROR, False) False)
# Checking an invalid message. # Checking an invalid message.
text = gpg.Data() text = gpg.Data()
@ -141,33 +146,32 @@ except Exception as e:
else: else:
assert False, "Expected an error but got none." assert False, "Expected an error but got none."
# Idiomatic interface. # Idiomatic interface.
with gpg.Context(armor=True) as c: with gpg.Context(armor=True) as c:
# Checking a valid message. # Checking a valid message.
_, result = c.verify(test_text1, test_sig1) _, result = c.verify(test_text1, test_sig1)
check_result(result, gpg.constants.sigsum.VALID | gpg.constants.sigsum.GREEN, check_result(
gpg.constants.validity.FULL, result, gpg.constants.sigsum.VALID | gpg.constants.sigsum.GREEN,
"A0FF4590BB6122EDEF6E3C542D727CC768697734", gpg.constants.validity.FULL,
gpg.errors.NO_ERROR, True) "A0FF4590BB6122EDEF6E3C542D727CC768697734", gpg.errors.NO_ERROR, True)
# Checking a manipulated message. # Checking a manipulated message.
try: try:
c.verify(test_text1f, test_sig1) c.verify(test_text1f, test_sig1)
except gpg.errors.BadSignatures as e: except gpg.errors.BadSignatures as e:
check_result(e.result, gpg.constants.sigsum.RED, check_result(e.result, gpg.constants.sigsum.RED,
gpg.constants.validity.UNKNOWN, gpg.constants.validity.UNKNOWN, "2D727CC768697734",
"2D727CC768697734", gpg.errors.BAD_SIGNATURE, False) gpg.errors.BAD_SIGNATURE, False)
else: else:
assert False, "Expected an error but got none." assert False, "Expected an error but got none."
# Checking a normal signature. # Checking a normal signature.
sig = gpg.Data(test_sig2) sig = gpg.Data(test_sig2)
data, result = c.verify(test_sig2) data, result = c.verify(test_sig2)
check_result(result, gpg.constants.sigsum.VALID | gpg.constants.sigsum.GREEN, check_result(
gpg.constants.validity.FULL, result, gpg.constants.sigsum.VALID | gpg.constants.sigsum.GREEN,
"A0FF4590BB6122EDEF6E3C542D727CC768697734", gpg.constants.validity.FULL,
gpg.errors.NO_ERROR, False) "A0FF4590BB6122EDEF6E3C542D727CC768697734", gpg.errors.NO_ERROR, False)
assert data == test_text1 assert data == test_text1
# Checking an invalid message. # Checking an invalid message.

View File

@ -18,12 +18,13 @@
# License along with this program; if not, see <http://www.gnu.org/licenses/>. # License along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals from __future__ import absolute_import, print_function, unicode_literals
del absolute_import, print_function, unicode_literals
import time import time
import gpg import gpg
import support import support
_ = support # to appease pyflakes. _ = support # to appease pyflakes.
del absolute_import, print_function, unicode_literals
c = gpg.Context() c = gpg.Context()
c.set_armor(True) c.set_armor(True)

View File

@ -19,9 +19,9 @@
import gpg import gpg
import support import support
_ = support # to appease pyflakes. _ = support # to appease pyflakes.
d0 = gpg.Data() d0 = gpg.Data()
d0.seek # trigger on-demand-wrapping d0.seek # trigger on-demand-wrapping
assert d0.seek == d0.seek, "Generated wrapper functions are not cached" assert d0.seek == d0.seek, "Generated wrapper functions are not cached"
assert hasattr(gpg.Data, 'seek'), "Generated wrapper functions are not shared" assert hasattr(gpg.Data, 'seek'), "Generated wrapper functions are not shared"