Fixing remaining flake8 lint warnings

This commit is contained in:
Jacob Alexander
2019-12-11 22:44:44 -08:00
parent f9647aa9a7
commit fc75e4083d
21 changed files with 128 additions and 30 deletions

View File

@@ -11,6 +11,3 @@ pytest = "*"
tox = "*" tox = "*"
Jinja2 = "*" Jinja2 = "*"
Cython = "*" Cython = "*"
[requires]
python_version = "3.7"

View File

@@ -6,6 +6,7 @@ import shutil
import struct import struct
import sys import sys
def build_libcapnp(bundle_dir, build_dir): def build_libcapnp(bundle_dir, build_dir):
''' '''
Build capnproto Build capnproto

View File

@@ -20,10 +20,12 @@ from .msg import info
pjoin = os.path.join pjoin = os.path.join
# #
# Constants # Constants
# #
bundled_version = (0, 7, 0) bundled_version = (0, 7, 0)
libcapnp_name = "capnproto-c++-%i.%i.%i.tar.gz" % (bundled_version) libcapnp_name = "capnproto-c++-%i.%i.%i.tar.gz" % (bundled_version)
libcapnp_url = "https://capnproto.org/" + libcapnp_name libcapnp_url = "https://capnproto.org/" + libcapnp_name
@@ -31,6 +33,7 @@ libcapnp_url = "https://capnproto.org/" + libcapnp_name
HERE = os.path.dirname(__file__) HERE = os.path.dirname(__file__)
ROOT = os.path.dirname(HERE) ROOT = os.path.dirname(HERE)
# #
# Utilities # Utilities
# #
@@ -40,11 +43,13 @@ def untgz(archive):
"""Remove .tar.gz""" """Remove .tar.gz"""
return archive.replace('.tar.gz', '') return archive.replace('.tar.gz', '')
def localpath(*args): def localpath(*args):
"""construct an absolute path from a list relative to the root pycapnp directory""" """construct an absolute path from a list relative to the root pycapnp directory"""
plist = [ROOT] + list(args) plist = [ROOT] + list(args)
return os.path.abspath(pjoin(*plist)) return os.path.abspath(pjoin(*plist))
def fetch_archive(savedir, url, fname, force=False): def fetch_archive(savedir, url, fname, force=False):
"""download an archive to a specific location""" """download an archive to a specific location"""
dest = pjoin(savedir, fname) dest = pjoin(savedir, fname)
@@ -59,10 +64,12 @@ def fetch_archive(savedir, url, fname, force=False):
f.write(req.read()) f.write(req.read())
return dest return dest
# #
# libcapnp # libcapnp
# #
def fetch_libcapnp(savedir, url=None): def fetch_libcapnp(savedir, url=None):
"""download and extract libcapnp""" """download and extract libcapnp"""
is_preconfigured = False is_preconfigured = False
@@ -84,4 +91,3 @@ def fetch_libcapnp(savedir, url=None):
else: else:
cpp_dir = os.path.join(with_version, 'c++') cpp_dir = os.path.join(with_version, 'c++')
shutil.move(cpp_dir, dest) shutil.move(cpp_dir, dest)

View File

@@ -15,6 +15,7 @@
# Utility functions (adapted from h5py: http://h5py.googlecode.com) # Utility functions (adapted from h5py: http://h5py.googlecode.com)
# #
def v_str(v_tuple): def v_str(v_tuple):
"""turn (2,0,1) into '2.0.1'.""" """turn (2,0,1) into '2.0.1'."""
return ".".join(str(x) for x in v_tuple) return ".".join(str(x) for x in v_tuple)

View File

@@ -32,6 +32,7 @@ pjoin = os.path.join
# Utility functions (adapted from h5py: http://h5py.googlecode.com) # Utility functions (adapted from h5py: http://h5py.googlecode.com)
# #
def test_compilation(cfile, compiler=None, **compiler_attrs): def test_compilation(cfile, compiler=None, **compiler_attrs):
"""Test simple compilation with given settings""" """Test simple compilation with given settings"""
cc = get_compiler(compiler, **compiler_attrs) cc = get_compiler(compiler, **compiler_attrs)

View File

@@ -24,9 +24,11 @@ def customize_mingw(cc):
if 'msvcr90' in cc.dll_libraries: if 'msvcr90' in cc.dll_libraries:
cc.dll_libraries.remove('msvcr90') cc.dll_libraries.remove('msvcr90')
def customize_msvc(cc): def customize_msvc(cc):
pass pass
def get_compiler(compiler, **compiler_attrs): def get_compiler(compiler, **compiler_attrs):
"""get and customize a compiler""" """get and customize a compiler"""
if compiler is None or isinstance(compiler, str): if compiler is None or isinstance(compiler, str):

View File

@@ -21,23 +21,28 @@ else:
logger.setLevel(logging.INFO) logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler(sys.stderr)) logger.addHandler(logging.StreamHandler(sys.stderr))
def debug(msg): def debug(msg):
"""Debug""" """Debug"""
logger.debug(msg) logger.debug(msg)
def info(msg): def info(msg):
"""Info""" """Info"""
logger.info(msg) logger.info(msg)
def fatal(msg, code=1): def fatal(msg, code=1):
"""Fatal""" """Fatal"""
logger.error("Fatal: %s", msg) logger.error("Fatal: %s", msg)
exit(code) exit(code)
def warn(msg): def warn(msg):
"""Warning""" """Warning"""
logger.error("Warning: %s", msg) logger.error("Warning: %s", msg)
def line(c='*', width=48): def line(c='*', width=48):
"""Horizontal rule""" """Horizontal rule"""
print(c * (width // len(c))) print(c * (width // len(c)))

View File

@@ -14,8 +14,10 @@ from .misc import get_output_error
pjoin = os.path.join pjoin = os.path.join
# LIB_PAT from delocate # LIB_PAT from delocate
LIB_PAT = re.compile(r"\s*(.*) \(compatibility version (\d+\.\d+\.\d+), " LIB_PAT = re.compile(
r"current version (\d+\.\d+\.\d+)\)") r"\s*(.*) \(compatibility version (\d+\.\d+\.\d+), current version (\d+\.\d+\.\d+)\)"
)
def _get_libs(fname): def _get_libs(fname):
rc, so, se = get_output_error(['otool', '-L', fname]) rc, so, se = get_output_error(['otool', '-L', fname])
@@ -27,6 +29,7 @@ def _get_libs(fname):
if m: if m:
yield m.group(1) yield m.group(1)
def _find_library(lib, path): def _find_library(lib, path):
"""Find a library""" """Find a library"""
for d in path[::-1]: for d in path[::-1]:
@@ -35,11 +38,13 @@ def _find_library(lib, path):
return real_lib return real_lib
return None return None
def _install_name_change(fname, lib, real_lib): def _install_name_change(fname, lib, real_lib):
rc, so, se = get_output_error(['install_name_tool', '-change', lib, real_lib, fname]) rc, so, se = get_output_error(['install_name_tool', '-change', lib, real_lib, fname])
if rc: if rc:
logging.error("Couldn't update load path: %s", se) logging.error("Couldn't update load path: %s", se)
def patch_lib_paths(fname, library_dirs): def patch_lib_paths(fname, library_dirs):
"""Load any weakly-defined libraries from their real location """Load any weakly-defined libraries from their real location

View File

@@ -6,6 +6,7 @@ import sys
from jinja2 import Environment, PackageLoader from jinja2 import Environment, PackageLoader
import os import os
def find_type(code, id): def find_type(code, id):
for node in code['nodes']: for node in code['nodes']:
if node['id'] == id: if node['id'] == id:
@@ -13,6 +14,7 @@ def find_type(code, id):
return None return None
def main(): def main():
env = Environment(loader=PackageLoader('capnp', 'templates')) env = Environment(loader=PackageLoader('capnp', 'templates'))
env.filters['format_name'] = lambda name: name[name.find(':') + 1:] env.filters['format_name'] = lambda name: name[name.find(':') + 1:]

View File

@@ -1,10 +1,11 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from __future__ import print_function from __future__ import print_function
import capnp # noqa: F401 import capnp # noqa: F401
import addressbook_capnp import addressbook_capnp
def writeAddressBook(file): def writeAddressBook(file):
addresses = addressbook_capnp.AddressBook.new_message() addresses = addressbook_capnp.AddressBook.new_message()
people = addresses.init('people', 2) people = addresses.init('people', 2)

View File

@@ -5,6 +5,7 @@ import sys
import json import json
import capnp import capnp
def parse_args(): def parse_args():
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument("command") parser.add_argument("command")
@@ -14,6 +15,7 @@ def parse_args():
return parser.parse_args() return parser.parse_args()
def encode(schema_file, struct_name, **kwargs): def encode(schema_file, struct_name, **kwargs):
schema = capnp.load(schema_file) schema = capnp.load(schema_file)
@@ -24,6 +26,7 @@ def encode(schema_file, struct_name, **kwargs):
struct.write(sys.stdout) struct.write(sys.stdout)
def decode(schema_file, struct_name, defaults): def decode(schema_file, struct_name, defaults):
schema = capnp.load(schema_file) schema = capnp.load(schema_file)
@@ -32,6 +35,7 @@ def decode(schema_file, struct_name, defaults):
json.dump(struct.to_dict(defaults), sys.stdout) json.dump(struct.to_dict(defaults), sys.stdout)
def main(): def main():
args = parse_args() args = parse_args()
@@ -39,7 +43,7 @@ def main():
kwargs = vars(args) kwargs = vars(args)
del kwargs['command'] del kwargs['command']
globals()[command](**kwargs) # hacky way to get defined functions, and call function with name=command globals()[command](**kwargs) # hacky way to get defined functions, and call function with name=command
main() main()

View File

@@ -4,15 +4,16 @@ import os
import sys import sys
import capnp import capnp
capnp.add_import_hook([os.getcwd(), "/usr/local/include/"]) # change this to be auto-detected? capnp.add_import_hook([os.getcwd(), "/usr/local/include/"]) # change this to be auto-detected?
import test_capnp # noqa: E402 import test_capnp # noqa: E402
def decode(name): def decode(name):
class_name = name[0].upper() + name[1:] class_name = name[0].upper() + name[1:]
print(getattr(test_capnp, class_name).from_bytes(sys.stdin.read())._short_str()) print(getattr(test_capnp, class_name).from_bytes(sys.stdin.read())._short_str())
def encode(name): def encode(name):
val = getattr(test_capnp, name) val = getattr(test_capnp, name)
class_name = name[0].upper() + name[1:] class_name = name[0].upper() + name[1:]

View File

@@ -4,6 +4,7 @@ import time
import capnp import capnp
import test_capability_capnp as capability import test_capability_capnp as capability
class Server(capability.TestInterface.Server): class Server(capability.TestInterface.Server):
def __init__(self, val=1): def __init__(self, val=1):
self.val = val self.val = val
@@ -20,6 +21,7 @@ class Server(capability.TestInterface.Server):
def bam(self, i, **kwargs): def bam(self, i, **kwargs):
return str(i) + '_test', i return str(i) + '_test', i
class PipelineServer(capability.TestPipeline.Server): class PipelineServer(capability.TestPipeline.Server):
def getCap(self, n, inCap, _context, **kwargs): def getCap(self, n, inCap, _context, **kwargs):
def _then(response): def _then(response):
@@ -29,6 +31,7 @@ class PipelineServer(capability.TestPipeline.Server):
return inCap.foo(i=n).then(_then) return inCap.foo(i=n).then(_then)
def test_client(): def test_client():
client = capability.TestInterface._new_client(Server()) client = capability.TestInterface._new_client(Server())
@@ -61,6 +64,7 @@ def test_client():
with pytest.raises(AttributeError): with pytest.raises(AttributeError):
req.baz = 1 req.baz = 1
def test_simple_client(): def test_simple_client():
client = capability.TestInterface._new_client(Server()) client = capability.TestInterface._new_client(Server())
@@ -69,7 +73,6 @@ def test_simple_client():
assert response.x == '26' assert response.x == '26'
remote = client.foo(i=5) remote = client.foo(i=5)
response = remote.wait() response = remote.wait()
@@ -121,6 +124,7 @@ def test_simple_client():
with pytest.raises(Exception): with pytest.raises(Exception):
remote = client.foo(baz=5) remote = client.foo(baz=5)
def test_pipeline(): def test_pipeline():
client = capability.TestPipeline._new_client(PipelineServer()) client = capability.TestPipeline._new_client(PipelineServer())
foo_client = capability.TestInterface._new_client(Server()) foo_client = capability.TestInterface._new_client(Server())
@@ -136,6 +140,7 @@ def test_pipeline():
response = remote.wait() response = remote.wait()
assert response.s == '26_foo' assert response.s == '26_foo'
class BadServer(capability.TestInterface.Server): class BadServer(capability.TestInterface.Server):
def __init__(self, val=1): def __init__(self, val=1):
self.val = val self.val = val
@@ -144,7 +149,8 @@ class BadServer(capability.TestInterface.Server):
extra = 0 extra = 0
if j: if j:
extra = 1 extra = 1
return str(i * 5 + extra + self.val), 10 # returning too many args return str(i * 5 + extra + self.val), 10 # returning too many args
def test_exception_client(): def test_exception_client():
client = capability.TestInterface._new_client(BadServer()) client = capability.TestInterface._new_client(BadServer())
@@ -153,6 +159,7 @@ def test_exception_client():
with pytest.raises(capnp.KjException): with pytest.raises(capnp.KjException):
remote.wait() remote.wait()
class BadPipelineServer(capability.TestPipeline.Server): class BadPipelineServer(capability.TestPipeline.Server):
def getCap(self, n, inCap, _context, **kwargs): def getCap(self, n, inCap, _context, **kwargs):
def _then(response): def _then(response):
@@ -165,6 +172,7 @@ class BadPipelineServer(capability.TestPipeline.Server):
return inCap.foo(i=n).then(_then, _error) return inCap.foo(i=n).then(_then, _error)
def test_exception_chain(): def test_exception_chain():
client = capability.TestPipeline._new_client(BadPipelineServer()) client = capability.TestPipeline._new_client(BadPipelineServer())
foo_client = capability.TestInterface._new_client(BadServer()) foo_client = capability.TestInterface._new_client(BadServer())
@@ -176,6 +184,7 @@ def test_exception_chain():
except Exception as e: except Exception as e:
assert 'test was a success' in str(e) assert 'test was a success' in str(e)
def test_pipeline_exception(): def test_pipeline_exception():
client = capability.TestPipeline._new_client(BadPipelineServer()) client = capability.TestPipeline._new_client(BadPipelineServer())
foo_client = capability.TestInterface._new_client(BadServer()) foo_client = capability.TestInterface._new_client(BadServer())
@@ -191,6 +200,7 @@ def test_pipeline_exception():
with pytest.raises(Exception): with pytest.raises(Exception):
remote.wait() remote.wait()
def test_casting(): def test_casting():
client = capability.TestExtends._new_client(Server()) client = capability.TestExtends._new_client(Server())
client2 = client.upcast(capability.TestInterface) client2 = client.upcast(capability.TestInterface)
@@ -199,6 +209,7 @@ def test_casting():
with pytest.raises(Exception): with pytest.raises(Exception):
client.upcast(capability.TestPipeline) client.upcast(capability.TestPipeline)
class TailCallOrder(capability.TestCallOrder.Server): class TailCallOrder(capability.TestCallOrder.Server):
def __init__(self): def __init__(self):
self.count = -1 self.count = -1
@@ -207,6 +218,7 @@ class TailCallOrder(capability.TestCallOrder.Server):
self.count += 1 self.count += 1
return self.count return self.count
class TailCaller(capability.TestTailCaller.Server): class TailCaller(capability.TestTailCaller.Server):
def __init__(self): def __init__(self):
self.count = 0 self.count = 0
@@ -217,6 +229,7 @@ class TailCaller(capability.TestTailCaller.Server):
tail = callee.foo_request(i=i, t='from TailCaller') tail = callee.foo_request(i=i, t='from TailCaller')
return _context.tail_call(tail) return _context.tail_call(tail)
class TailCallee(capability.TestTailCallee.Server): class TailCallee(capability.TestTailCallee.Server):
def __init__(self): def __init__(self):
self.count = 0 self.count = 0
@@ -229,6 +242,7 @@ class TailCallee(capability.TestTailCallee.Server):
results.t = t results.t = t
results.c = TailCallOrder() results.c = TailCallOrder()
def test_tail_call(): def test_tail_call():
callee_server = TailCallee() callee_server = TailCallee()
caller_server = TailCaller() caller_server = TailCaller()

View File

@@ -31,6 +31,7 @@ def test_large_read(test_capnp):
del f del f
assert array.rows[0].values[9000] == 9000 assert array.rows[0].values[9000] == 9000
def test_large_read_multiple(test_capnp): def test_large_read_multiple(test_capnp):
f = tempfile.TemporaryFile() f = tempfile.TemporaryFile()
msg1 = test_capnp.Msg.new_message() msg1 = test_capnp.Msg.new_message()
@@ -43,6 +44,7 @@ def test_large_read_multiple(test_capnp):
for m in test_capnp.Msg.read_multiple(f): for m in test_capnp.Msg.read_multiple(f):
pass pass
def get_two_adjacent_messages(test_capnp): def get_two_adjacent_messages(test_capnp):
msg1 = test_capnp.Msg.new_message() msg1 = test_capnp.Msg.new_message()
msg1.data = [0x41] * 8192 msg1.data = [0x41] * 8192
@@ -52,6 +54,7 @@ def get_two_adjacent_messages(test_capnp):
return m1 + m2 return m1 + m2
def test_large_read_multiple_bytes(test_capnp): def test_large_read_multiple_bytes(test_capnp):
data = get_two_adjacent_messages(test_capnp) data = get_two_adjacent_messages(test_capnp)
for m in test_capnp.Msg.read_multiple_bytes(data): for m in test_capnp.Msg.read_multiple_bytes(data):
@@ -67,6 +70,7 @@ def test_large_read_multiple_bytes(test_capnp):
for m in test_capnp.Msg.read_multiple_bytes(data): for m in test_capnp.Msg.read_multiple_bytes(data):
pass pass
@pytest.mark.skipif(platform.python_implementation() == 'PyPy', reason="PyPy memoryview support is limited") @pytest.mark.skipif(platform.python_implementation() == 'PyPy', reason="PyPy memoryview support is limited")
def test_large_read_mutltiple_bytes_memoryview(test_capnp): def test_large_read_mutltiple_bytes_memoryview(test_capnp):
data = get_two_adjacent_messages(test_capnp) data = get_two_adjacent_messages(test_capnp)

View File

@@ -5,28 +5,35 @@ import sys
this_dir = os.path.dirname(__file__) this_dir = os.path.dirname(__file__)
@pytest.fixture @pytest.fixture
def addressbook(): def addressbook():
return capnp.load(os.path.join(this_dir, 'addressbook.capnp')) return capnp.load(os.path.join(this_dir, 'addressbook.capnp'))
@pytest.fixture @pytest.fixture
def foo(): def foo():
return capnp.load(os.path.join(this_dir, 'foo.capnp')) return capnp.load(os.path.join(this_dir, 'foo.capnp'))
@pytest.fixture @pytest.fixture
def bar(): def bar():
return capnp.load(os.path.join(this_dir, 'bar.capnp')) return capnp.load(os.path.join(this_dir, 'bar.capnp'))
def test_basic_load(): def test_basic_load():
capnp.load(os.path.join(this_dir, 'addressbook.capnp')) capnp.load(os.path.join(this_dir, 'addressbook.capnp'))
def test_constants(addressbook): def test_constants(addressbook):
assert addressbook.qux == 123 assert addressbook.qux == 123
def test_classes(addressbook): def test_classes(addressbook):
assert addressbook.AddressBook assert addressbook.AddressBook
assert addressbook.Person assert addressbook.Person
def test_import(foo, bar): def test_import(foo, bar):
m = capnp._MallocMessageBuilder() m = capnp._MallocMessageBuilder()
foo = m.init_root(foo.Foo) foo = m.init_root(foo.Foo)
@@ -38,6 +45,7 @@ def test_import(foo, bar):
assert bar.foo.name == 'foo' assert bar.foo.name == 'foo'
def test_failed_import(): def test_failed_import():
s = capnp.SchemaParser() s = capnp.SchemaParser()
s2 = capnp.SchemaParser() s2 = capnp.SchemaParser()
@@ -55,17 +63,21 @@ def test_failed_import():
with pytest.raises(Exception): with pytest.raises(Exception):
bar.foo = foo bar.foo = foo
def test_defualt_import_hook(): def test_defualt_import_hook():
# Make sure any previous imports of addressbook_capnp are gone # Make sure any previous imports of addressbook_capnp are gone
capnp.cleanup_global_schema_parser() capnp.cleanup_global_schema_parser()
import addressbook_capnp # noqa: F401 import addressbook_capnp # noqa: F401
def test_dash_import(): def test_dash_import():
import addressbook_with_dashes_capnp # noqa: F401 import addressbook_with_dashes_capnp # noqa: F401
def test_spaces_import(): def test_spaces_import():
import addressbook_with_spaces_capnp # noqa: F401 import addressbook_with_spaces_capnp # noqa: F401
def test_add_import_hook(): def test_add_import_hook():
capnp.add_import_hook([this_dir]) capnp.add_import_hook([this_dir])
@@ -76,6 +88,7 @@ def test_add_import_hook():
import addressbook_capnp import addressbook_capnp
addressbook_capnp.AddressBook.new_message() addressbook_capnp.AddressBook.new_message()
def test_multiple_add_import_hook(): def test_multiple_add_import_hook():
capnp.add_import_hook() capnp.add_import_hook()
capnp.add_import_hook() capnp.add_import_hook()
@@ -87,12 +100,14 @@ def test_multiple_add_import_hook():
import addressbook_capnp import addressbook_capnp
addressbook_capnp.AddressBook.new_message() addressbook_capnp.AddressBook.new_message()
def test_remove_import_hook(): def test_remove_import_hook():
capnp.add_import_hook([this_dir]) capnp.add_import_hook([this_dir])
capnp.remove_import_hook() capnp.remove_import_hook()
if 'addressbook_capnp' in sys.modules: if 'addressbook_capnp' in sys.modules:
del sys.modules['addressbook_capnp'] # hack to deal with it being imported already # hack to deal with it being imported already
del sys.modules['addressbook_capnp']
with pytest.raises(ImportError): with pytest.raises(ImportError):
import addressbook_capnp # noqa: F401 import addressbook_capnp # noqa: F401

View File

@@ -18,6 +18,7 @@ else:
def addressbook(): def addressbook():
return capnp.load(os.path.join(this_dir, 'addressbook.capnp')) return capnp.load(os.path.join(this_dir, 'addressbook.capnp'))
def test_addressbook_message_classes(addressbook): def test_addressbook_message_classes(addressbook):
def writeAddressBook(fd): def writeAddressBook(fd):
message = capnp._MallocMessageBuilder() message = capnp._MallocMessageBuilder()
@@ -46,7 +47,6 @@ def test_addressbook_message_classes(addressbook):
capnp._write_packed_message_to_fd(fd, message) capnp._write_packed_message_to_fd(fd, message)
def printAddressBook(fd): def printAddressBook(fd):
message = capnp._PackedFdMessageReader(f) message = capnp._PackedFdMessageReader(f)
addressBook = message.get_root(addressbook.AddressBook) addressBook = message.get_root(addressbook.AddressBook)
@@ -79,6 +79,7 @@ def test_addressbook_message_classes(addressbook):
f = open('example', 'r') f = open('example', 'r')
printAddressBook(f.fileno()) printAddressBook(f.fileno())
def test_addressbook(addressbook): def test_addressbook(addressbook):
def writeAddressBook(file): def writeAddressBook(file):
addresses = addressbook.AddressBook.new_message() addresses = addressbook.AddressBook.new_message()
@@ -106,7 +107,6 @@ def test_addressbook(addressbook):
addresses.write(file) addresses.write(file)
def printAddressBook(file): def printAddressBook(file):
addresses = addressbook.AddressBook.read(file) addresses = addressbook.AddressBook.read(file)
@@ -132,13 +132,13 @@ def test_addressbook(addressbook):
assert bobPhones[1].type == 'work' assert bobPhones[1].type == 'work'
assert bob.employment.unemployed is None assert bob.employment.unemployed is None
f = open('example', 'w') f = open('example', 'w')
writeAddressBook(f) writeAddressBook(f)
f = open('example', 'r') f = open('example', 'r')
printAddressBook(f) printAddressBook(f)
def test_addressbook_resizable(addressbook): def test_addressbook_resizable(addressbook):
def writeAddressBook(file): def writeAddressBook(file):
addresses = addressbook.AddressBook.new_message() addresses = addressbook.AddressBook.new_message()
@@ -168,7 +168,6 @@ def test_addressbook_resizable(addressbook):
addresses.write(file) addresses.write(file)
def printAddressBook(file): def printAddressBook(file):
addresses = addressbook.AddressBook.read(file) addresses = addressbook.AddressBook.read(file)
@@ -194,13 +193,13 @@ def test_addressbook_resizable(addressbook):
assert bobPhones[1].type == 'work' assert bobPhones[1].type == 'work'
assert bob.employment.unemployed is None assert bob.employment.unemployed is None
f = open('example', 'w') f = open('example', 'w')
writeAddressBook(f) writeAddressBook(f)
f = open('example', 'r') f = open('example', 'r')
printAddressBook(f) printAddressBook(f)
def test_addressbook_explicit_fields(addressbook): def test_addressbook_explicit_fields(addressbook):
def writeAddressBook(file): def writeAddressBook(file):
addresses = addressbook.AddressBook.new_message() addresses = addressbook.AddressBook.new_message()
@@ -233,7 +232,6 @@ def test_addressbook_explicit_fields(addressbook):
addresses.write(file) addresses.write(file)
def printAddressBook(file): def printAddressBook(file):
addresses = addressbook.AddressBook.read(file) addresses = addressbook.AddressBook.read(file)
address_fields = addressbook.AddressBook.schema.fields address_fields = addressbook.AddressBook.schema.fields
@@ -264,13 +262,13 @@ def test_addressbook_explicit_fields(addressbook):
employment = bob._get_by_field(person_fields['employment']) employment = bob._get_by_field(person_fields['employment'])
employment._get_by_field(addressbook.Person.Employment.schema.fields['unemployed']) is None employment._get_by_field(addressbook.Person.Employment.schema.fields['unemployed']) is None
f = open('example', 'w') f = open('example', 'w')
writeAddressBook(f) writeAddressBook(f)
f = open('example', 'r') f = open('example', 'r')
printAddressBook(f) printAddressBook(f)
@pytest.fixture @pytest.fixture
def all_types(): def all_types():
return capnp.load(os.path.join(this_dir, 'all_types.capnp')) return capnp.load(os.path.join(this_dir, 'all_types.capnp'))
@@ -280,6 +278,7 @@ def all_types():
# - Build an identical message using Python code and compare it to the golden. # - Build an identical message using Python code and compare it to the golden.
# #
def init_all_types(builder): def init_all_types(builder):
builder.voidField = None builder.voidField = None
builder.boolField = True builder.boolField = True
@@ -358,10 +357,12 @@ def init_all_types(builder):
listBuilder[2].textField = "structlist 3" listBuilder[2].textField = "structlist 3"
builder.enumList = ["foo", "garply"] builder.enumList = ["foo", "garply"]
def assert_almost(float1, float2): def assert_almost(float1, float2):
if float1 != float2: if float1 != float2:
assert abs((float1 - float2) / float1) < 0.00001 assert abs((float1 - float2) / float1) < 0.00001
def check_list(reader, expected): def check_list(reader, expected):
assert len(reader) == len(expected) assert len(reader) == len(expected)
for (i, v) in enumerate(expected): for (i, v) in enumerate(expected):
@@ -370,6 +371,7 @@ def check_list(reader, expected):
else: else:
assert reader[i] == v assert reader[i] == v
def check_all_types(reader): def check_all_types(reader):
assert reader.voidField is None assert reader.voidField is None
assert reader.boolField assert reader.boolField
@@ -483,12 +485,14 @@ def check_all_types(reader):
check_list(reader.enumList, ["foo", "garply"]) check_list(reader.enumList, ["foo", "garply"])
def test_build(all_types): def test_build(all_types):
root = all_types.TestAllTypes.new_message() root = all_types.TestAllTypes.new_message()
init_all_types(root) init_all_types(root)
expectedText = open(os.path.join(this_dir, 'all-types.txt'), 'r', encoding='utf8').read() expectedText = open(os.path.join(this_dir, 'all-types.txt'), 'r', encoding='utf8').read()
assert str(root) + '\n' == expectedText assert str(root) + '\n' == expectedText
def test_build_first_segment_size(all_types): def test_build_first_segment_size(all_types):
root = all_types.TestAllTypes.new_message(1) root = all_types.TestAllTypes.new_message(1)
init_all_types(root) init_all_types(root)
@@ -500,6 +504,7 @@ def test_build_first_segment_size(all_types):
expectedText = open(os.path.join(this_dir, 'all-types.txt'), 'r', encoding='utf8').read() expectedText = open(os.path.join(this_dir, 'all-types.txt'), 'r', encoding='utf8').read()
assert str(root) + '\n' == expectedText assert str(root) + '\n' == expectedText
def test_binary_read(all_types): def test_binary_read(all_types):
f = open(os.path.join(this_dir, 'all-types.binary'), 'r', encoding='utf8') f = open(os.path.join(this_dir, 'all-types.binary'), 'r', encoding='utf8')
root = all_types.TestAllTypes.read(f) root = all_types.TestAllTypes.read(f)
@@ -517,6 +522,7 @@ def test_binary_read(all_types):
builder2.set_root(builder.get_root(all_types.TestAllTypes)) builder2.set_root(builder.get_root(all_types.TestAllTypes))
check_all_types(builder2.get_root(all_types.TestAllTypes)) check_all_types(builder2.get_root(all_types.TestAllTypes))
def test_packed_read(all_types): def test_packed_read(all_types):
f = open(os.path.join(this_dir, 'all-types.packed'), 'r', encoding='utf8') f = open(os.path.join(this_dir, 'all-types.packed'), 'r', encoding='utf8')
root = all_types.TestAllTypes.read_packed(f) root = all_types.TestAllTypes.read_packed(f)
@@ -525,6 +531,7 @@ def test_packed_read(all_types):
expectedText = open(os.path.join(this_dir, 'all-types.txt'), 'r', encoding='utf8').read() expectedText = open(os.path.join(this_dir, 'all-types.txt'), 'r', encoding='utf8').read()
assert str(root) + '\n' == expectedText assert str(root) + '\n' == expectedText
def test_binary_write(all_types): def test_binary_write(all_types):
root = all_types.TestAllTypes.new_message() root = all_types.TestAllTypes.new_message()
init_all_types(root) init_all_types(root)
@@ -532,6 +539,7 @@ def test_binary_write(all_types):
check_all_types(all_types.TestAllTypes.read(open('example', 'r'))) check_all_types(all_types.TestAllTypes.read(open('example', 'r')))
def test_packed_write(all_types): def test_packed_write(all_types):
root = all_types.TestAllTypes.new_message() root = all_types.TestAllTypes.new_message()
init_all_types(root) init_all_types(root)

View File

@@ -1,5 +1,6 @@
import test_response_capnp import test_response_capnp
class FooServer(test_response_capnp.Foo.Server): class FooServer(test_response_capnp.Foo.Server):
def __init__(self, val=1): def __init__(self, val=1):
self.val = val self.val = val
@@ -7,6 +8,7 @@ class FooServer(test_response_capnp.Foo.Server):
def foo(self, **kwargs): def foo(self, **kwargs):
return 1 return 1
class BazServer(test_response_capnp.Baz.Server): class BazServer(test_response_capnp.Baz.Server):
def __init__(self, val=1): def __init__(self, val=1):
self.val = val self.val = val
@@ -14,6 +16,7 @@ class BazServer(test_response_capnp.Baz.Server):
def grault(self, **kwargs): def grault(self, **kwargs):
return {"foo": FooServer()} return {"foo": FooServer()}
def test_response_reference(): def test_response_reference():
baz = test_response_capnp.Baz._new_client(BazServer()) baz = test_response_capnp.Baz._new_client(BazServer())
@@ -23,6 +26,7 @@ def test_response_reference():
# This used to cause an exception about invalid pointers because the response got garbage collected # This used to cause an exception about invalid pointers because the response got garbage collected
assert foo.foo().wait().val == 1 assert foo.foo().wait().val == 1
def test_response_reference2(): def test_response_reference2():
baz = test_response_capnp.Baz._new_client(BazServer()) baz = test_response_capnp.Baz._new_client(BazServer())

View File

@@ -11,8 +11,8 @@ import capnp
examples_dir = os.path.join(os.path.dirname(__file__), '..', 'examples') examples_dir = os.path.join(os.path.dirname(__file__), '..', 'examples')
sys.path.append(examples_dir) sys.path.append(examples_dir)
import calculator_client # noqa: E402 import calculator_client # noqa: E402
import calculator_server # noqa: E402 import calculator_server # noqa: E402
def test_calculator(): def test_calculator():
@@ -78,6 +78,7 @@ def test_calculator_unix():
address = 'unix:' + path address = 'unix:' + path
run_subprocesses(address) run_subprocesses(address)
def test_calculator_gc(): def test_calculator_gc():
def new_evaluate_impl(old_evaluate_impl): def new_evaluate_impl(old_evaluate_impl):
def call(*args, **kwargs): def call(*args, **kwargs):

View File

@@ -10,10 +10,12 @@ import sys
this_dir = os.path.dirname(__file__) this_dir = os.path.dirname(__file__)
@pytest.fixture @pytest.fixture
def all_types(): def all_types():
return capnp.load(os.path.join(this_dir, 'all_types.capnp')) return capnp.load(os.path.join(this_dir, 'all_types.capnp'))
def test_roundtrip_file(all_types): def test_roundtrip_file(all_types):
f = tempfile.TemporaryFile() f = tempfile.TemporaryFile()
msg = all_types.TestAllTypes.new_message() msg = all_types.TestAllTypes.new_message()
@@ -24,6 +26,7 @@ def test_roundtrip_file(all_types):
msg = all_types.TestAllTypes.read(f) msg = all_types.TestAllTypes.read(f)
test_regression.check_all_types(msg) test_regression.check_all_types(msg)
def test_roundtrip_file_packed(all_types): def test_roundtrip_file_packed(all_types):
f = tempfile.TemporaryFile() f = tempfile.TemporaryFile()
msg = all_types.TestAllTypes.new_message() msg = all_types.TestAllTypes.new_message()
@@ -34,6 +37,7 @@ def test_roundtrip_file_packed(all_types):
msg = all_types.TestAllTypes.read_packed(f) msg = all_types.TestAllTypes.read_packed(f)
test_regression.check_all_types(msg) test_regression.check_all_types(msg)
def test_roundtrip_bytes(all_types): def test_roundtrip_bytes(all_types):
msg = all_types.TestAllTypes.new_message() msg = all_types.TestAllTypes.new_message()
test_regression.init_all_types(msg) test_regression.init_all_types(msg)
@@ -42,6 +46,7 @@ def test_roundtrip_bytes(all_types):
msg = all_types.TestAllTypes.from_bytes(message_bytes) msg = all_types.TestAllTypes.from_bytes(message_bytes)
test_regression.check_all_types(msg) test_regression.check_all_types(msg)
@pytest.mark.skipif( @pytest.mark.skipif(
platform.python_implementation() == 'PyPy', platform.python_implementation() == 'PyPy',
reason="TODO: Investigate why this works on CPython but fails on PyPy." reason="TODO: Investigate why this works on CPython but fails on PyPy."
@@ -53,6 +58,7 @@ def test_roundtrip_segments(all_types):
msg = all_types.TestAllTypes.from_segments(segments) msg = all_types.TestAllTypes.from_segments(segments)
test_regression.check_all_types(msg) test_regression.check_all_types(msg)
@pytest.mark.skipif(sys.version_info[0] < 3, reason="mmap doesn't implement the buffer interface under python 2.") @pytest.mark.skipif(sys.version_info[0] < 3, reason="mmap doesn't implement the buffer interface under python 2.")
def test_roundtrip_bytes_mmap(all_types): def test_roundtrip_bytes_mmap(all_types):
msg = all_types.TestAllTypes.new_message() msg = all_types.TestAllTypes.new_message()
@@ -68,6 +74,7 @@ def test_roundtrip_bytes_mmap(all_types):
msg = all_types.TestAllTypes.from_bytes(memory) msg = all_types.TestAllTypes.from_bytes(memory)
test_regression.check_all_types(msg) test_regression.check_all_types(msg)
@pytest.mark.skipif(sys.version_info[0] < 3, reason="memoryview is a builtin on Python 3") @pytest.mark.skipif(sys.version_info[0] < 3, reason="memoryview is a builtin on Python 3")
def test_roundtrip_bytes_buffer(all_types): def test_roundtrip_bytes_buffer(all_types):
msg = all_types.TestAllTypes.new_message() msg = all_types.TestAllTypes.new_message()
@@ -78,10 +85,12 @@ def test_roundtrip_bytes_buffer(all_types):
msg = all_types.TestAllTypes.from_bytes(v) msg = all_types.TestAllTypes.from_bytes(v)
test_regression.check_all_types(msg) test_regression.check_all_types(msg)
def test_roundtrip_bytes_fail(all_types): def test_roundtrip_bytes_fail(all_types):
with pytest.raises(TypeError): with pytest.raises(TypeError):
all_types.TestAllTypes.from_bytes(42) all_types.TestAllTypes.from_bytes(42)
@pytest.mark.skipif( @pytest.mark.skipif(
platform.python_implementation() == 'PyPy', platform.python_implementation() == 'PyPy',
reason="This works in PyPy 4.0.1 but travisci's version of PyPy has some bug that fails this test." reason="This works in PyPy 4.0.1 but travisci's version of PyPy has some bug that fails this test."
@@ -94,6 +103,7 @@ def test_roundtrip_bytes_packed(all_types):
msg = all_types.TestAllTypes.from_bytes_packed(message_bytes) msg = all_types.TestAllTypes.from_bytes_packed(message_bytes)
test_regression.check_all_types(msg) test_regression.check_all_types(msg)
def test_roundtrip_file_multiple(all_types): def test_roundtrip_file_multiple(all_types):
f = tempfile.TemporaryFile() f = tempfile.TemporaryFile()
msg = all_types.TestAllTypes.new_message() msg = all_types.TestAllTypes.new_message()
@@ -109,6 +119,7 @@ def test_roundtrip_file_multiple(all_types):
i += 1 i += 1
assert i == 3 assert i == 3
def test_roundtrip_bytes_multiple(all_types): def test_roundtrip_bytes_multiple(all_types):
msg = all_types.TestAllTypes.new_message() msg = all_types.TestAllTypes.new_message()
test_regression.init_all_types(msg) test_regression.init_all_types(msg)
@@ -123,6 +134,7 @@ def test_roundtrip_bytes_multiple(all_types):
i += 1 i += 1
assert i == 3 assert i == 3
def test_roundtrip_file_multiple_packed(all_types): def test_roundtrip_file_multiple_packed(all_types):
f = tempfile.TemporaryFile() f = tempfile.TemporaryFile()
msg = all_types.TestAllTypes.new_message() msg = all_types.TestAllTypes.new_message()
@@ -138,6 +150,7 @@ def test_roundtrip_file_multiple_packed(all_types):
i += 1 i += 1
assert i == 3 assert i == 3
def test_roundtrip_bytes_multiple_packed(all_types): def test_roundtrip_bytes_multiple_packed(all_types):
msg = all_types.TestAllTypes.new_message() msg = all_types.TestAllTypes.new_message()
test_regression.init_all_types(msg) test_regression.init_all_types(msg)
@@ -152,6 +165,7 @@ def test_roundtrip_bytes_multiple_packed(all_types):
i += 1 i += 1
assert i == 3 assert i == 3
@pytest.mark.skipif( @pytest.mark.skipif(
platform.python_implementation() == 'PyPy', platform.python_implementation() == 'PyPy',
reason="This works on my local PyPy v2.5.0, but is for some reason broken on TravisCI. Skip for now." reason="This works on my local PyPy v2.5.0, but is for some reason broken on TravisCI. Skip for now."
@@ -164,6 +178,7 @@ def test_roundtrip_dict(all_types):
msg = all_types.TestAllTypes.from_dict(d) msg = all_types.TestAllTypes.from_dict(d)
test_regression.check_all_types(msg) test_regression.check_all_types(msg)
def test_file_and_bytes(all_types): def test_file_and_bytes(all_types):
f = tempfile.TemporaryFile() f = tempfile.TemporaryFile()
msg = all_types.TestAllTypes.new_message() msg = all_types.TestAllTypes.new_message()
@@ -174,6 +189,7 @@ def test_file_and_bytes(all_types):
assert f.read() == msg.to_bytes() assert f.read() == msg.to_bytes()
def test_file_and_bytes_packed(all_types): def test_file_and_bytes_packed(all_types):
f = tempfile.TemporaryFile() f = tempfile.TemporaryFile()
msg = all_types.TestAllTypes.new_message() msg = all_types.TestAllTypes.new_message()
@@ -184,6 +200,7 @@ def test_file_and_bytes_packed(all_types):
assert f.read() == msg.to_bytes_packed() assert f.read() == msg.to_bytes_packed()
def test_pickle(all_types): def test_pickle(all_types):
msg = all_types.TestAllTypes.new_message() msg = all_types.TestAllTypes.new_message()
test_regression.init_all_types(msg) test_regression.init_all_types(msg)
@@ -192,6 +209,7 @@ def test_pickle(all_types):
test_regression.check_all_types(msg2) test_regression.check_all_types(msg2)
def test_from_bytes_traversal_limit(all_types): def test_from_bytes_traversal_limit(all_types):
size = 1024 size = 1024
bld = all_types.TestAllTypes.new_message() bld = all_types.TestAllTypes.new_message()
@@ -203,8 +221,10 @@ def test_from_bytes_traversal_limit(all_types):
for i in range(0, size): for i in range(0, size):
msg.structList[i].uInt8Field == 0 msg.structList[i].uInt8Field == 0
msg = all_types.TestAllTypes.from_bytes(data, msg = all_types.TestAllTypes.from_bytes(
traversal_limit_in_words=2**62) data,
traversal_limit_in_words=2**62
)
for i in range(0, size): for i in range(0, size):
assert msg.structList[i].uInt8Field == 0 assert msg.structList[i].uInt8Field == 0
@@ -220,7 +240,9 @@ def test_from_bytes_packed_traversal_limit(all_types):
for i in range(0, size): for i in range(0, size):
msg.structList[i].uInt8Field == 0 msg.structList[i].uInt8Field == 0
msg = all_types.TestAllTypes.from_bytes_packed(data, msg = all_types.TestAllTypes.from_bytes_packed(
traversal_limit_in_words=2**62) data,
traversal_limit_in_words=2**62
)
for i in range(0, size): for i in range(0, size):
assert msg.structList[i].uInt8Field == 0 assert msg.structList[i].uInt8Field == 0

View File

@@ -191,6 +191,7 @@ def test_set_dict_union(addressbook):
assert person.employment.employer.name == 'foo' assert person.employment.employer.name == 'foo'
def isstr(s): def isstr(s):
return isinstance(s, str) return isinstance(s, str)
@@ -238,6 +239,7 @@ def test_to_dict_ordered(addressbook):
with pytest.raises(Exception): with pytest.raises(Exception):
person.to_dict(ordered=True) person.to_dict(ordered=True)
def test_nested_list(addressbook): def test_nested_list(addressbook):
struct = addressbook.NestedList.new_message() struct = addressbook.NestedList.new_message()
struct.init('list', 2) struct.init('list', 2)

View File

@@ -11,6 +11,7 @@ import pytest
import capnp import capnp
import test_capability_capnp import test_capability_capnp
@pytest.mark.skipif( @pytest.mark.skipif(
platform.python_implementation() == 'PyPy', platform.python_implementation() == 'PyPy',
reason="pycapnp's GIL handling isn't working properly at the moment for PyPy" reason="pycapnp's GIL handling isn't working properly at the moment for PyPy"
@@ -25,6 +26,7 @@ def test_making_event_loop():
capnp.remove_event_loop() capnp.remove_event_loop()
capnp.create_event_loop() capnp.create_event_loop()
@pytest.mark.skipif( @pytest.mark.skipif(
platform.python_implementation() == 'PyPy', platform.python_implementation() == 'PyPy',
reason="pycapnp's GIL handling isn't working properly at the moment for PyPy" reason="pycapnp's GIL handling isn't working properly at the moment for PyPy"