Replace black and flake8 with ruff for linting and formatting
- Remove .flake8; add [tool.ruff] and [tool.ruff.format] config in pyproject.toml (line-length 120, excludes, ignore list, per-file-ignores, mccabe complexity) - Update GitHub workflow lint job to run `ruff check .` and `ruff format --check .` - Swap black and flake8 for ruff in requirements.txt and Pipfile - Change capnp/__init__.py to ruff-style noqa comment - Move max-complexity into [tool.ruff.lint.mccabe], lint options into [tool.ruff.lint] - Add per-file-ignores for capnp/__init__.py (F401, F403, F405), remove inline noqa - Run ruff format across codebase (24 files) for consistent style
This commit is contained in:
6
.flake8
6
.flake8
@@ -1,6 +0,0 @@
|
||||
[flake8]
|
||||
max-line-length = 120
|
||||
extend-ignore = E203,E211,E225,E226,E227,E231,E251,E261,E262,E265,E402,E999
|
||||
max-complexity = 10
|
||||
per-file-ignores =
|
||||
test/test_examples.py: C901
|
||||
11
.github/workflows/wheels.yml
vendored
11
.github/workflows/wheels.yml
vendored
@@ -79,17 +79,16 @@ jobs:
|
||||
path: dist/*.tar.gz
|
||||
|
||||
lint:
|
||||
name: Lint with flake8 and check black
|
||||
name: Lint and format with ruff
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
|
||||
- name: Lint with flake8 and check black
|
||||
- name: Lint and format with ruff
|
||||
run: |
|
||||
pip install black flake8
|
||||
flake8 . --filename '*.py,*.pyx,*.pxd' --count --show-source --statistics --exclude benchmark,build,capnp/templates/module.pyx
|
||||
flake8 . --count --show-source --statistics --exclude benchmark,build
|
||||
black . --check --diff --color
|
||||
pip install ruff
|
||||
ruff check .
|
||||
ruff format --check .
|
||||
|
||||
# upload_pypi:
|
||||
# needs: [build_wheels, build_sdist]
|
||||
|
||||
3
Pipfile
3
Pipfile
@@ -6,8 +6,7 @@ verify_ssl = true
|
||||
[packages]
|
||||
Cython = "<3"
|
||||
Jinja2 = "*"
|
||||
black = "*"
|
||||
flake8 = "*"
|
||||
ruff = "*"
|
||||
pkgconfig = "*"
|
||||
pytest = "*"
|
||||
sphinx = "*"
|
||||
|
||||
@@ -21,9 +21,7 @@ class _CustomBuildMetaBackend(backend_class):
|
||||
sys.argv = sys.argv[:1] + ["build_ext"] + flags + sys.argv[1:]
|
||||
return super().run_setup(setup_script)
|
||||
|
||||
def build_wheel(
|
||||
self, wheel_directory, config_settings=None, metadata_directory=None
|
||||
):
|
||||
def build_wheel(self, wheel_directory, config_settings=None, metadata_directory=None):
|
||||
self.config_settings = config_settings
|
||||
return super().build_wheel(wheel_directory, config_settings, metadata_directory)
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
# Adapted for use in pycapnp from pyzmq. See https://github.com/zeromq/pyzmq
|
||||
# for original project.
|
||||
|
||||
|
||||
import fileinput # noqa
|
||||
import os
|
||||
import shutil
|
||||
|
||||
@@ -32,7 +32,6 @@ Example Usage::
|
||||
print(phone.type, ':', phone.number)
|
||||
"""
|
||||
|
||||
# flake8: noqa F401 F403 F405
|
||||
from .version import version as __version__
|
||||
from .lib.capnp import *
|
||||
from .lib.capnp import (
|
||||
|
||||
@@ -21,21 +21,13 @@ def main():
|
||||
|
||||
code = schema_capnp.CodeGeneratorRequest.read(sys.stdin)
|
||||
code = code.to_dict()
|
||||
code["nodes"] = [
|
||||
node for node in code["nodes"] if "struct" in node and node["scopeId"] != 0
|
||||
]
|
||||
code["nodes"] = [node for node in code["nodes"] if "struct" in node and node["scopeId"] != 0]
|
||||
for node in code["nodes"]:
|
||||
displayName = node["displayName"]
|
||||
parent, path = displayName.split(":")
|
||||
node["module_path"] = (
|
||||
parent.replace(".", "_")
|
||||
+ "."
|
||||
+ ".".join([x[0].upper() + x[1:] for x in path.split(".")])
|
||||
)
|
||||
node["module_path"] = parent.replace(".", "_") + "." + ".".join([x[0].upper() + x[1:] for x in path.split(".")])
|
||||
node["module_name"] = path.replace(".", "_")
|
||||
node["c_module_path"] = "::".join(
|
||||
[x[0].upper() + x[1:] for x in path.split(".")]
|
||||
)
|
||||
node["c_module_path"] = "::".join([x[0].upper() + x[1:] for x in path.split(".")])
|
||||
node["schema"] = "_{}_Schema".format(node["module_name"])
|
||||
is_union = False
|
||||
for field in node["struct"]["fields"]:
|
||||
@@ -63,18 +55,12 @@ def main():
|
||||
filename = f["filename"].replace(".", "_") + "_cython.pyx"
|
||||
|
||||
file_code = dict(code)
|
||||
file_code["nodes"] = [
|
||||
node
|
||||
for node in file_code["nodes"]
|
||||
if node["displayName"].startswith(f["filename"])
|
||||
]
|
||||
file_code["nodes"] = [node for node in file_code["nodes"] if node["displayName"].startswith(f["filename"])]
|
||||
with open(filename, "w") as out:
|
||||
out.write(module.render(code=file_code, file=f, include_dir=include_dir))
|
||||
|
||||
setup = env.get_template("setup.py.tmpl")
|
||||
with open("setup_capnp.py", "w") as out:
|
||||
out.write(setup.render(code=code))
|
||||
print(
|
||||
"You now need to build the cython module by running `python setup_capnp.py build_ext --inplace`."
|
||||
)
|
||||
print("You now need to build the cython module by running `python setup_capnp.py build_ext --inplace`.")
|
||||
print()
|
||||
|
||||
@@ -23,9 +23,7 @@ class PowerFunction(calculator_capnp.Calculator.Function.Server):
|
||||
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(
|
||||
usage="Connects to the Calculator server at the given address and does some RPCs"
|
||||
)
|
||||
parser = argparse.ArgumentParser(usage="Connects to the Calculator server at the given address and does some RPCs")
|
||||
parser.add_argument("host", help="HOST:PORT")
|
||||
|
||||
return parser.parse_args()
|
||||
|
||||
@@ -111,9 +111,7 @@ async def new_connection(stream):
|
||||
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(
|
||||
usage="""Runs the server bound to the given address/port ADDRESS. """
|
||||
)
|
||||
parser = argparse.ArgumentParser(usage="""Runs the server bound to the given address/port ADDRESS. """)
|
||||
|
||||
parser.add_argument("address", help="ADDRESS:PORT")
|
||||
|
||||
|
||||
@@ -45,21 +45,15 @@ async def main(host):
|
||||
addr, port = host.split(":")
|
||||
|
||||
# Setup SSL context
|
||||
ctx = ssl.create_default_context(
|
||||
ssl.Purpose.SERVER_AUTH, cafile=os.path.join(this_dir, "selfsigned.cert")
|
||||
)
|
||||
ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=os.path.join(this_dir, "selfsigned.cert"))
|
||||
|
||||
# Handle both IPv4 and IPv6 cases
|
||||
try:
|
||||
print("Try IPv4")
|
||||
stream = await capnp.AsyncIoStream.create_connection(
|
||||
addr, port, ssl=ctx, family=socket.AF_INET
|
||||
)
|
||||
stream = await capnp.AsyncIoStream.create_connection(addr, port, ssl=ctx, family=socket.AF_INET)
|
||||
except Exception:
|
||||
print("Try IPv6")
|
||||
stream = await capnp.AsyncIoStream.create_connection(
|
||||
addr, port, ssl=ctx, family=socket.AF_INET6
|
||||
)
|
||||
stream = await capnp.AsyncIoStream.create_connection(addr, port, ssl=ctx, family=socket.AF_INET6)
|
||||
|
||||
client = capnp.TwoPartyClient(stream)
|
||||
cap = client.bootstrap().cast_as(thread_capnp.Example)
|
||||
|
||||
@@ -28,9 +28,7 @@ async def new_connection(stream):
|
||||
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(
|
||||
usage="""Runs the server bound to the given address/port ADDRESS. """
|
||||
)
|
||||
parser = argparse.ArgumentParser(usage="""Runs the server bound to the given address/port ADDRESS. """)
|
||||
|
||||
parser.add_argument("address", help="ADDRESS:PORT")
|
||||
|
||||
|
||||
@@ -42,9 +42,7 @@ async def new_connection(stream):
|
||||
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(
|
||||
usage="""Runs the server bound to the given address/port ADDRESS. """
|
||||
)
|
||||
parser = argparse.ArgumentParser(usage="""Runs the server bound to the given address/port ADDRESS. """)
|
||||
|
||||
parser.add_argument("address", help="ADDRESS:PORT")
|
||||
|
||||
|
||||
@@ -28,9 +28,7 @@ class PowerFunction(calculator_capnp.Calculator.Function.Server):
|
||||
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(
|
||||
usage="Connects to the Calculator server at the given address and does some RPCs"
|
||||
)
|
||||
parser = argparse.ArgumentParser(usage="Connects to the Calculator server at the given address and does some RPCs")
|
||||
parser.add_argument("host", help="HOST:PORT")
|
||||
|
||||
return parser.parse_args()
|
||||
@@ -40,21 +38,15 @@ async def main(host):
|
||||
addr, port = host.split(":")
|
||||
|
||||
# Setup SSL context
|
||||
ctx = ssl.create_default_context(
|
||||
ssl.Purpose.SERVER_AUTH, cafile=os.path.join(this_dir, "selfsigned.cert")
|
||||
)
|
||||
ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=os.path.join(this_dir, "selfsigned.cert"))
|
||||
|
||||
# Handle both IPv4 and IPv6 cases
|
||||
try:
|
||||
print("Try IPv4")
|
||||
stream = await capnp.AsyncIoStream.create_connection(
|
||||
addr, port, ssl=ctx, family=socket.AF_INET
|
||||
)
|
||||
stream = await capnp.AsyncIoStream.create_connection(addr, port, ssl=ctx, family=socket.AF_INET)
|
||||
except Exception:
|
||||
print("Try IPv6")
|
||||
stream = await capnp.AsyncIoStream.create_connection(
|
||||
addr, port, ssl=ctx, family=socket.AF_INET6
|
||||
)
|
||||
stream = await capnp.AsyncIoStream.create_connection(addr, port, ssl=ctx, family=socket.AF_INET6)
|
||||
|
||||
client = capnp.TwoPartyClient(stream)
|
||||
|
||||
|
||||
@@ -112,9 +112,7 @@ class CalculatorImpl(calculator_capnp.Calculator.Server):
|
||||
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(
|
||||
usage="""Runs the server bound to the given address/port ADDRESS. """
|
||||
)
|
||||
parser = argparse.ArgumentParser(usage="""Runs the server bound to the given address/port ADDRESS. """)
|
||||
|
||||
parser.add_argument("address", help="ADDRESS:PORT")
|
||||
|
||||
@@ -138,14 +136,10 @@ async def main():
|
||||
# Handle both IPv4 and IPv6 cases
|
||||
try:
|
||||
print("Try IPv4")
|
||||
server = await capnp.AsyncIoStream.create_server(
|
||||
new_connection, host, port, ssl=ctx, family=socket.AF_INET
|
||||
)
|
||||
server = await capnp.AsyncIoStream.create_server(new_connection, host, port, ssl=ctx, family=socket.AF_INET)
|
||||
except Exception:
|
||||
print("Try IPv6")
|
||||
server = await capnp.AsyncIoStream.create_server(
|
||||
new_connection, host, port, ssl=ctx, family=socket.AF_INET6
|
||||
)
|
||||
server = await capnp.AsyncIoStream.create_server(new_connection, host, port, ssl=ctx, family=socket.AF_INET6)
|
||||
|
||||
async with server:
|
||||
await server.serve_forever()
|
||||
|
||||
@@ -33,21 +33,15 @@ async def main(host):
|
||||
addr, port = host.split(":")
|
||||
|
||||
# Setup SSL context
|
||||
ctx = ssl.create_default_context(
|
||||
ssl.Purpose.SERVER_AUTH, cafile=os.path.join(this_dir, "selfsigned.cert")
|
||||
)
|
||||
ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=os.path.join(this_dir, "selfsigned.cert"))
|
||||
|
||||
# Handle both IPv4 and IPv6 cases
|
||||
try:
|
||||
print("Try IPv4")
|
||||
stream = await capnp.AsyncIoStream.create_connection(
|
||||
addr, port, ssl=ctx, family=socket.AF_INET
|
||||
)
|
||||
stream = await capnp.AsyncIoStream.create_connection(addr, port, ssl=ctx, family=socket.AF_INET)
|
||||
except Exception:
|
||||
print("Try IPv6")
|
||||
stream = await capnp.AsyncIoStream.create_connection(
|
||||
addr, port, ssl=ctx, family=socket.AF_INET6
|
||||
)
|
||||
stream = await capnp.AsyncIoStream.create_connection(addr, port, ssl=ctx, family=socket.AF_INET6)
|
||||
|
||||
client = capnp.TwoPartyClient(stream)
|
||||
cap = client.bootstrap().cast_as(thread_capnp.Example)
|
||||
|
||||
@@ -36,9 +36,7 @@ async def new_connection(stream):
|
||||
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(
|
||||
usage="""Runs the server bound to the given address/port ADDRESS. """
|
||||
)
|
||||
parser = argparse.ArgumentParser(usage="""Runs the server bound to the given address/port ADDRESS. """)
|
||||
parser.add_argument("address", help="ADDRESS:PORT")
|
||||
return parser.parse_args()
|
||||
|
||||
@@ -56,14 +54,10 @@ async def main():
|
||||
# Handle both IPv4 and IPv6 cases
|
||||
try:
|
||||
print("Try IPv4")
|
||||
server = await capnp.AsyncIoStream.create_server(
|
||||
new_connection, host, port, ssl=ctx, family=socket.AF_INET
|
||||
)
|
||||
server = await capnp.AsyncIoStream.create_server(new_connection, host, port, ssl=ctx, family=socket.AF_INET)
|
||||
except Exception:
|
||||
print("Try IPv6")
|
||||
server = await capnp.AsyncIoStream.create_server(
|
||||
new_connection, host, port, ssl=ctx, family=socket.AF_INET6
|
||||
)
|
||||
server = await capnp.AsyncIoStream.create_server(new_connection, host, port, ssl=ctx, family=socket.AF_INET6)
|
||||
|
||||
async with server:
|
||||
await server.serve_forever()
|
||||
|
||||
@@ -51,9 +51,7 @@ print(person.extraData)
|
||||
print(type(person.extraData))
|
||||
print()
|
||||
|
||||
person = addressbook_capnp.Person.new_message(
|
||||
allocate_seg_callable=MemoryViewAllocator()
|
||||
)
|
||||
person = addressbook_capnp.Person.new_message(allocate_seg_callable=MemoryViewAllocator())
|
||||
|
||||
person.init("extraData", 5)
|
||||
print(person.extraData)
|
||||
|
||||
@@ -5,3 +5,24 @@ backend-path = ["_custom_build"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
asyncio_mode = "auto"
|
||||
|
||||
[tool.ruff]
|
||||
target-version = "py37"
|
||||
line-length = 120
|
||||
exclude = ["benchmark", "build", "capnp/templates/module.pyx"]
|
||||
|
||||
[tool.ruff.lint]
|
||||
ignore = [
|
||||
"E203", "E211", "E225", "E226", "E227", "E231", "E251",
|
||||
"E261", "E262", "E265", "E402",
|
||||
]
|
||||
|
||||
[tool.ruff.lint.per-file-ignores]
|
||||
"test/test_examples.py" = ["C901"]
|
||||
"capnp/__init__.py" = ["F401", "F403", "F405"]
|
||||
|
||||
[tool.ruff.lint.mccabe]
|
||||
max-complexity = 10
|
||||
|
||||
[tool.ruff.format]
|
||||
quote-style = "double"
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
jinja2
|
||||
black
|
||||
cython>=3
|
||||
flake8
|
||||
ruff
|
||||
setuptools
|
||||
pkgconfig
|
||||
pytest
|
||||
|
||||
@@ -48,9 +48,7 @@ def main():
|
||||
kwargs = vars(args)
|
||||
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()
|
||||
|
||||
@@ -4,9 +4,7 @@ import sys
|
||||
|
||||
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
|
||||
|
||||
|
||||
10
setup.py
10
setup.py
@@ -124,11 +124,7 @@ class build_libcapnp_ext(build_ext_c):
|
||||
if capnp_executable:
|
||||
capnp_dir = os.path.dirname(capnp_executable)
|
||||
self.include_dirs += [os.path.join(capnp_dir, "..", "include")]
|
||||
self.library_dirs += [
|
||||
os.path.join(
|
||||
capnp_dir, "..", "lib{}".format(8 * struct.calcsize("P"))
|
||||
)
|
||||
]
|
||||
self.library_dirs += [os.path.join(capnp_dir, "..", "lib{}".format(8 * struct.calcsize("P")))]
|
||||
self.library_dirs += [os.path.join(capnp_dir, "..", "lib")]
|
||||
|
||||
# Look for capnproto using pkg-config (and minimum version)
|
||||
@@ -151,9 +147,7 @@ class build_libcapnp_ext(build_ext_c):
|
||||
bundle_dir = os.path.join(_this_dir, "bundled")
|
||||
if not os.path.exists(bundle_dir):
|
||||
os.mkdir(bundle_dir)
|
||||
build_dir = os.path.join(
|
||||
_this_dir, "build{}".format(8 * struct.calcsize("P"))
|
||||
)
|
||||
build_dir = os.path.join(_this_dir, "build{}".format(8 * struct.calcsize("P")))
|
||||
if not os.path.exists(build_dir):
|
||||
os.mkdir(build_dir)
|
||||
|
||||
|
||||
@@ -63,9 +63,7 @@ async def test_large_response_sequential():
|
||||
response = await cap.foo(i=size, j=False)
|
||||
|
||||
# Verify the response has the correct length
|
||||
assert (
|
||||
len(response.x) == size
|
||||
), f"Size mismatch for {size}: expected {size}, got {len(response.x)}"
|
||||
assert len(response.x) == size, f"Size mismatch for {size}: expected {size}, got {len(response.x)}"
|
||||
|
||||
# Verify the pattern is correct (not corrupted)
|
||||
expected = "".join(chr(65 + (k % 26)) for k in range(size))
|
||||
@@ -107,6 +105,4 @@ async def test_large_response_pipelined():
|
||||
assert len(response.x) == size, f"Size mismatch for {size}"
|
||||
|
||||
expected = "".join(chr(65 + (k % 26)) for k in range(size))
|
||||
assert (
|
||||
response.x == expected
|
||||
), f"Data corruption detected for {size} bytes payload!"
|
||||
assert response.x == expected, f"Data corruption detected for {size} bytes payload!"
|
||||
|
||||
@@ -212,9 +212,7 @@ class TailCaller(capability.TestTailCaller.Server):
|
||||
async def foo_context(self, context):
|
||||
self.count += 1
|
||||
|
||||
tail = context.params.callee.foo_request(
|
||||
i=context.params.i, t="from TailCaller"
|
||||
)
|
||||
tail = context.params.callee.foo_request(i=context.params.i, t="from TailCaller")
|
||||
await context.tail_call(tail)
|
||||
|
||||
|
||||
|
||||
@@ -19,9 +19,7 @@ def cleanup():
|
||||
p.kill()
|
||||
|
||||
|
||||
def run_subprocesses(
|
||||
address, server, client, wildcard_server=False, ipv4_force=True
|
||||
): # noqa
|
||||
def run_subprocesses(address, server, client, wildcard_server=False, ipv4_force=True): # noqa
|
||||
server_attempt = 0
|
||||
server_attempts = 2
|
||||
done = False
|
||||
@@ -29,9 +27,7 @@ def run_subprocesses(
|
||||
c_address = address
|
||||
s_address = address
|
||||
while not done:
|
||||
assert server_attempt < server_attempts, "Failed {} server attempts".format(
|
||||
server_attempts
|
||||
)
|
||||
assert server_attempt < server_attempts, "Failed {} server attempts".format(server_attempts)
|
||||
server_attempt += 1
|
||||
|
||||
# Force ipv4 for tests (known issues on GitHub Actions with IPv6 for some targets)
|
||||
@@ -125,9 +121,7 @@ def test_async_calculator_example(unused_tcp_port, cleanup):
|
||||
|
||||
|
||||
def test_addressbook_example(cleanup):
|
||||
proc = subprocess.Popen(
|
||||
[sys.executable, os.path.join(examples_dir, "addressbook.py")]
|
||||
)
|
||||
proc = subprocess.Popen([sys.executable, os.path.join(examples_dir, "addressbook.py")])
|
||||
ret = proc.wait()
|
||||
assert ret == 0
|
||||
|
||||
|
||||
@@ -197,12 +197,10 @@ def test_view_keeps_message_alive(all_types):
|
||||
view = msg.get_data_as_view("dataField")
|
||||
new_ref_count = sys.getrefcount(msg)
|
||||
|
||||
assert (
|
||||
new_ref_count > initial_ref_count
|
||||
), f"View failed to hold reference to Message! (Old: {initial_ref_count}, New: {new_ref_count})"
|
||||
print(
|
||||
f"\n[Ref Check] Success: Ref count increased from {initial_ref_count} to {new_ref_count}"
|
||||
assert new_ref_count > initial_ref_count, (
|
||||
f"View failed to hold reference to Message! (Old: {initial_ref_count}, New: {new_ref_count})"
|
||||
)
|
||||
print(f"\n[Ref Check] Success: Ref count increased from {initial_ref_count} to {new_ref_count}")
|
||||
|
||||
del msg
|
||||
gc.collect()
|
||||
|
||||
@@ -216,9 +216,7 @@ def test_addressbook_explicit_fields(addressbook):
|
||||
alicePhones[0]._set_by_field(phone_fields["number"], "555-1212")
|
||||
alicePhones[0]._set_by_field(phone_fields["type"], "mobile")
|
||||
employment = alice._get_by_field(person_fields["employment"])
|
||||
employment._set_by_field(
|
||||
addressbook.Person.Employment.schema.fields["school"], "MIT"
|
||||
)
|
||||
employment._set_by_field(addressbook.Person.Employment.schema.fields["school"], "MIT")
|
||||
|
||||
bob = people[1]
|
||||
bob._set_by_field(person_fields["id"], 456)
|
||||
@@ -230,9 +228,7 @@ def test_addressbook_explicit_fields(addressbook):
|
||||
bobPhones[1]._set_by_field(phone_fields["number"], "555-7654")
|
||||
bobPhones[1]._set_by_field(phone_fields["type"], "work")
|
||||
employment = bob._get_by_field(person_fields["employment"])
|
||||
employment._set_by_field(
|
||||
addressbook.Person.Employment.schema.fields["unemployed"], None
|
||||
)
|
||||
employment._set_by_field(addressbook.Person.Employment.schema.fields["unemployed"], None)
|
||||
|
||||
addresses.write(file)
|
||||
|
||||
@@ -252,9 +248,7 @@ def test_addressbook_explicit_fields(addressbook):
|
||||
assert alicePhones[0]._get_by_field(phone_fields["number"]) == "555-1212"
|
||||
assert alicePhones[0]._get_by_field(phone_fields["type"]) == "mobile"
|
||||
employment = alice._get_by_field(person_fields["employment"])
|
||||
employment._get_by_field(
|
||||
addressbook.Person.Employment.schema.fields["school"]
|
||||
) == "MIT"
|
||||
employment._get_by_field(addressbook.Person.Employment.schema.fields["school"]) == "MIT"
|
||||
|
||||
bob = people[1]
|
||||
assert bob._get_by_field(person_fields["id"]) == 456
|
||||
@@ -266,9 +260,7 @@ def test_addressbook_explicit_fields(addressbook):
|
||||
assert bobPhones[1]._get_by_field(phone_fields["number"]) == "555-7654"
|
||||
assert bobPhones[1]._get_by_field(phone_fields["type"]) == "work"
|
||||
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")
|
||||
writeAddressBook(f)
|
||||
@@ -450,13 +442,9 @@ def check_all_types(reader):
|
||||
check_list(subReader.uInt8List, [12, 34, 0, 0xFF])
|
||||
check_list(subReader.uInt16List, [1234, 5678, 0, 0xFFFF])
|
||||
check_list(subReader.uInt32List, [12345678, 90123456, 0, 0xFFFFFFFF])
|
||||
check_list(
|
||||
subReader.uInt64List, [123456789012345, 678901234567890, 0, 0xFFFFFFFFFFFFFFFF]
|
||||
)
|
||||
check_list(subReader.uInt64List, [123456789012345, 678901234567890, 0, 0xFFFFFFFFFFFFFFFF])
|
||||
check_list(subReader.float32List, [0.0, 1234567.0, 1e37, -1e37, 1e-37, -1e-37])
|
||||
check_list(
|
||||
subReader.float64List, [0.0, 123456789012345.0, 1e306, -1e306, 1e-306, -1e-306]
|
||||
)
|
||||
check_list(subReader.float64List, [0.0, 123456789012345.0, 1e306, -1e306, 1e-306, -1e-306])
|
||||
check_list(subReader.textList, ["quux", "corge", "grault"])
|
||||
check_list(subReader.dataList, [b"garply", b"waldo", b"fred"])
|
||||
|
||||
@@ -510,25 +498,19 @@ def check_all_types(reader):
|
||||
def test_build(all_types):
|
||||
root = all_types.TestAllTypes.new_message()
|
||||
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
|
||||
|
||||
|
||||
def test_build_first_segment_size(all_types):
|
||||
root = all_types.TestAllTypes.new_message(1)
|
||||
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
|
||||
|
||||
root = all_types.TestAllTypes.new_message(1024 * 1024)
|
||||
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
|
||||
|
||||
|
||||
@@ -537,9 +519,7 @@ def test_binary_read(all_types):
|
||||
root = all_types.TestAllTypes.read(f)
|
||||
check_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
|
||||
|
||||
# Test set_root().
|
||||
@@ -557,9 +537,7 @@ def test_packed_read(all_types):
|
||||
root = all_types.TestAllTypes.read_packed(f)
|
||||
check_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
|
||||
|
||||
|
||||
|
||||
@@ -40,15 +40,11 @@ def test_annotations(annotations):
|
||||
assert annotation.value.struct.as_struct(annotations.AnnotationStruct).test == 100
|
||||
|
||||
annotation = annotations.TestAnnotationThree.schema.node.annotations[0]
|
||||
annotation_list = annotation.value.list.as_list(
|
||||
capnp._ListSchema(annotations.AnnotationStruct)
|
||||
)
|
||||
annotation_list = annotation.value.list.as_list(capnp._ListSchema(annotations.AnnotationStruct))
|
||||
assert annotation_list[0].test == 100
|
||||
assert annotation_list[1].test == 101
|
||||
|
||||
annotation = annotations.TestAnnotationFour.schema.node.annotations[0]
|
||||
annotation_list = annotation.value.list.as_list(
|
||||
capnp._ListSchema(capnp.types.UInt16)
|
||||
)
|
||||
annotation_list = annotation.value.list.as_list(capnp._ListSchema(capnp.types.UInt16))
|
||||
assert annotation_list[0] == 200
|
||||
assert annotation_list[1] == 201
|
||||
|
||||
@@ -114,9 +114,7 @@ def test_roundtrip_bytes_packed(all_types):
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _warnings(
|
||||
expected_count=2, expected_text="This message has already been written once."
|
||||
):
|
||||
def _warnings(expected_count=2, expected_text="This message has already been written once."):
|
||||
with warnings.catch_warnings(record=True) as w:
|
||||
yield
|
||||
|
||||
|
||||
@@ -168,9 +168,7 @@ def test_new_message(all_types):
|
||||
|
||||
assert msg.structField.int32Field == 100
|
||||
|
||||
msg = all_types.TestAllTypes.new_message(
|
||||
structList=[{"int32Field": 100}, {"int32Field": 101}]
|
||||
)
|
||||
msg = all_types.TestAllTypes.new_message(structList=[{"int32Field": 100}, {"int32Field": 101}])
|
||||
|
||||
assert msg.structList[0].int32Field == 100
|
||||
assert msg.structList[1].int32Field == 101
|
||||
@@ -199,9 +197,7 @@ def test_set_dict(all_types):
|
||||
|
||||
|
||||
def test_set_dict_union(addressbook):
|
||||
person = addressbook.Person.new_message(
|
||||
**{"employment": {"employer": {"name": "foo"}}}
|
||||
)
|
||||
person = addressbook.Person.new_message(**{"employment": {"employer": {"name": "foo"}}})
|
||||
|
||||
assert person.employment.which == addressbook.Person.Employment.employer
|
||||
|
||||
@@ -212,16 +208,12 @@ def test_union_enum(all_types):
|
||||
assert all_types.UnionAllTypes.Union.UnionStructField1 == 0
|
||||
assert all_types.UnionAllTypes.Union.UnionStructField2 == 1
|
||||
|
||||
msg = all_types.UnionAllTypes.new_message(
|
||||
**{"unionStructField1": {"textField": "foo"}}
|
||||
)
|
||||
msg = all_types.UnionAllTypes.new_message(**{"unionStructField1": {"textField": "foo"}})
|
||||
assert msg.which == all_types.UnionAllTypes.Union.UnionStructField1
|
||||
assert msg.which == "unionStructField1"
|
||||
assert msg.which == 0
|
||||
|
||||
msg = all_types.UnionAllTypes.new_message(
|
||||
**{"unionStructField2": {"textField": "foo"}}
|
||||
)
|
||||
msg = all_types.UnionAllTypes.new_message(**{"unionStructField2": {"textField": "foo"}})
|
||||
assert msg.which == all_types.UnionAllTypes.Union.UnionStructField2
|
||||
assert msg.which == "unionStructField2"
|
||||
assert msg.which == 1
|
||||
@@ -229,14 +221,10 @@ def test_union_enum(all_types):
|
||||
assert all_types.GroupedUnionAllTypes.Union.G1 == 0
|
||||
assert all_types.GroupedUnionAllTypes.Union.G2 == 1
|
||||
|
||||
msg = all_types.GroupedUnionAllTypes.new_message(
|
||||
**{"g1": {"unionStructField1": {"textField": "foo"}}}
|
||||
)
|
||||
msg = all_types.GroupedUnionAllTypes.new_message(**{"g1": {"unionStructField1": {"textField": "foo"}}})
|
||||
assert msg.which == all_types.GroupedUnionAllTypes.Union.G1
|
||||
|
||||
msg = all_types.GroupedUnionAllTypes.new_message(
|
||||
**{"g2": {"unionStructField2": {"textField": "foo"}}}
|
||||
)
|
||||
msg = all_types.GroupedUnionAllTypes.new_message(**{"g2": {"unionStructField2": {"textField": "foo"}}})
|
||||
assert msg.which == all_types.GroupedUnionAllTypes.Union.G2
|
||||
|
||||
msg = all_types.UnionAllTypes.new_message()
|
||||
@@ -248,9 +236,7 @@ def isstr(s):
|
||||
|
||||
|
||||
def test_to_dict_enum(addressbook):
|
||||
person = addressbook.Person.new_message(
|
||||
**{"phones": [{"number": "999-9999", "type": "mobile"}]}
|
||||
)
|
||||
person = addressbook.Person.new_message(**{"phones": [{"number": "999-9999", "type": "mobile"}]})
|
||||
|
||||
field = person.to_dict()["phones"][0]["type"]
|
||||
assert isstr(field)
|
||||
|
||||
Reference in New Issue
Block a user