Compare commits
181 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
87b84afc4b | ||
|
|
8283ef7298 | ||
|
|
0931eb3bf5 | ||
|
|
8f535913a1 | ||
|
|
fd02cb6180 | ||
|
|
950d2f6536 | ||
|
|
29f12ea88d | ||
|
|
219233b50e | ||
|
|
2d30bdb7b2 | ||
|
|
bdd3389b17 | ||
|
|
441844b97a | ||
|
|
aa81680c83 | ||
|
|
a413d08fc1 | ||
|
|
24d694afe2 | ||
|
|
84af157122 | ||
|
|
df0c17bf0a | ||
|
|
8659c51123 | ||
|
|
d1825026db | ||
|
|
a12c9d24de | ||
|
|
d79a9eee14 | ||
|
|
d848d05710 | ||
|
|
26da86d2cd | ||
|
|
604dcb104f | ||
|
|
421aa78014 | ||
|
|
0fda2cc05d | ||
|
|
4cdf1bb9e0 | ||
|
|
d203659a44 | ||
|
|
6faac1d1ca | ||
|
|
098989e9e9 | ||
|
|
182aedaec4 | ||
|
|
a7532bbadc | ||
|
|
73d1fa3d5b | ||
|
|
c00bc96db7 | ||
|
|
d3e9621aa8 | ||
|
|
fcbd8a3759 | ||
|
|
aad7d2ad76 | ||
|
|
37e53fce85 | ||
|
|
2b41383745 | ||
|
|
b0b6cd24ad | ||
|
|
b81195eb44 | ||
|
|
d2af2f2fac | ||
|
|
e7f07fa2a1 | ||
|
|
50fa4e6268 | ||
|
|
2fa0be2141 | ||
|
|
13d656587c | ||
|
|
6df8cef3f0 | ||
|
|
1b1bd47cb1 | ||
|
|
0adcc9020c | ||
|
|
bfc0fac754 | ||
|
|
8fbf4476a8 | ||
|
|
591ec5efb3 | ||
|
|
f31d51cf3c | ||
|
|
496eba2750 | ||
|
|
d663a318b7 | ||
|
|
2fb37dd108 | ||
|
|
42d2df6de6 | ||
|
|
3fd5a0d662 | ||
|
|
bc13e7070d | ||
|
|
6536181902 | ||
|
|
85e4be96d8 | ||
|
|
06c26ba60d | ||
|
|
6a70b8e8ea | ||
|
|
3ca092a724 | ||
|
|
6f7d706a8e | ||
|
|
ac96d8254b | ||
|
|
e7133adeb3 | ||
|
|
204e04dd69 | ||
|
|
b9b0b22d57 | ||
|
|
402c21256f | ||
|
|
5f7e4d58ef | ||
|
|
1aaf7728cc | ||
|
|
70310c9e8c | ||
|
|
18a518efa7 | ||
|
|
62da35b3ea | ||
|
|
69f4192341 | ||
|
|
9c1bf25304 | ||
|
|
a836fb23bc | ||
|
|
bd69862a02 | ||
|
|
74205e3319 | ||
|
|
3f377e3bfd | ||
|
|
8c727d904f | ||
|
|
eeddc844a5 | ||
|
|
9b5594adbe | ||
|
|
d991040ff6 | ||
|
|
d260f071e0 | ||
|
|
6dd7baa26c | ||
|
|
573c7292a6 | ||
|
|
d77f44ebb7 | ||
|
|
671c0ff4ac | ||
|
|
9cecc8c3ff | ||
|
|
bc3cfc5562 | ||
|
|
b0a36d12e4 | ||
|
|
a4d2d39546 | ||
|
|
c424b6f8db | ||
|
|
421fdba309 | ||
|
|
fb2793e0b6 | ||
|
|
ad8b91766a | ||
|
|
a33126544b | ||
|
|
02e41afd09 | ||
|
|
7368299a70 | ||
|
|
deb623ed14 | ||
|
|
95339bf74d | ||
|
|
5b639c82b2 | ||
|
|
7c5ee47e68 | ||
|
|
bb646fe26f | ||
|
|
fc90653ab1 | ||
|
|
2a73dbac98 | ||
|
|
891c9e5d6c | ||
|
|
a890514b5c | ||
|
|
fe1e712fdb | ||
|
|
7a358a63cf | ||
|
|
342e6559dc | ||
|
|
2f62189346 | ||
|
|
8a215367ad | ||
|
|
6c1c41e9cc | ||
|
|
9e6881999e | ||
|
|
59f5f88c0d | ||
|
|
8eea5fe256 | ||
|
|
1d54ef8f99 | ||
|
|
73cea12e1f | ||
|
|
a157f05480 | ||
|
|
69dfe9cafc | ||
|
|
a8a082e4e7 | ||
|
|
e44de6da06 | ||
|
|
a5e0ef910f | ||
|
|
8f7af272cc | ||
|
|
bf9412e083 | ||
|
|
4630c1cc67 | ||
|
|
d3e4fbb311 | ||
|
|
58556e0eb6 | ||
|
|
a3f5f21738 | ||
|
|
0028cc384a | ||
|
|
034e2e7da0 | ||
|
|
ca16b6ed34 | ||
|
|
16d554db75 | ||
|
|
9ef5503728 | ||
|
|
c93351ef21 | ||
|
|
80bef7c94f | ||
|
|
804805f0f5 | ||
|
|
43c134d27c | ||
|
|
0cd9510b54 | ||
|
|
beafc812ff | ||
|
|
3d8c0cb713 | ||
|
|
c513853301 | ||
|
|
c1a76a5f5e | ||
|
|
2745953a8e | ||
|
|
b5dcac1250 | ||
|
|
cbd3437080 | ||
|
|
2585a07fcf | ||
|
|
6c29771f4c | ||
|
|
0ba0692dec | ||
|
|
42e197f985 | ||
|
|
459d12b24d | ||
|
|
cebf9176a3 | ||
|
|
8864f4fdbd | ||
|
|
03211604bc | ||
|
|
1d7ba850e9 | ||
|
|
b2651335ce | ||
|
|
5a591ef2a4 | ||
|
|
8d7d0efb9b | ||
|
|
b891d257f6 | ||
|
|
8bcb67b66f | ||
|
|
72d72b4603 | ||
|
|
3273ae4d2c | ||
|
|
6fe666473d | ||
|
|
0338fcba29 | ||
|
|
0f3ad25770 | ||
|
|
586e28d2dc | ||
|
|
a8d8159d27 | ||
|
|
3f519d4fb1 | ||
|
|
dedead048f | ||
|
|
87b3a4b86d | ||
|
|
f2e87192b0 | ||
|
|
98d00f0d21 | ||
|
|
23dcbc2695 | ||
|
|
0af0cf4bfb | ||
|
|
28a288924f | ||
|
|
5c700618fd | ||
|
|
a914306f33 | ||
|
|
67422db6b9 | ||
|
|
061bf86a9c |
23
.github/CONTRIBUTING.md
vendored
Normal file
23
.github/CONTRIBUTING.md
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
# Contributing
|
||||
|
||||
There's lots to do, and we're working hard, so any help is welcome!
|
||||
|
||||
- :speech_balloon: Join us on [Slack](https://join.slack.com/t/betterproto/shared_invite/zt-f0n0uolx-iN8gBNrkPxtKHTLpG3o1OQ)!
|
||||
|
||||
What can you do?
|
||||
|
||||
- :+1: Vote on [issues](https://github.com/danielgtaylor/python-betterproto/issues).
|
||||
- :speech_balloon: Give feedback on [Pull Requests](https://github.com/danielgtaylor/python-betterproto/pulls) and [Issues](https://github.com/danielgtaylor/python-betterproto/issues):
|
||||
- Suggestions
|
||||
- Express approval
|
||||
- Raise concerns
|
||||
- :small_red_triangle: Create an issue:
|
||||
- File a bug (please check its not a duplicate)
|
||||
- Propose an enhancement
|
||||
- :white_check_mark: Create a PR:
|
||||
- [Creating a failing test-case](https://github.com/danielgtaylor/python-betterproto/blob/master/betterproto/tests/README.md) to make bug-fixing easier
|
||||
- Fix any of the open issues
|
||||
- [Good first issues](https://github.com/danielgtaylor/python-betterproto/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22)
|
||||
- [Issues with tests](https://github.com/danielgtaylor/python-betterproto/issues?q=is%3Aissue+is%3Aopen+label%3A%22has+test%22)
|
||||
- New bugfix or idea
|
||||
- If you'd like to discuss your idea first, join us on Slack!
|
||||
113
.github/workflows/ci.yml
vendored
113
.github/workflows/ci.yml
vendored
@@ -1,74 +1,65 @@
|
||||
name: CI
|
||||
|
||||
on: [push, pull_request]
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
pull_request:
|
||||
branches:
|
||||
- '**'
|
||||
|
||||
jobs:
|
||||
|
||||
check-formatting:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
name: Consult black on python formatting
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-python@v2
|
||||
with:
|
||||
python-version: 3.7
|
||||
- uses: Gr1N/setup-poetry@v2
|
||||
- uses: actions/cache@v2
|
||||
with:
|
||||
path: ~/.cache/pypoetry/virtualenvs
|
||||
key: ${{ runner.os }}-poetry-${{ hashFiles('poetry.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-poetry-
|
||||
- name: Install dependencies
|
||||
run: poetry install
|
||||
- name: Run black
|
||||
run: make check-style
|
||||
|
||||
run-tests:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
name: Run tests with tox
|
||||
|
||||
tests:
|
||||
name: ${{ matrix.os }} / ${{ matrix.python-version }}
|
||||
runs-on: ${{ matrix.os }}-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
python-version: [ '3.6', '3.7', '3.8']
|
||||
|
||||
os: [Ubuntu, MacOS, Windows]
|
||||
python-version: ['3.7', '3.8', '3.9', '3.10', '3.11']
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-python@v2
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
- uses: Gr1N/setup-poetry@v2
|
||||
- uses: actions/cache@v2
|
||||
|
||||
- name: Get full Python version
|
||||
id: full-python-version
|
||||
shell: bash
|
||||
run: echo ::set-output name=version::$(python -c "import sys; print('-'.join(str(v) for v in sys.version_info))")
|
||||
|
||||
- name: Install poetry
|
||||
shell: bash
|
||||
run: |
|
||||
python -m pip install poetry
|
||||
echo "$HOME/.poetry/bin" >> $GITHUB_PATH
|
||||
|
||||
- name: Configure poetry
|
||||
shell: bash
|
||||
run: poetry config virtualenvs.in-project true
|
||||
|
||||
- name: Set up cache
|
||||
uses: actions/cache@v3
|
||||
id: cache
|
||||
with:
|
||||
path: ~/.cache/pypoetry/virtualenvs
|
||||
key: ${{ runner.os }}-poetry-${{ hashFiles('poetry.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-poetry-
|
||||
path: .venv
|
||||
key: venv-${{ runner.os }}-${{ steps.full-python-version.outputs.version }}-${{ hashFiles('**/poetry.lock') }}
|
||||
|
||||
- name: Ensure cache is healthy
|
||||
if: steps.cache.outputs.cache-hit == 'true'
|
||||
shell: bash
|
||||
run: poetry run pip --version >/dev/null 2>&1 || rm -rf .venv
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
sudo apt install protobuf-compiler libprotobuf-dev
|
||||
poetry install
|
||||
- name: Run tests
|
||||
run: |
|
||||
make generate
|
||||
make test
|
||||
shell: bash
|
||||
run: poetry install -E compiler
|
||||
|
||||
build-release:
|
||||
runs-on: ubuntu-latest
|
||||
- name: Generate code from proto files
|
||||
shell: bash
|
||||
run: poetry run python -m tests.generate -v
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-python@v2
|
||||
with:
|
||||
python-version: 3.7
|
||||
- uses: Gr1N/setup-poetry@v2
|
||||
- name: Build package
|
||||
run: poetry build
|
||||
- name: Publish package to PyPI
|
||||
if: github.event_name == 'push' && startsWith(github.event.ref, 'refs/tags')
|
||||
run: poetry publish -n
|
||||
env:
|
||||
POETRY_PYPI_TOKEN_PYPI: ${{ secrets.pypi }}
|
||||
- name: Execute test suite
|
||||
shell: bash
|
||||
run: poetry run python -m pytest tests/
|
||||
|
||||
18
.github/workflows/code-quality.yml
vendored
Normal file
18
.github/workflows/code-quality.yml
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
name: Code Quality
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
pull_request:
|
||||
branches:
|
||||
- '**'
|
||||
|
||||
jobs:
|
||||
check-formatting:
|
||||
name: Check code/doc formatting
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-python@v4
|
||||
- uses: pre-commit/action@v2.0.3
|
||||
31
.github/workflows/release.yml
vendored
Normal file
31
.github/workflows/release.yml
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
tags:
|
||||
- '**'
|
||||
pull_request:
|
||||
branches:
|
||||
- '**'
|
||||
|
||||
jobs:
|
||||
packaging:
|
||||
name: Distribution
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Set up Python 3.8
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: 3.8
|
||||
- name: Install poetry
|
||||
run: python -m pip install poetry
|
||||
- name: Build package
|
||||
run: poetry build
|
||||
- name: Publish package to PyPI
|
||||
if: github.event_name == 'push' && startsWith(github.event.ref, 'refs/tags')
|
||||
env:
|
||||
POETRY_PYPI_TOKEN_PYPI: ${{ secrets.pypi }}
|
||||
run: poetry publish -n
|
||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -6,7 +6,7 @@
|
||||
.pytest_cache
|
||||
.python-version
|
||||
build/
|
||||
betterproto/tests/output_*
|
||||
tests/output_*
|
||||
**/__pycache__
|
||||
dist
|
||||
**/*.egg-info
|
||||
@@ -14,3 +14,7 @@ output
|
||||
.idea
|
||||
.DS_Store
|
||||
.tox
|
||||
.venv
|
||||
.asv
|
||||
venv
|
||||
.devcontainer
|
||||
|
||||
21
.pre-commit-config.yaml
Normal file
21
.pre-commit-config.yaml
Normal file
@@ -0,0 +1,21 @@
|
||||
ci:
|
||||
autofix_prs: false
|
||||
|
||||
repos:
|
||||
- repo: https://github.com/pycqa/isort
|
||||
rev: 5.11.5
|
||||
hooks:
|
||||
- id: isort
|
||||
|
||||
- repo: https://github.com/psf/black
|
||||
rev: 23.1.0
|
||||
hooks:
|
||||
- id: black
|
||||
args: ["--target-version", "py310"]
|
||||
|
||||
- repo: https://github.com/PyCQA/doc8
|
||||
rev: 0.10.1
|
||||
hooks:
|
||||
- id: doc8
|
||||
additional_dependencies:
|
||||
- toml
|
||||
17
.readthedocs.yml
Normal file
17
.readthedocs.yml
Normal file
@@ -0,0 +1,17 @@
|
||||
version: 2
|
||||
formats: []
|
||||
|
||||
build:
|
||||
image: latest
|
||||
|
||||
sphinx:
|
||||
configuration: docs/conf.py
|
||||
fail_on_warning: false
|
||||
|
||||
python:
|
||||
version: 3.7
|
||||
install:
|
||||
- method: pip
|
||||
path: .
|
||||
extra_requirements:
|
||||
- dev
|
||||
131
CHANGELOG.md
131
CHANGELOG.md
@@ -7,6 +7,134 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
- Versions suffixed with `b*` are in `beta` and can be installed with `pip install --pre betterproto`.
|
||||
|
||||
## [2.0.0b6] - 2023-06-25
|
||||
|
||||
- **Breaking**: the minimum Python version has been bumped to `3.7` [#444](https://github.com/danielgtaylor/python-betterproto/pull/444)
|
||||
|
||||
- Support generating [Pydantic dataclasses](https://docs.pydantic.dev/latest/usage/dataclasses).
|
||||
Pydantic dataclasses are are drop-in replacement for dataclasses in the standard library that additionally supports validation.
|
||||
Pass `--python_betterproto_opt=pydantic_dataclasses` to enable this feature.
|
||||
Refer to [#406](https://github.com/danielgtaylor/python-betterproto/pull/406)
|
||||
and [README.md](https://github.com/danielgtaylor/python-betterproto#generating-pydantic-models) for more information.
|
||||
|
||||
- Added support for `@generated` marker [#382](https://github.com/danielgtaylor/python-betterproto/pull/382)
|
||||
- Pull down the `include_default_values` argument to `to_json()` [#405](https://github.com/danielgtaylor/python-betterproto/pull/405)
|
||||
- Pythonize input_type name in py_input_message [#436](https://github.com/danielgtaylor/python-betterproto/pull/436)
|
||||
- Widen `from_dict()` to accept any `Mapping` [#451](https://github.com/danielgtaylor/python-betterproto/pull/451)
|
||||
- Replace `pkg_resources` with `importlib` [#462](https://github.com/danielgtaylor/python-betterproto/pull/462)
|
||||
|
||||
- Fix typechecker compatiblity checks in server streaming methods [#413](https://github.com/danielgtaylor/python-betterproto/pull/413)
|
||||
- Fix "empty-valued" repeated fields not being serialised [#417](https://github.com/danielgtaylor/python-betterproto/pull/417)
|
||||
- Fix `dict` encoding for timezone-aware `datetimes` [#468](https://github.com/danielgtaylor/python-betterproto/pull/468)
|
||||
- Fix `to_pydict()` serialization for optional fields [#495](https://github.com/danielgtaylor/python-betterproto/pull/495)
|
||||
- Handle empty value objects properly [#481](https://github.com/danielgtaylor/python-betterproto/pull/481)
|
||||
|
||||
## [2.0.0b5] - 2022-08-01
|
||||
|
||||
- **Breaking**: Client and Service Stubs no longer pack and unpack the input message fields as parameters [#331](https://github.com/danielgtaylor/python-betterproto/pull/311)
|
||||
|
||||
Update your client calls and server handlers as follows:
|
||||
|
||||
Clients before:
|
||||
|
||||
```py
|
||||
response = await service.echo(value="hello", extra_times=1)
|
||||
```
|
||||
|
||||
Clients after:
|
||||
|
||||
```py
|
||||
response = await service.echo(EchoRequest(value="hello", extra_times=1))
|
||||
```
|
||||
|
||||
Servers before:
|
||||
|
||||
```py
|
||||
async def echo(self, value: str, extra_times: int) -> EchoResponse: ...
|
||||
```
|
||||
|
||||
Servers after:
|
||||
|
||||
```py
|
||||
async def echo(self, echo_request: EchoRequest) -> EchoResponse:
|
||||
# Use echo_request.value
|
||||
# Use echo_request.extra_times
|
||||
...
|
||||
```
|
||||
|
||||
- Add `to/from_pydict()` for `Message` [#203](https://github.com/danielgtaylor/python-betterproto/pull/203)
|
||||
- Format field comments also as docstrings [#304](https://github.com/danielgtaylor/python-betterproto/pull/304)
|
||||
- Implement `__deepcopy__` for `Message` [#339](https://github.com/danielgtaylor/python-betterproto/pull/339)
|
||||
- Run isort on compiled code [#355](https://github.com/danielgtaylor/python-betterproto/pull/355)
|
||||
- Expose timeout, deadline and metadata parameters from grpclib [#352](https://github.com/danielgtaylor/python-betterproto/pull/352)
|
||||
- Make `Message.__getattribute__` invisible to type checkers [#359](https://github.com/danielgtaylor/python-betterproto/pull/359)
|
||||
|
||||
- Fix map field edge-case [#254](https://github.com/danielgtaylor/python-betterproto/pull/254)
|
||||
- Fix message text in `NotImplementedError` [#325](https://github.com/danielgtaylor/python-betterproto/pull/325)
|
||||
- Fix `Message.from_dict()` in the presence of optional datetime fields [#329](https://github.com/danielgtaylor/python-betterproto/pull/329)
|
||||
- Support Jinja2 3.0 to prevent version conflicts [#330](https://github.com/danielgtaylor/python-betterproto/pull/330)
|
||||
- Fix overwriting top level `__init__.py` [#337](https://github.com/danielgtaylor/python-betterproto/pull/337)
|
||||
- Remove deprecation warnings when fields are initialised with non-default values [#348](https://github.com/danielgtaylor/python-betterproto/pull/348)
|
||||
- Ensure nested class names are converted to PascalCase [#353](https://github.com/danielgtaylor/python-betterproto/pull/353)
|
||||
- Fix `Message.to_dict()` mutating the underlying Message [#378](https://github.com/danielgtaylor/python-betterproto/pull/378)
|
||||
- Fix some parameters being missing from services [#381](https://github.com/danielgtaylor/python-betterproto/pull/381)
|
||||
|
||||
## [2.0.0b4] - 2022-01-03
|
||||
|
||||
- **Breaking**: the minimum Python version has been bumped to `3.6.2`
|
||||
|
||||
- Always add `AsyncIterator` to imports if there are services [#264](https://github.com/danielgtaylor/python-betterproto/pull/264)
|
||||
- Allow parsing of messages from `ByteStrings` [#266](https://github.com/danielgtaylor/python-betterproto/pull/266)
|
||||
- Add support for proto3 optional [#281](https://github.com/danielgtaylor/python-betterproto/pull/281)
|
||||
|
||||
- Fix compilation of fields with names identical to builtin types [#294](https://github.com/danielgtaylor/python-betterproto/pull/294)
|
||||
- Fix default values for enum service args [#299](https://github.com/danielgtaylor/python-betterproto/pull/299)
|
||||
|
||||
## [2.0.0b3] - 2021-04-07
|
||||
|
||||
- Generate grpclib service stubs [#170](https://github.com/danielgtaylor/python-betterproto/pull/170)
|
||||
- Add \_\_version\_\_ attribute to package [#134](https://github.com/danielgtaylor/python-betterproto/pull/134)
|
||||
- Use betterproto generated messages in the plugin [#161](https://github.com/danielgtaylor/python-betterproto/pull/161)
|
||||
- Sort the list of sources in generated file headers [#164](https://github.com/danielgtaylor/python-betterproto/pull/164)
|
||||
- Micro-optimization: use tuples instead of lists for conditions [#228](https://github.com/danielgtaylor/python-betterproto/pull/228)
|
||||
- Improve datestring parsing [#213](https://github.com/danielgtaylor/python-betterproto/pull/213)
|
||||
|
||||
- Fix serialization of repeated fields with empty messages [#180](https://github.com/danielgtaylor/python-betterproto/pull/180)
|
||||
- Fix compilation of fields named 'bytes' or 'str' [#226](https://github.com/danielgtaylor/python-betterproto/pull/226)
|
||||
- Fix json serialization of infinite and nan floats/doubles [#215](https://github.com/danielgtaylor/python-betterproto/pull/215)
|
||||
- Fix template bug resulting in empty \_\_post_init\_\_ methods [#162](https://github.com/danielgtaylor/python-betterproto/pull/162)
|
||||
- Fix serialization of zero-value messages in a oneof group [#176](https://github.com/danielgtaylor/python-betterproto/pull/176)
|
||||
- Fix missing typing and datetime imports [#183](https://github.com/danielgtaylor/python-betterproto/pull/183)
|
||||
- Fix code generation for empty services [#222](https://github.com/danielgtaylor/python-betterproto/pull/222)
|
||||
- Fix Message.to_dict and from_dict handling of repeated timestamps and durations [#211](https://github.com/danielgtaylor/python-betterproto/pull/211)
|
||||
- Fix incorrect routes in generated client when service is not in a package [#177](https://github.com/danielgtaylor/python-betterproto/pull/177)
|
||||
|
||||
## [2.0.0b2] - 2020-11-24
|
||||
|
||||
- Add support for deprecated message and fields [#126](https://github.com/danielgtaylor/python-betterproto/pull/126)
|
||||
- Add support for recursive messages [#130](https://github.com/danielgtaylor/python-betterproto/pull/130)
|
||||
- Add support for `bool(Message)` [#142](https://github.com/danielgtaylor/python-betterproto/pull/142)
|
||||
- Improve support for Python 3.9 [#140](https://github.com/danielgtaylor/python-betterproto/pull/140) [#173](https://github.com/danielgtaylor/python-betterproto/pull/173)
|
||||
- Improve keyword sanitisation for generated code [#137](https://github.com/danielgtaylor/python-betterproto/pull/137)
|
||||
|
||||
- Fix missing serialized_on_wire when message contains only lists [#81](https://github.com/danielgtaylor/python-betterproto/pull/81)
|
||||
- Fix circular dependencies [#100](https://github.com/danielgtaylor/python-betterproto/pull/100)
|
||||
- Fix to_dict enum fields when numbering is not consecutive [#102](https://github.com/danielgtaylor/python-betterproto/pull/102)
|
||||
- Fix argument generation for stub methods when using `import` with proto definition [#103](https://github.com/danielgtaylor/python-betterproto/pull/103)
|
||||
- Fix missing async/await keywords when casing [#104](https://github.com/danielgtaylor/python-betterproto/pull/104)
|
||||
- Fix mutable default arguments in generated code [#105](https://github.com/danielgtaylor/python-betterproto/pull/105)
|
||||
- Fix serialisation of default values in oneofs when calling to_dict() or to_json() [#110](https://github.com/danielgtaylor/python-betterproto/pull/110)
|
||||
- Fix static type checking for grpclib client [#124](https://github.com/danielgtaylor/python-betterproto/pull/124)
|
||||
- Fix python3.6 compatibility issue with dataclasses [#124](https://github.com/danielgtaylor/python-betterproto/pull/124)
|
||||
- Fix handling of trailer-only responses [#127](https://github.com/danielgtaylor/python-betterproto/pull/127)
|
||||
|
||||
- Refactor plugin.py to use modular dataclasses in tree-like structure to represent parsed data [#121](https://github.com/danielgtaylor/python-betterproto/pull/121)
|
||||
- Refactor template compilation logic [#136](https://github.com/danielgtaylor/python-betterproto/pull/136)
|
||||
|
||||
- Replace use of platform provided protoc with development dependency on grpcio-tools [#107](https://github.com/danielgtaylor/python-betterproto/pull/107)
|
||||
- Switch to using `poe` from `make` to manage project development tasks [#118](https://github.com/danielgtaylor/python-betterproto/pull/118)
|
||||
- Improve CI platform coverage [#128](https://github.com/danielgtaylor/python-betterproto/pull/128)
|
||||
|
||||
## [2.0.0b1] - 2020-07-04
|
||||
|
||||
[Upgrade Guide](./docs/upgrading.md)
|
||||
@@ -15,8 +143,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
> `2.0.0` will be released once the interface is stable.
|
||||
|
||||
- Add support for gRPC and **stream-stream** [#83](https://github.com/danielgtaylor/python-betterproto/pull/83)
|
||||
- Switch from to `poetry` for development [#75](https://github.com/danielgtaylor/python-betterproto/pull/75)
|
||||
- Fix No arguments are generated for stub methods when using import with proto definition
|
||||
- Switch from `pipenv` to `poetry` for development [#75](https://github.com/danielgtaylor/python-betterproto/pull/75)
|
||||
- Fix two packages with the same name suffix should not cause naming conflict [#25](https://github.com/danielgtaylor/python-betterproto/issues/25)
|
||||
|
||||
- Fix Import child package from root [#57](https://github.com/danielgtaylor/python-betterproto/issues/57)
|
||||
|
||||
21
LICENSE.md
Normal file
21
LICENSE.md
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 Daniel G. Taylor
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
42
Makefile
42
Makefile
@@ -1,42 +0,0 @@
|
||||
.PHONY: help setup generate test types format clean plugin full-test check-style
|
||||
|
||||
help: ## - Show this help.
|
||||
@fgrep -h "##" $(MAKEFILE_LIST) | fgrep -v fgrep | sed -e 's/\\$$//' | sed -e 's/##//'
|
||||
|
||||
# Dev workflow tasks
|
||||
|
||||
generate: ## - Generate test cases (do this once before running test)
|
||||
poetry run ./betterproto/tests/generate.py
|
||||
|
||||
test: ## - Run tests
|
||||
poetry run pytest --cov betterproto
|
||||
|
||||
types: ## - Check types with mypy
|
||||
poetry run mypy betterproto --ignore-missing-imports
|
||||
|
||||
format: ## - Apply black formatting to source code
|
||||
poetry run black . --exclude tests/output_
|
||||
|
||||
clean: ## - Clean out generated files from the workspace
|
||||
rm -rf .coverage \
|
||||
.mypy_cache \
|
||||
.pytest_cache \
|
||||
dist \
|
||||
**/__pycache__ \
|
||||
betterproto/tests/output_*
|
||||
|
||||
# Manual testing
|
||||
|
||||
# By default write plugin output to a directory called output
|
||||
o=output
|
||||
plugin: ## - Execute the protoc plugin, with output write to `output` or the value passed to `-o`
|
||||
mkdir -p $(o)
|
||||
protoc --plugin=protoc-gen-custom=betterproto/plugin.py $(i) --custom_out=$(o)
|
||||
|
||||
# CI tasks
|
||||
|
||||
full-test: generate ## - Run full testing sequence with multiple pythons
|
||||
poetry run tox
|
||||
|
||||
check-style: ## - Check if code style is correct
|
||||
poetry run black . --check --diff --exclude tests/output_
|
||||
150
README.md
150
README.md
@@ -1,18 +1,20 @@
|
||||
# Better Protobuf / gRPC Support for Python
|
||||
|
||||

|
||||
> :octocat: If you're reading this on github, please be aware that it might mention unreleased features! See the latest released README on [pypi](https://pypi.org/project/betterproto/).
|
||||
|
||||
This project aims to provide an improved experience when using Protobuf / gRPC in a modern Python environment by making use of modern language features and generating readable, understandable, idiomatic Python code. It will not support legacy features or environments (e.g. Protobuf 2). The following are supported:
|
||||
|
||||
- Protobuf 3 & gRPC code generation
|
||||
- Both binary & JSON serialization is built-in
|
||||
- Python 3.6+ making use of:
|
||||
- Python 3.7+ making use of:
|
||||
- Enums
|
||||
- Dataclasses
|
||||
- `async`/`await`
|
||||
- Timezone-aware `datetime` and `timedelta` objects
|
||||
- Relative imports
|
||||
- Mypy type checking
|
||||
- [Pydantic Models](https://docs.pydantic.dev/) generation (see #generating-pydantic-models)
|
||||
|
||||
This project is heavily inspired by, and borrows functionality from:
|
||||
|
||||
@@ -38,6 +40,7 @@ This project exists because I am unhappy with the state of the official Google p
|
||||
- Special wrapped types don't use Python's `None`
|
||||
- Timestamp/duration types don't use Python's built-in `datetime` module
|
||||
|
||||
|
||||
This project is a reimplementation from the ground up focused on idiomatic modern Python to help fix some of the above. While it may not be a 1:1 drop-in replacement due to changed method names and call patterns, the wire format is identical.
|
||||
|
||||
## Installation
|
||||
@@ -58,7 +61,7 @@ pip install betterproto
|
||||
|
||||
### Compiling proto files
|
||||
|
||||
Now, given you installed the compiler and have a proto file, e.g `example.proto`:
|
||||
Given you installed the compiler and have a proto file, e.g `example.proto`:
|
||||
|
||||
```protobuf
|
||||
syntax = "proto3";
|
||||
@@ -71,13 +74,20 @@ message Greeting {
|
||||
}
|
||||
```
|
||||
|
||||
You can run the following:
|
||||
You can run the following to invoke protoc directly:
|
||||
|
||||
```sh
|
||||
mkdir lib
|
||||
protoc -I . --python_betterproto_out=lib example.proto
|
||||
```
|
||||
|
||||
or run the following to invoke protoc via grpcio-tools:
|
||||
|
||||
```sh
|
||||
pip install grpcio-tools
|
||||
python -m grpc_tools.protoc -I . --python_betterproto_out=lib example.proto
|
||||
```
|
||||
|
||||
This will generate `lib/hello/__init__.py` which looks like:
|
||||
|
||||
```python
|
||||
@@ -126,7 +136,7 @@ Greeting(message="Hey!")
|
||||
|
||||
The generated Protobuf `Message` classes are compatible with [grpclib](https://github.com/vmagamedov/grpclib) so you are free to use it if you like. That said, this project also includes support for async gRPC stub generation with better static type checking and code completion support. It is enabled by default.
|
||||
|
||||
Given an example like:
|
||||
Given an example service definition:
|
||||
|
||||
```protobuf
|
||||
syntax = "proto3";
|
||||
@@ -153,22 +163,75 @@ service Echo {
|
||||
}
|
||||
```
|
||||
|
||||
You can use it like so (enable async in the interactive shell first):
|
||||
Generate echo proto file:
|
||||
|
||||
```
|
||||
python -m grpc_tools.protoc -I . --python_betterproto_out=. echo.proto
|
||||
```
|
||||
|
||||
A client can be implemented as follows:
|
||||
```python
|
||||
>>> import echo
|
||||
>>> from grpclib.client import Channel
|
||||
import asyncio
|
||||
import echo
|
||||
|
||||
>>> channel = Channel(host="127.0.0.1", port=1234)
|
||||
>>> service = echo.EchoStub(channel)
|
||||
>>> await service.echo(value="hello", extra_times=1)
|
||||
EchoResponse(values=["hello", "hello"])
|
||||
from grpclib.client import Channel
|
||||
|
||||
>>> async for response in service.echo_stream(value="hello", extra_times=1)
|
||||
|
||||
async def main():
|
||||
channel = Channel(host="127.0.0.1", port=50051)
|
||||
service = echo.EchoStub(channel)
|
||||
response = await service.echo(echo.EchoRequest(value="hello", extra_times=1))
|
||||
print(response)
|
||||
|
||||
async for response in service.echo_stream(echo.EchoRequest(value="hello", extra_times=1)):
|
||||
print(response)
|
||||
|
||||
EchoStreamResponse(value="hello")
|
||||
EchoStreamResponse(value="hello")
|
||||
# don't forget to close the channel when done!
|
||||
channel.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
loop = asyncio.get_event_loop()
|
||||
loop.run_until_complete(main())
|
||||
|
||||
```
|
||||
|
||||
which would output
|
||||
```python
|
||||
EchoResponse(values=['hello', 'hello'])
|
||||
EchoStreamResponse(value='hello')
|
||||
EchoStreamResponse(value='hello')
|
||||
```
|
||||
|
||||
This project also produces server-facing stubs that can be used to implement a Python
|
||||
gRPC server.
|
||||
To use them, simply subclass the base class in the generated files and override the
|
||||
service methods:
|
||||
|
||||
```python
|
||||
import asyncio
|
||||
from echo import EchoBase, EchoRequest, EchoResponse, EchoStreamResponse
|
||||
from grpclib.server import Server
|
||||
from typing import AsyncIterator
|
||||
|
||||
|
||||
class EchoService(EchoBase):
|
||||
async def echo(self, echo_request: "EchoRequest") -> "EchoResponse":
|
||||
return EchoResponse([echo_request.value for _ in range(echo_request.extra_times)])
|
||||
|
||||
async def echo_stream(self, echo_request: "EchoRequest") -> AsyncIterator["EchoStreamResponse"]:
|
||||
for _ in range(echo_request.extra_times):
|
||||
yield EchoStreamResponse(echo_request.value)
|
||||
|
||||
|
||||
async def main():
|
||||
server = Server([EchoService()])
|
||||
await server.start("127.0.0.1", 50051)
|
||||
await server.wait_closed()
|
||||
|
||||
if __name__ == '__main__':
|
||||
loop = asyncio.get_event_loop()
|
||||
loop.run_until_complete(main())
|
||||
```
|
||||
|
||||
### JSON
|
||||
@@ -302,37 +365,51 @@ datetime.datetime(2019, 1, 1, 11, 59, 58, 800000, tzinfo=datetime.timezone.utc)
|
||||
{'ts': '2019-01-01T12:00:00Z', 'duration': '1.200s'}
|
||||
```
|
||||
|
||||
## Generating Pydantic Models
|
||||
|
||||
You can use python-betterproto to generate pydantic based models, using
|
||||
pydantic dataclasses. This means the results of the protobuf unmarshalling will
|
||||
be typed checked. The usage is the same, but you need to add a custom option
|
||||
when calling the protobuf compiler:
|
||||
|
||||
|
||||
```
|
||||
protoc -I . --python_betterproto_opt=pydantic_dataclasses --python_betterproto_out=lib example.proto
|
||||
```
|
||||
|
||||
With the important change being `--python_betterproto_opt=pydantic_dataclasses`. This will
|
||||
swap the dataclass implementation from the builtin python dataclass to the
|
||||
pydantic dataclass. You must have pydantic as a dependency in your project for
|
||||
this to work.
|
||||
|
||||
|
||||
|
||||
## Development
|
||||
|
||||
Join us on [Slack](https://join.slack.com/t/betterproto/shared_invite/zt-f0n0uolx-iN8gBNrkPxtKHTLpG3o1OQ)!
|
||||
- _Join us on [Slack](https://join.slack.com/t/betterproto/shared_invite/zt-f0n0uolx-iN8gBNrkPxtKHTLpG3o1OQ)!_
|
||||
- _See how you can help → [Contributing](.github/CONTRIBUTING.md)_
|
||||
|
||||
### Requirements
|
||||
|
||||
- Python (3.6 or higher)
|
||||
|
||||
- [protoc](https://grpc.io/docs/protoc-installation/) (3.12 or higher)
|
||||
*Needed to compile `.proto` files and run the tests*
|
||||
- Python (3.7 or higher)
|
||||
|
||||
- [poetry](https://python-poetry.org/docs/#installation)
|
||||
*Needed to install dependencies in a virtual environment*
|
||||
|
||||
- make ([ubuntu](https://www.howtoinstall.me/ubuntu/18-04/make/), [windows](https://stackoverflow.com/questions/32127524/how-to-install-and-use-make-in-windows), [mac](https://osxdaily.com/2014/02/12/install-command-line-tools-mac-os-x/))
|
||||
|
||||
*Needed to conveniently run development tasks.*
|
||||
*Alternatively, manually run the commands defined in the [Makefile](./Makefile)*
|
||||
- [poethepoet](https://github.com/nat-n/poethepoet) for running development tasks as defined in pyproject.toml
|
||||
- Can be installed to your host environment via `pip install poethepoet` then executed as simple `poe`
|
||||
- or run from the poetry venv as `poetry run poe`
|
||||
|
||||
### Setup
|
||||
|
||||
```sh
|
||||
# Get set up with the virtual env & dependencies
|
||||
poetry install
|
||||
poetry install -E compiler
|
||||
|
||||
# Activate the poetry environment
|
||||
poetry shell
|
||||
```
|
||||
|
||||
Run `make help` to see all available development tasks.
|
||||
|
||||
### Code style
|
||||
|
||||
This project enforces [black](https://github.com/psf/black) python code formatting.
|
||||
@@ -340,7 +417,7 @@ This project enforces [black](https://github.com/psf/black) python code formatti
|
||||
Before committing changes run:
|
||||
|
||||
```sh
|
||||
make format
|
||||
poe format
|
||||
```
|
||||
|
||||
To avoid merge conflicts later, non-black formatted python code will fail in CI.
|
||||
@@ -362,7 +439,7 @@ Adding a standard test case is easy.
|
||||
|
||||
It will be picked up automatically when you run the tests.
|
||||
|
||||
- See also: [Standard Tests Development Guide](betterproto/tests/README.md)
|
||||
- See also: [Standard Tests Development Guide](tests/README.md)
|
||||
|
||||
#### Custom tests
|
||||
|
||||
@@ -374,20 +451,20 @@ Here's how to run the tests.
|
||||
|
||||
```sh
|
||||
# Generate assets from sample .proto files required by the tests
|
||||
make generate
|
||||
poe generate
|
||||
# Run the tests
|
||||
make test
|
||||
poe test
|
||||
```
|
||||
|
||||
To run tests as they are run in CI (with tox) run:
|
||||
|
||||
```sh
|
||||
make full-test
|
||||
poe full-test
|
||||
```
|
||||
|
||||
### (Re)compiling Google Well-known Types
|
||||
|
||||
Betterproto includes compiled versions for Google's well-known types at [betterproto/lib/google](betterproto/lib/google).
|
||||
Betterproto includes compiled versions for Google's well-known types at [src/betterproto/lib/google](src/betterproto/lib/google).
|
||||
Be sure to regenerate these files when modifying the plugin output format, and validate by running the tests.
|
||||
|
||||
Normally, the plugin does not compile any references to `google.protobuf`, since they are pre-compiled. To force compilation of `google.protobuf`, use the option `--custom_opt=INCLUDE_GOOGLE`.
|
||||
@@ -396,14 +473,13 @@ Assuming your `google.protobuf` source files (included with all releases of `pro
|
||||
|
||||
```sh
|
||||
protoc \
|
||||
--plugin=protoc-gen-custom=betterproto/plugin.py \
|
||||
--plugin=protoc-gen-custom=src/betterproto/plugin/main.py \
|
||||
--custom_opt=INCLUDE_GOOGLE \
|
||||
--custom_out=betterproto/lib \
|
||||
--custom_out=src/betterproto/lib \
|
||||
-I /usr/local/include/ \
|
||||
/usr/local/include/google/protobuf/*.proto
|
||||
```
|
||||
|
||||
|
||||
### TODO
|
||||
|
||||
- [x] Fixed length fields
|
||||
@@ -434,10 +510,10 @@ protoc \
|
||||
- [x] Enum strings
|
||||
- [x] Well known types support (timestamp, duration, wrappers)
|
||||
- [x] Support different casing (orig vs. camel vs. others?)
|
||||
- [ ] Async service stubs
|
||||
- [x] Async service stubs
|
||||
- [x] Unary-unary
|
||||
- [x] Server streaming response
|
||||
- [ ] Client streaming request
|
||||
- [x] Client streaming request
|
||||
- [x] Renaming messages and fields to conform to Python name standards
|
||||
- [x] Renaming clashes with language keywords
|
||||
- [x] Python package
|
||||
|
||||
157
asv.conf.json
Normal file
157
asv.conf.json
Normal file
@@ -0,0 +1,157 @@
|
||||
{
|
||||
// The version of the config file format. Do not change, unless
|
||||
// you know what you are doing.
|
||||
"version": 1,
|
||||
|
||||
// The name of the project being benchmarked
|
||||
"project": "python-betterproto",
|
||||
|
||||
// The project's homepage
|
||||
"project_url": "https://github.com/danielgtaylor/python-betterproto",
|
||||
|
||||
// The URL or local path of the source code repository for the
|
||||
// project being benchmarked
|
||||
"repo": ".",
|
||||
|
||||
// The Python project's subdirectory in your repo. If missing or
|
||||
// the empty string, the project is assumed to be located at the root
|
||||
// of the repository.
|
||||
// "repo_subdir": "",
|
||||
|
||||
// Customizable commands for building, installing, and
|
||||
// uninstalling the project. See asv.conf.json documentation.
|
||||
//
|
||||
"install_command": ["python -m pip install ."],
|
||||
"uninstall_command": ["return-code=any python -m pip uninstall -y {project}"],
|
||||
"build_command": ["python -m pip wheel -w {build_cache_dir} {build_dir}"],
|
||||
|
||||
// List of branches to benchmark. If not provided, defaults to "master"
|
||||
// (for git) or "default" (for mercurial).
|
||||
// "branches": ["master"], // for git
|
||||
// "branches": ["default"], // for mercurial
|
||||
|
||||
// The DVCS being used. If not set, it will be automatically
|
||||
// determined from "repo" by looking at the protocol in the URL
|
||||
// (if remote), or by looking for special directories, such as
|
||||
// ".git" (if local).
|
||||
// "dvcs": "git",
|
||||
|
||||
// The tool to use to create environments. May be "conda",
|
||||
// "virtualenv" or other value depending on the plugins in use.
|
||||
// If missing or the empty string, the tool will be automatically
|
||||
// determined by looking for tools on the PATH environment
|
||||
// variable.
|
||||
"environment_type": "virtualenv",
|
||||
|
||||
// timeout in seconds for installing any dependencies in environment
|
||||
// defaults to 10 min
|
||||
//"install_timeout": 600,
|
||||
|
||||
// the base URL to show a commit for the project.
|
||||
// "show_commit_url": "http://github.com/owner/project/commit/",
|
||||
|
||||
// The Pythons you'd like to test against. If not provided, defaults
|
||||
// to the current version of Python used to run `asv`.
|
||||
// "pythons": ["2.7", "3.6"],
|
||||
|
||||
// The list of conda channel names to be searched for benchmark
|
||||
// dependency packages in the specified order
|
||||
// "conda_channels": ["conda-forge", "defaults"],
|
||||
|
||||
// The matrix of dependencies to test. Each key is the name of a
|
||||
// package (in PyPI) and the values are version numbers. An empty
|
||||
// list or empty string indicates to just test against the default
|
||||
// (latest) version. null indicates that the package is to not be
|
||||
// installed. If the package to be tested is only available from
|
||||
// PyPi, and the 'environment_type' is conda, then you can preface
|
||||
// the package name by 'pip+', and the package will be installed via
|
||||
// pip (with all the conda available packages installed first,
|
||||
// followed by the pip installed packages).
|
||||
//
|
||||
// "matrix": {
|
||||
// "numpy": ["1.6", "1.7"],
|
||||
// "six": ["", null], // test with and without six installed
|
||||
// "pip+emcee": [""], // emcee is only available for install with pip.
|
||||
// },
|
||||
|
||||
// Combinations of libraries/python versions can be excluded/included
|
||||
// from the set to test. Each entry is a dictionary containing additional
|
||||
// key-value pairs to include/exclude.
|
||||
//
|
||||
// An exclude entry excludes entries where all values match. The
|
||||
// values are regexps that should match the whole string.
|
||||
//
|
||||
// An include entry adds an environment. Only the packages listed
|
||||
// are installed. The 'python' key is required. The exclude rules
|
||||
// do not apply to includes.
|
||||
//
|
||||
// In addition to package names, the following keys are available:
|
||||
//
|
||||
// - python
|
||||
// Python version, as in the *pythons* variable above.
|
||||
// - environment_type
|
||||
// Environment type, as above.
|
||||
// - sys_platform
|
||||
// Platform, as in sys.platform. Possible values for the common
|
||||
// cases: 'linux2', 'win32', 'cygwin', 'darwin'.
|
||||
//
|
||||
// "exclude": [
|
||||
// {"python": "3.2", "sys_platform": "win32"}, // skip py3.2 on windows
|
||||
// {"environment_type": "conda", "six": null}, // don't run without six on conda
|
||||
// ],
|
||||
//
|
||||
// "include": [
|
||||
// // additional env for python2.7
|
||||
// {"python": "2.7", "numpy": "1.8"},
|
||||
// // additional env if run on windows+conda
|
||||
// {"platform": "win32", "environment_type": "conda", "python": "2.7", "libpython": ""},
|
||||
// ],
|
||||
|
||||
// The directory (relative to the current directory) that benchmarks are
|
||||
// stored in. If not provided, defaults to "benchmarks"
|
||||
// "benchmark_dir": "benchmarks",
|
||||
|
||||
// The directory (relative to the current directory) to cache the Python
|
||||
// environments in. If not provided, defaults to "env"
|
||||
"env_dir": ".asv/env",
|
||||
|
||||
// The directory (relative to the current directory) that raw benchmark
|
||||
// results are stored in. If not provided, defaults to "results".
|
||||
"results_dir": ".asv/results",
|
||||
|
||||
// The directory (relative to the current directory) that the html tree
|
||||
// should be written to. If not provided, defaults to "html".
|
||||
"html_dir": ".asv/html",
|
||||
|
||||
// The number of characters to retain in the commit hashes.
|
||||
// "hash_length": 8,
|
||||
|
||||
// `asv` will cache results of the recent builds in each
|
||||
// environment, making them faster to install next time. This is
|
||||
// the number of builds to keep, per environment.
|
||||
// "build_cache_size": 2,
|
||||
|
||||
// The commits after which the regression search in `asv publish`
|
||||
// should start looking for regressions. Dictionary whose keys are
|
||||
// regexps matching to benchmark names, and values corresponding to
|
||||
// the commit (exclusive) after which to start looking for
|
||||
// regressions. The default is to start from the first commit
|
||||
// with results. If the commit is `null`, regression detection is
|
||||
// skipped for the matching benchmark.
|
||||
//
|
||||
// "regressions_first_commits": {
|
||||
// "some_benchmark": "352cdf", // Consider regressions only after this commit
|
||||
// "another_benchmark": null, // Skip regression detection altogether
|
||||
// },
|
||||
|
||||
// The thresholds for relative change in results, after which `asv
|
||||
// publish` starts reporting regressions. Dictionary of the same
|
||||
// form as in ``regressions_first_commits``, with values
|
||||
// indicating the thresholds. If multiple entries match, the
|
||||
// maximum is taken. If no entry matches, the default is 5%.
|
||||
//
|
||||
// "regressions_thresholds": {
|
||||
// "some_benchmark": 0.01, // Threshold of 1%
|
||||
// "another_benchmark": 0.5, // Threshold of 50%
|
||||
// },
|
||||
}
|
||||
128
benchmarks/benchmarks.py
Normal file
128
benchmarks/benchmarks.py
Normal file
@@ -0,0 +1,128 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import List
|
||||
|
||||
import betterproto
|
||||
|
||||
|
||||
@dataclass
|
||||
class TestMessage(betterproto.Message):
|
||||
foo: int = betterproto.uint32_field(0)
|
||||
bar: str = betterproto.string_field(1)
|
||||
baz: float = betterproto.float_field(2)
|
||||
|
||||
|
||||
@dataclass
|
||||
class TestNestedChildMessage(betterproto.Message):
|
||||
str_key: str = betterproto.string_field(0)
|
||||
bytes_key: bytes = betterproto.bytes_field(1)
|
||||
bool_key: bool = betterproto.bool_field(2)
|
||||
float_key: float = betterproto.float_field(3)
|
||||
int_key: int = betterproto.uint64_field(4)
|
||||
|
||||
|
||||
@dataclass
|
||||
class TestNestedMessage(betterproto.Message):
|
||||
foo: TestNestedChildMessage = betterproto.message_field(0)
|
||||
bar: TestNestedChildMessage = betterproto.message_field(1)
|
||||
baz: TestNestedChildMessage = betterproto.message_field(2)
|
||||
|
||||
|
||||
@dataclass
|
||||
class TestRepeatedMessage(betterproto.Message):
|
||||
foo_repeat: List[str] = betterproto.string_field(0)
|
||||
bar_repeat: List[int] = betterproto.int64_field(1)
|
||||
baz_repeat: List[bool] = betterproto.bool_field(2)
|
||||
|
||||
|
||||
class BenchMessage:
|
||||
"""Test creation and usage a proto message."""
|
||||
|
||||
def setup(self):
|
||||
self.cls = TestMessage
|
||||
self.instance = TestMessage()
|
||||
self.instance_filled = TestMessage(0, "test", 0.0)
|
||||
self.instance_filled_bytes = bytes(self.instance_filled)
|
||||
self.instance_filled_nested = TestNestedMessage(
|
||||
TestNestedChildMessage("foo", bytearray(b"test1"), True, 0.1234, 500),
|
||||
TestNestedChildMessage("bar", bytearray(b"test2"), True, 3.1415, -302),
|
||||
TestNestedChildMessage("baz", bytearray(b"test3"), False, 1e5, 300),
|
||||
)
|
||||
self.instance_filled_nested_bytes = bytes(self.instance_filled_nested)
|
||||
self.instance_filled_repeated = TestRepeatedMessage(
|
||||
[
|
||||
"test1",
|
||||
"test2",
|
||||
"test3",
|
||||
"test4",
|
||||
"test5",
|
||||
"test6",
|
||||
"test7",
|
||||
"test8",
|
||||
"test9",
|
||||
"test10",
|
||||
],
|
||||
[2, -100, 0, 500000, 600, -425678, 1000000000, -300, 1, -694214214466],
|
||||
[True, False, False, False, True, True, False, True, False, False],
|
||||
)
|
||||
self.instance_filled_repeated_bytes = bytes(self.instance_filled_repeated)
|
||||
|
||||
def time_overhead(self):
|
||||
"""Overhead in class definition."""
|
||||
|
||||
@dataclass
|
||||
class Message(betterproto.Message):
|
||||
foo: int = betterproto.uint32_field(0)
|
||||
bar: str = betterproto.string_field(1)
|
||||
baz: float = betterproto.float_field(2)
|
||||
|
||||
def time_instantiation(self):
|
||||
"""Time instantiation"""
|
||||
self.cls()
|
||||
|
||||
def time_attribute_access(self):
|
||||
"""Time to access an attribute"""
|
||||
self.instance.foo
|
||||
self.instance.bar
|
||||
self.instance.baz
|
||||
|
||||
def time_init_with_values(self):
|
||||
"""Time to set an attribute"""
|
||||
self.cls(0, "test", 0.0)
|
||||
|
||||
def time_attribute_setting(self):
|
||||
"""Time to set attributes"""
|
||||
self.instance.foo = 0
|
||||
self.instance.bar = "test"
|
||||
self.instance.baz = 0.0
|
||||
|
||||
def time_serialize(self):
|
||||
"""Time serializing a message to wire."""
|
||||
bytes(self.instance_filled)
|
||||
|
||||
def time_deserialize(self):
|
||||
"""Time deserialize a message."""
|
||||
TestMessage().parse(self.instance_filled_bytes)
|
||||
|
||||
def time_serialize_nested(self):
|
||||
"""Time serializing a nested message to wire."""
|
||||
bytes(self.instance_filled_nested)
|
||||
|
||||
def time_deserialize_nested(self):
|
||||
"""Time deserialize a nested message."""
|
||||
TestNestedMessage().parse(self.instance_filled_nested_bytes)
|
||||
|
||||
def time_serialize_repeated(self):
|
||||
"""Time serializing a repeated message to wire."""
|
||||
bytes(self.instance_filled_repeated)
|
||||
|
||||
def time_deserialize_repeated(self):
|
||||
"""Time deserialize a repeated message."""
|
||||
TestRepeatedMessage().parse(self.instance_filled_repeated_bytes)
|
||||
|
||||
|
||||
class MemSuite:
|
||||
def setup(self):
|
||||
self.cls = TestMessage
|
||||
|
||||
def mem_instance(self):
|
||||
return self.cls()
|
||||
72
betterproto-extras/.gitignore
vendored
Normal file
72
betterproto-extras/.gitignore
vendored
Normal file
@@ -0,0 +1,72 @@
|
||||
/target
|
||||
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
.pytest_cache/
|
||||
*.py[cod]
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
.venv/
|
||||
env/
|
||||
bin/
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
include/
|
||||
man/
|
||||
venv/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
pip-selfcheck.json
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.coverage
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
|
||||
# Mr Developer
|
||||
.mr.developer.cfg
|
||||
.project
|
||||
.pydevproject
|
||||
|
||||
# Rope
|
||||
.ropeproject
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
*.pot
|
||||
|
||||
.DS_Store
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyCharm
|
||||
.idea/
|
||||
|
||||
# VSCode
|
||||
.vscode/
|
||||
|
||||
# Pyenv
|
||||
.python-version
|
||||
383
betterproto-extras/Cargo.lock
generated
Normal file
383
betterproto-extras/Cargo.lock
generated
Normal file
@@ -0,0 +1,383 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 3
|
||||
|
||||
[[package]]
|
||||
name = "anyhow"
|
||||
version = "1.0.75"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
|
||||
|
||||
[[package]]
|
||||
name = "betterproto-extras"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"indoc 2.0.3",
|
||||
"prost-reflect",
|
||||
"pyo3",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "1.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
|
||||
|
||||
[[package]]
|
||||
name = "bytes"
|
||||
version = "1.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be"
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07"
|
||||
|
||||
[[package]]
|
||||
name = "indoc"
|
||||
version = "1.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bfa799dd5ed20a7e349f3b4639aa80d74549c81716d9ec4f994c9b5815598306"
|
||||
|
||||
[[package]]
|
||||
name = "indoc"
|
||||
version = "2.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2c785eefb63ebd0e33416dfcb8d6da0bf27ce752843a45632a67bf10d4d4b5c4"
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.10.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473"
|
||||
dependencies = [
|
||||
"either",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.147"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3"
|
||||
|
||||
[[package]]
|
||||
name = "lock_api"
|
||||
version = "0.4.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c1cc9717a20b1bb222f333e6a92fd32f7d8a18ddc5a3191a11af45dcbf4dcd16"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
"scopeguard",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memoffset"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a634b1c61a95585bd15607c6ab0c4e5b226e695ff2800ba0cdccddf208c406c"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.18.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f"
|
||||
dependencies = [
|
||||
"lock_api",
|
||||
"parking_lot_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot_core"
|
||||
version = "0.9.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "93f00c865fe7cabf650081affecd3871070f26767e7b2070a3ffae14c654b447"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"redox_syscall",
|
||||
"smallvec",
|
||||
"windows-targets",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.66"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "18fb31db3f9bddb2ea821cde30a9f70117e3f119938b5ee630b7403aa6e2ead9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prost"
|
||||
version = "0.11.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b82eaa1d779e9a4bc1c3217db8ffbeabaae1dca241bf70183242128d48681cd"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"prost-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prost-derive"
|
||||
version = "0.11.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e5d2d8d10f3c6ded6da8b05b5fb3b8a5082514344d56c9f871412d29b4e075b4"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"itertools",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 1.0.109",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prost-reflect"
|
||||
version = "0.11.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6b823de344848e011658ac981009100818b322421676740546f8b52ed5249428"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
"prost",
|
||||
"prost-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prost-types"
|
||||
version = "0.11.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "213622a1460818959ac1181aaeb2dc9c7f63df720db7d788b3e24eacd1983e13"
|
||||
dependencies = [
|
||||
"prost",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pyo3"
|
||||
version = "0.19.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e681a6cfdc4adcc93b4d3cf993749a4552018ee0a9b65fc0ccfad74352c72a38"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"indoc 1.0.9",
|
||||
"libc",
|
||||
"memoffset",
|
||||
"parking_lot",
|
||||
"pyo3-build-config",
|
||||
"pyo3-ffi",
|
||||
"pyo3-macros",
|
||||
"unindent",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pyo3-build-config"
|
||||
version = "0.19.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "076c73d0bc438f7a4ef6fdd0c3bb4732149136abd952b110ac93e4edb13a6ba5"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
"target-lexicon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pyo3-ffi"
|
||||
version = "0.19.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e53cee42e77ebe256066ba8aa77eff722b3bb91f3419177cf4cd0f304d3284d9"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"pyo3-build-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pyo3-macros"
|
||||
version = "0.19.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dfeb4c99597e136528c6dd7d5e3de5434d1ceaf487436a3f03b2d56b6fc9efd1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"pyo3-macros-backend",
|
||||
"quote",
|
||||
"syn 1.0.109",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pyo3-macros-backend"
|
||||
version = "0.19.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "947dc12175c254889edc0c02e399476c2f652b4b9ebd123aa655c224de259536"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 1.0.109",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.33"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redox_syscall"
|
||||
version = "0.3.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "scopeguard"
|
||||
version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||
|
||||
[[package]]
|
||||
name = "smallvec"
|
||||
version = "1.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "62bb4feee49fdd9f707ef802e22365a35de4b7b299de4763d44bfea899442ff9"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "1.0.109"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.29"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c324c494eba9d92503e6f1ef2e6df781e78f6a7705a0202d9801b198807d518a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "target-lexicon"
|
||||
version = "0.12.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9d0e916b1148c8e263850e1ebcbd046f333e0683c724876bb0da63ea4373dc8a"
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "97a802ec30afc17eee47b2855fc72e0c4cd62be9b4efe6591edde0ec5bd68d8f"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6bb623b56e39ab7dcd4b1b98bb6c8f8d907ed255b18de254088016b27a8ee19b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.29",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "301abaae475aa91687eb82514b328ab47a211a533026cb25fc3e519b86adfc3c"
|
||||
|
||||
[[package]]
|
||||
name = "unindent"
|
||||
version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e1766d682d402817b5ac4490b3c3002d91dfa0d22812f341609f97b08757359c"
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
|
||||
dependencies = [
|
||||
"windows_aarch64_gnullvm",
|
||||
"windows_aarch64_msvc",
|
||||
"windows_i686_gnu",
|
||||
"windows_i686_msvc",
|
||||
"windows_x86_64_gnu",
|
||||
"windows_x86_64_gnullvm",
|
||||
"windows_x86_64_msvc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnullvm"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
|
||||
14
betterproto-extras/Cargo.toml
Normal file
14
betterproto-extras/Cargo.toml
Normal file
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "betterproto-extras"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
name = "betterproto_extras"
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
indoc = "2.0.3"
|
||||
prost-reflect = "0.11.5"
|
||||
pyo3 = { version = "0.19.2", features = ["abi3-py37", "extension-module"] }
|
||||
thiserror = "1.0.47"
|
||||
5
betterproto-extras/betterproto_extras.pyi
Normal file
5
betterproto-extras/betterproto_extras.pyi
Normal file
@@ -0,0 +1,5 @@
|
||||
def deserialize(msg, data: bytes):
|
||||
"""
|
||||
Parses the binary encoded Protobuf `data` with respect to the metadata
|
||||
given by the betterproto message `msg`, and merges the result into `msg`.
|
||||
"""
|
||||
16
betterproto-extras/pyproject.toml
Normal file
16
betterproto-extras/pyproject.toml
Normal file
@@ -0,0 +1,16 @@
|
||||
[build-system]
|
||||
requires = ["maturin>=1.2,<2.0"]
|
||||
build-backend = "maturin"
|
||||
|
||||
[project]
|
||||
name = "betterproto-extras"
|
||||
requires-python = ">=3.7"
|
||||
classifiers = [
|
||||
"Programming Language :: Rust",
|
||||
"Programming Language :: Python :: Implementation :: CPython",
|
||||
"Programming Language :: Python :: Implementation :: PyPy",
|
||||
]
|
||||
|
||||
|
||||
[tool.maturin]
|
||||
features = ["pyo3/extension-module"]
|
||||
289
betterproto-extras/src/descriptor_pool.rs
Normal file
289
betterproto-extras/src/descriptor_pool.rs
Normal file
@@ -0,0 +1,289 @@
|
||||
use crate::{
|
||||
error::{Error, Result},
|
||||
py_any_extras::PyAnyExtras,
|
||||
};
|
||||
use prost_reflect::{
|
||||
prost_types::{
|
||||
field_descriptor_proto::{Label, Type},
|
||||
DescriptorProto, EnumDescriptorProto, EnumValueDescriptorProto, FieldDescriptorProto,
|
||||
FileDescriptorProto, MessageOptions, OneofDescriptorProto,
|
||||
},
|
||||
DescriptorPool, MessageDescriptor,
|
||||
};
|
||||
use pyo3::PyAny;
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
|
||||
pub fn create_cached_descriptor(obj: &PyAny) -> Result<MessageDescriptor> {
|
||||
static DESCRIPTOR_POOL: OnceLock<Mutex<DescriptorPool>> = OnceLock::new();
|
||||
let mut pool = DESCRIPTOR_POOL
|
||||
.get_or_init(|| Mutex::new(DescriptorPool::global()))
|
||||
.lock()
|
||||
.unwrap();
|
||||
|
||||
let cls = obj.getattr("__class__")?;
|
||||
let name = format!("{}_{}", cls.qualified_name()?, cls.py_identifier());
|
||||
if let Some(desc) = pool.get_message_by_name(&name) {
|
||||
return Ok(desc);
|
||||
}
|
||||
|
||||
let mut file = FileDescriptorProto {
|
||||
name: Some(name.clone()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
add_message_to_file(name.clone(), obj, &pool, &mut file)?;
|
||||
pool.add_file_descriptor_proto(file)?;
|
||||
Ok(pool.get_message_by_name(&name).expect("Just registered..."))
|
||||
}
|
||||
|
||||
fn add_message_to_file(
|
||||
message_name: String,
|
||||
obj: &PyAny,
|
||||
pool: &DescriptorPool,
|
||||
file: &mut FileDescriptorProto,
|
||||
) -> Result<()> {
|
||||
let mut messages_to_add = vec![(message_name, obj)];
|
||||
|
||||
while let Some((message_name, obj)) = messages_to_add.pop() {
|
||||
let meta = obj.get_proto_meta()?;
|
||||
let mut message = DescriptorProto {
|
||||
name: Some(message_name.to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
for item in meta
|
||||
.getattr("meta_by_field_name")?
|
||||
.call_method0("items")?
|
||||
.iter()?
|
||||
{
|
||||
let (field_name, field_meta) = item?.extract::<(&str, &PyAny)>()?;
|
||||
message.field.push({
|
||||
let mut field = FieldDescriptorProto {
|
||||
name: Some(field_name.to_string()),
|
||||
number: Some(field_meta.getattr("number")?.extract::<i32>()?),
|
||||
..Default::default()
|
||||
};
|
||||
let proto_type = field_meta.getattr("proto_type")?.extract::<&str>()?;
|
||||
|
||||
if proto_type == "map" {
|
||||
field.set_type(Type::Message);
|
||||
let (key, val) = field_meta.getattr("map_types")?.extract::<(&str, &str)>()?;
|
||||
let key = map_type(key)?;
|
||||
let val = map_type(val)?;
|
||||
|
||||
if matches!(
|
||||
key,
|
||||
Type::Float | Type::Double | Type::Bytes | Type::Message | Type::Enum
|
||||
) {
|
||||
return Err(Error::UnsupportedMapKeyType(key));
|
||||
}
|
||||
|
||||
let map_entry_name = format!("{field_name}Entry");
|
||||
field.type_name = Some(format!("{message_name}.{map_entry_name}"));
|
||||
field.set_label(Label::Repeated);
|
||||
message.nested_type.push(DescriptorProto {
|
||||
name: Some(map_entry_name),
|
||||
field: vec![
|
||||
{
|
||||
let mut proto = FieldDescriptorProto {
|
||||
name: Some("key".to_string()),
|
||||
number: Some(1),
|
||||
..Default::default()
|
||||
};
|
||||
proto.set_type(key);
|
||||
proto
|
||||
},
|
||||
{
|
||||
let mut proto = FieldDescriptorProto {
|
||||
name: Some("value".to_string()),
|
||||
number: Some(2),
|
||||
..Default::default()
|
||||
};
|
||||
proto.set_type(val);
|
||||
if val == Type::Message {
|
||||
set_type_name(
|
||||
&message_name,
|
||||
meta.get_class(&format!("{field_name}.value"))?,
|
||||
&mut proto,
|
||||
file,
|
||||
&mut messages_to_add,
|
||||
pool,
|
||||
)?;
|
||||
}
|
||||
proto
|
||||
},
|
||||
],
|
||||
options: Some(MessageOptions {
|
||||
map_entry: Some(true),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
})
|
||||
} else {
|
||||
field.set_type(map_type(proto_type)?);
|
||||
match field.r#type() {
|
||||
Type::Message => match field_meta
|
||||
.getattr("wraps")?
|
||||
.extract::<Option<&str>>()?
|
||||
.map(map_type)
|
||||
.transpose()?
|
||||
{
|
||||
Some(Type::Bool) => {
|
||||
field.type_name = Some("google.protobuf.BoolValue".to_string());
|
||||
}
|
||||
Some(Type::Double) => {
|
||||
field.type_name = Some("google.protobuf.DoubleValue".to_string());
|
||||
}
|
||||
Some(Type::Float) => {
|
||||
field.type_name = Some("google.protobuf.FloatValue".to_string());
|
||||
}
|
||||
Some(Type::Int64) => {
|
||||
field.type_name = Some("google.protobuf.Int64Value".to_string());
|
||||
}
|
||||
Some(Type::Uint64) => {
|
||||
field.type_name = Some("google.protobuf.UInt64Value".to_string());
|
||||
}
|
||||
Some(Type::Int32) => {
|
||||
field.type_name = Some("google.protobuf.Int32Value".to_string());
|
||||
}
|
||||
Some(Type::Uint32) => {
|
||||
field.type_name = Some("google.protobuf.UInt32Value".to_string());
|
||||
}
|
||||
Some(Type::String) => {
|
||||
field.type_name = Some("google.protobuf.StringValue".to_string());
|
||||
}
|
||||
Some(Type::Bytes) => {
|
||||
field.type_name = Some("google.protobuf.BytesValue".to_string());
|
||||
}
|
||||
Some(t) => return Err(Error::UnsupportedWrapperType(t)),
|
||||
None => {
|
||||
set_type_name(
|
||||
&message_name,
|
||||
meta.get_class(field_name)?,
|
||||
&mut field,
|
||||
file,
|
||||
&mut messages_to_add,
|
||||
pool,
|
||||
)?;
|
||||
}
|
||||
},
|
||||
Type::Enum => {
|
||||
let cls = meta.get_class(field_name)?;
|
||||
let cls_name =
|
||||
format!("{}_{}", cls.qualified_name()?, cls.py_identifier());
|
||||
field.type_name = Some(cls_name.to_string());
|
||||
|
||||
if pool.get_enum_by_name(&cls_name).is_none()
|
||||
&& !file.enum_type.iter().any(|item| item.name() == cls_name)
|
||||
{
|
||||
let mut proto = EnumDescriptorProto {
|
||||
name: Some(cls_name.clone()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
for item in cls.iter()? {
|
||||
let item = item?;
|
||||
proto.value.push(EnumValueDescriptorProto {
|
||||
number: Some(item.getattr("value")?.extract()?),
|
||||
name: Some(format!(
|
||||
"{}_{}",
|
||||
cls_name,
|
||||
item.getattr("name")?.extract::<&str>()?
|
||||
)),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
|
||||
file.enum_type.push(proto);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
if meta.is_list_field(field_name)? {
|
||||
field.set_label(Label::Repeated);
|
||||
} else if field_meta.getattr("optional")?.extract::<bool>()? {
|
||||
field.proto3_optional = Some(true);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(grp) = meta.oneof_group(field_name)? {
|
||||
let oneof_index = message.oneof_decl.iter().position(|x| x.name() == grp);
|
||||
|
||||
match oneof_index {
|
||||
Some(i) => field.oneof_index = Some(i as i32),
|
||||
None => {
|
||||
message.oneof_decl.push(OneofDescriptorProto {
|
||||
name: Some(grp),
|
||||
..Default::default()
|
||||
});
|
||||
field.oneof_index = Some((message.oneof_decl.len() - 1) as i32)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
field
|
||||
});
|
||||
}
|
||||
|
||||
file.message_type.push(message);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn map_type(str: &str) -> Result<Type> {
|
||||
match str {
|
||||
"enum" => Ok(Type::Enum),
|
||||
"bool" => Ok(Type::Bool),
|
||||
"int32" => Ok(Type::Int32),
|
||||
"int64" => Ok(Type::Int64),
|
||||
"uint32" => Ok(Type::Uint32),
|
||||
"uint64" => Ok(Type::Uint64),
|
||||
"sint32" => Ok(Type::Sint32),
|
||||
"sint64" => Ok(Type::Sint64),
|
||||
"float" => Ok(Type::Float),
|
||||
"double" => Ok(Type::Double),
|
||||
"fixed32" => Ok(Type::Fixed32),
|
||||
"sfixed32" => Ok(Type::Sfixed32),
|
||||
"fixed64" => Ok(Type::Fixed64),
|
||||
"sfixed64" => Ok(Type::Sfixed64),
|
||||
"string" => Ok(Type::String),
|
||||
"bytes" => Ok(Type::Bytes),
|
||||
"message" => Ok(Type::Message),
|
||||
_ => Err(Error::UnsupportedType(str.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_type_name<'py>(
|
||||
message_name: &str,
|
||||
field_cls: &'py PyAny,
|
||||
field: &mut FieldDescriptorProto,
|
||||
file: &FileDescriptorProto,
|
||||
messages_to_add: &mut Vec<(String, &'py PyAny)>,
|
||||
pool: &DescriptorPool,
|
||||
) -> Result<()> {
|
||||
let cls_name = field_cls.qualified_name()?;
|
||||
|
||||
match cls_name.as_str() {
|
||||
"datetime.datetime" => {
|
||||
field.type_name = Some("google.protobuf.Timestamp".to_string());
|
||||
}
|
||||
"datetime.timedelta" => {
|
||||
field.type_name = Some("google.protobuf.Duration".to_string());
|
||||
}
|
||||
_ => {
|
||||
let cls_name = format!("{}_{}", cls_name, field_cls.py_identifier());
|
||||
field.type_name = Some(cls_name.clone());
|
||||
|
||||
if message_name != cls_name
|
||||
&& pool.get_message_by_name(&cls_name).is_none()
|
||||
&& !file.message_type.iter().any(|item| item.name() == cls_name)
|
||||
&& !messages_to_add.iter().any(|item| item.0 == cls_name)
|
||||
{
|
||||
messages_to_add.push((cls_name, field_cls.call0()?));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
29
betterproto-extras/src/error.rs
Normal file
29
betterproto-extras/src/error.rs
Normal file
@@ -0,0 +1,29 @@
|
||||
use prost_reflect::{
|
||||
prost::DecodeError, prost_types::field_descriptor_proto::Type, DescriptorError,
|
||||
};
|
||||
use pyo3::{exceptions::PyRuntimeError, PyErr};
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum Error {
|
||||
#[error("Given object is not a valid betterproto message.")]
|
||||
NoBetterprotoMessage(#[from] PyErr),
|
||||
#[error("Unsupported type `{0}`.")]
|
||||
UnsupportedType(String),
|
||||
#[error("Unsupported map key type `{0:?}`.")]
|
||||
UnsupportedMapKeyType(Type),
|
||||
#[error("Unsupported wrapper type `{0:?}`.")]
|
||||
UnsupportedWrapperType(Type),
|
||||
#[error("Error on proto registration")]
|
||||
FailedToRegisterDescriptor(#[from] DescriptorError),
|
||||
#[error("The given binary data does not match the protobuf schema.")]
|
||||
FailedToDecode(#[from] DecodeError),
|
||||
}
|
||||
|
||||
pub type Result<T> = core::result::Result<T, Error>;
|
||||
|
||||
impl From<Error> for PyErr {
|
||||
fn from(value: Error) -> Self {
|
||||
PyRuntimeError::new_err(value.to_string())
|
||||
}
|
||||
}
|
||||
24
betterproto-extras/src/lib.rs
Normal file
24
betterproto-extras/src/lib.rs
Normal file
@@ -0,0 +1,24 @@
|
||||
mod descriptor_pool;
|
||||
mod error;
|
||||
mod merging;
|
||||
mod py_any_extras;
|
||||
|
||||
use descriptor_pool::create_cached_descriptor;
|
||||
use error::Result;
|
||||
use merging::merge_msg_into_pyobj;
|
||||
use prost_reflect::DynamicMessage;
|
||||
use pyo3::prelude::*;
|
||||
|
||||
#[pyfunction]
|
||||
fn deserialize(obj: &PyAny, buf: &[u8]) -> Result<()> {
|
||||
let desc = create_cached_descriptor(obj)?;
|
||||
let msg = DynamicMessage::decode(desc, buf)?;
|
||||
merge_msg_into_pyobj(obj, msg)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[pymodule]
|
||||
fn betterproto_extras(_py: Python, m: &PyModule) -> PyResult<()> {
|
||||
m.add_function(wrap_pyfunction!(deserialize, m)?)?;
|
||||
Ok(())
|
||||
}
|
||||
182
betterproto-extras/src/merging.rs
Normal file
182
betterproto-extras/src/merging.rs
Normal file
@@ -0,0 +1,182 @@
|
||||
use crate::{error::Result, py_any_extras::PyAnyExtras};
|
||||
use indoc::indoc;
|
||||
use prost_reflect::{
|
||||
prost_types::{Duration, Timestamp},
|
||||
DynamicMessage, MapKey, ReflectMessage, Value,
|
||||
};
|
||||
use pyo3::{
|
||||
sync::GILOnceCell,
|
||||
types::{IntoPyDict, PyBytes, PyModule},
|
||||
Py, PyAny, PyObject, Python, ToPyObject,
|
||||
};
|
||||
|
||||
pub fn merge_msg_into_pyobj(obj: &PyAny, mut msg: DynamicMessage) -> Result<()> {
|
||||
for field in msg.take_fields() {
|
||||
let field_name = field.0.name();
|
||||
let proto_meta = obj.get_proto_meta()?;
|
||||
obj.setattr(
|
||||
field_name,
|
||||
map_field_value(field_name, field.1, proto_meta)?,
|
||||
)?;
|
||||
}
|
||||
|
||||
let mut buf = vec![];
|
||||
for field in msg.unknown_fields() {
|
||||
field.encode(&mut buf);
|
||||
}
|
||||
if !buf.is_empty() {
|
||||
let mut unknown_fields = obj.getattr("_unknown_fields")?.extract::<Vec<u8>>()?;
|
||||
unknown_fields.append(&mut buf);
|
||||
obj.setattr("_unknown_fields", PyBytes::new(obj.py(), &unknown_fields))?;
|
||||
}
|
||||
|
||||
obj.setattr("_serialized_on_wire", true)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn map_field_value(field_name: &str, field_value: Value, proto_meta: &PyAny) -> Result<PyObject> {
|
||||
let py = proto_meta.py();
|
||||
match field_value {
|
||||
Value::Bool(x) => Ok(x.to_object(py)),
|
||||
Value::Bytes(x) => Ok(PyBytes::new(py, &x).to_object(py)),
|
||||
Value::F32(x) => Ok(x.to_object(py)),
|
||||
Value::F64(x) => Ok(x.to_object(py)),
|
||||
Value::I32(x) => Ok(x.to_object(py)),
|
||||
Value::I64(x) => Ok(x.to_object(py)),
|
||||
Value::String(x) => Ok(x.to_object(py)),
|
||||
Value::U32(x) => Ok(x.to_object(py)),
|
||||
Value::U64(x) => Ok(x.to_object(py)),
|
||||
Value::Message(msg) => match msg.descriptor().full_name() {
|
||||
"google.protobuf.BoolValue" => Ok(msg
|
||||
.get_field_by_number(1)
|
||||
.and_then(|val| val.as_bool())
|
||||
.to_object(py)),
|
||||
"google.protobuf.DoubleValue" => Ok(msg
|
||||
.get_field_by_number(1)
|
||||
.and_then(|val| val.as_f64())
|
||||
.to_object(py)),
|
||||
"google.protobuf.FloatValue" => Ok(msg
|
||||
.get_field_by_number(1)
|
||||
.and_then(|val| val.as_f32())
|
||||
.to_object(py)),
|
||||
"google.protobuf.Int64Value" => Ok(msg
|
||||
.get_field_by_number(1)
|
||||
.and_then(|val| val.as_i64())
|
||||
.to_object(py)),
|
||||
"google.protobuf.UInt64Value" => Ok(msg
|
||||
.get_field_by_number(1)
|
||||
.and_then(|val| val.as_u64())
|
||||
.to_object(py)),
|
||||
"google.protobuf.Int32Value" => Ok(msg
|
||||
.get_field_by_number(1)
|
||||
.and_then(|val| val.as_i32())
|
||||
.to_object(py)),
|
||||
"google.protobuf.UInt32Value" => Ok(msg
|
||||
.get_field_by_number(1)
|
||||
.and_then(|val| val.as_u32())
|
||||
.to_object(py)),
|
||||
"google.protobuf.StringValue" => Ok(msg
|
||||
.get_field_by_number(1)
|
||||
.and_then(|val| val.as_str().map(|s| s.to_string()))
|
||||
.to_object(py)),
|
||||
"google.protobuf.BytesValue" => Ok(msg
|
||||
.get_field_by_number(1)
|
||||
.and_then(|val| val.as_bytes().map(|b| PyBytes::new(py, b)))
|
||||
.to_object(py)),
|
||||
"google.protobuf.Timestamp" => {
|
||||
let msg = msg.transcode_to::<Timestamp>()?;
|
||||
Ok(create_py_datetime(&msg, py))
|
||||
}
|
||||
"google.protobuf.Duration" => {
|
||||
let msg = msg.transcode_to::<Duration>()?;
|
||||
Ok(create_py_timedelta(&msg, py))
|
||||
}
|
||||
_ => {
|
||||
let obj = proto_meta.create_instance(field_name)?;
|
||||
merge_msg_into_pyobj(obj, msg)?;
|
||||
Ok(obj.to_object(py))
|
||||
}
|
||||
},
|
||||
Value::List(ls) => Ok(ls
|
||||
.into_iter()
|
||||
.map(|x| map_field_value(field_name, x, proto_meta))
|
||||
.collect::<Result<Vec<PyObject>>>()?
|
||||
.to_object(py)),
|
||||
Value::EnumNumber(x) => {
|
||||
let cls = proto_meta.get_class(field_name)?;
|
||||
Ok(cls.call1((x,))?.to_object(py))
|
||||
}
|
||||
Value::Map(map) => {
|
||||
let res: Result<Vec<_>> = map
|
||||
.into_iter()
|
||||
.map(|(k, v)| {
|
||||
let key = map_key(k, py);
|
||||
let val = map_field_value(&format!("{field_name}.value"), v, proto_meta)?;
|
||||
Ok((key, val))
|
||||
})
|
||||
.collect();
|
||||
Ok(res?.into_py_dict(py).to_object(py))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn map_key(key: MapKey, py: Python) -> PyObject {
|
||||
match key {
|
||||
MapKey::Bool(x) => x.to_object(py),
|
||||
MapKey::I32(x) => x.to_object(py),
|
||||
MapKey::I64(x) => x.to_object(py),
|
||||
MapKey::U32(x) => x.to_object(py),
|
||||
MapKey::U64(x) => x.to_object(py),
|
||||
MapKey::String(x) => x.to_object(py),
|
||||
}
|
||||
}
|
||||
|
||||
fn create_py_datetime(ts: &Timestamp, py: Python) -> PyObject {
|
||||
static CONSTRUCTOR_CACHE: GILOnceCell<Py<PyAny>> = GILOnceCell::new();
|
||||
let constructor = CONSTRUCTOR_CACHE.get_or_init(py, || {
|
||||
let constructor = PyModule::from_code(
|
||||
py,
|
||||
indoc! {"
|
||||
from datetime import datetime, timezone
|
||||
|
||||
def constructor(ts):
|
||||
return datetime.fromtimestamp(ts, tz=timezone.utc)
|
||||
"},
|
||||
"",
|
||||
"",
|
||||
)
|
||||
.expect("This is a valid Python module")
|
||||
.getattr("constructor")
|
||||
.expect("Attribute exists");
|
||||
Py::from(constructor)
|
||||
});
|
||||
let ts = (ts.seconds as f64) + (ts.nanos as f64) / 1e9;
|
||||
constructor
|
||||
.call1(py, (ts,))
|
||||
.expect("static function will not fail")
|
||||
}
|
||||
|
||||
fn create_py_timedelta(duration: &Duration, py: Python) -> PyObject {
|
||||
static CONSTRUCTOR_CACHE: GILOnceCell<Py<PyAny>> = GILOnceCell::new();
|
||||
let constructor = CONSTRUCTOR_CACHE.get_or_init(py, || {
|
||||
let constructor = PyModule::from_code(
|
||||
py,
|
||||
indoc! {"
|
||||
from datetime import timedelta
|
||||
|
||||
def constructor(s, ms):
|
||||
return timedelta(seconds=s, microseconds=ms)
|
||||
"},
|
||||
"",
|
||||
"",
|
||||
)
|
||||
.expect("This is a valid Python module")
|
||||
.getattr("constructor")
|
||||
.expect("Attribute exists");
|
||||
Py::from(constructor)
|
||||
});
|
||||
constructor
|
||||
.call1(py, (duration.seconds as f64, (duration.nanos as f64) / 1e3))
|
||||
.expect("static function will not fail")
|
||||
}
|
||||
68
betterproto-extras/src/py_any_extras.rs
Normal file
68
betterproto-extras/src/py_any_extras.rs
Normal file
@@ -0,0 +1,68 @@
|
||||
use crate::error::Result;
|
||||
use pyo3::{PyAny, Py, sync::GILOnceCell};
|
||||
|
||||
pub trait PyAnyExtras {
|
||||
fn qualified_name(&self) -> Result<String>;
|
||||
fn qualified_class_name(&self) -> Result<String>;
|
||||
fn get_proto_meta(&self) -> Result<&PyAny>;
|
||||
fn get_class(&self, field_name: &str) -> Result<&PyAny>;
|
||||
fn create_instance(&self, field_name: &str) -> Result<&PyAny>;
|
||||
fn is_list_field(&self, field_name: &str) -> Result<bool>;
|
||||
fn oneof_group(&self, field_name: &str) -> Result<Option<String>>;
|
||||
fn py_identifier(&self) -> u64;
|
||||
}
|
||||
|
||||
impl PyAnyExtras for PyAny {
|
||||
fn qualified_name(&self) -> Result<String> {
|
||||
let module = self.getattr("__module__")?;
|
||||
let name = self.getattr("__name__")?;
|
||||
Ok(format!("{module}.{name}"))
|
||||
}
|
||||
|
||||
fn qualified_class_name(&self) -> Result<String> {
|
||||
self.getattr("__class__")?.qualified_name()
|
||||
}
|
||||
|
||||
fn get_proto_meta(&self) -> Result<&PyAny> {
|
||||
Ok(self.getattr("_betterproto")?)
|
||||
}
|
||||
|
||||
fn get_class(&self, field_name: &str) -> Result<&PyAny> {
|
||||
let cls = self.getattr("cls_by_field")?.get_item(field_name)?;
|
||||
Ok(cls)
|
||||
}
|
||||
|
||||
fn create_instance(&self, field_name: &str) -> Result<&PyAny> {
|
||||
Ok(self.get_class(field_name)?.call0()?)
|
||||
}
|
||||
|
||||
fn is_list_field(&self, field_name: &str) -> Result<bool> {
|
||||
let cls = self.getattr("default_gen")?.get_item(field_name)?;
|
||||
let module = cls.getattr("__module__")?;
|
||||
let name = cls.getattr("__name__")?;
|
||||
Ok(module.to_string() == "builtins" && name.to_string() == "list")
|
||||
}
|
||||
|
||||
fn oneof_group(&self, field_name: &str) -> Result<Option<String>> {
|
||||
let opt = self
|
||||
.getattr("oneof_group_by_field")?
|
||||
.call_method1("get", (field_name,))?
|
||||
.extract()?;
|
||||
Ok(opt)
|
||||
}
|
||||
|
||||
fn py_identifier(&self) -> u64 {
|
||||
static FUN_CACHE: GILOnceCell<Py<PyAny>> = GILOnceCell::new();
|
||||
let py = self.py();
|
||||
let fun = FUN_CACHE.get_or_init(py, || {
|
||||
let fun = py
|
||||
.eval("id", None, None)
|
||||
.expect("This is a valid Python expression");
|
||||
Py::from(fun)
|
||||
});
|
||||
fun.call1(py, (self,))
|
||||
.expect("Identity function is callable")
|
||||
.extract::<u64>(py)
|
||||
.expect("Identity function always returns an integer")
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,2 +0,0 @@
|
||||
@SET plugin_dir=%~dp0
|
||||
@python %plugin_dir%/plugin.py %*
|
||||
@@ -1,403 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
import itertools
|
||||
import os.path
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import textwrap
|
||||
from typing import List, Union
|
||||
|
||||
import betterproto
|
||||
from betterproto.compile.importing import get_type_reference
|
||||
from betterproto.compile.naming import (
|
||||
pythonize_class_name,
|
||||
pythonize_field_name,
|
||||
pythonize_method_name,
|
||||
)
|
||||
|
||||
try:
|
||||
# betterproto[compiler] specific dependencies
|
||||
import black
|
||||
from google.protobuf.compiler import plugin_pb2 as plugin
|
||||
from google.protobuf.descriptor_pb2 import (
|
||||
DescriptorProto,
|
||||
EnumDescriptorProto,
|
||||
FieldDescriptorProto,
|
||||
)
|
||||
import google.protobuf.wrappers_pb2 as google_wrappers
|
||||
import jinja2
|
||||
except ImportError as err:
|
||||
missing_import = err.args[0][17:-1]
|
||||
print(
|
||||
"\033[31m"
|
||||
f"Unable to import `{missing_import}` from betterproto plugin! "
|
||||
"Please ensure that you've installed betterproto as "
|
||||
'`pip install "betterproto[compiler]"` so that compiler dependencies '
|
||||
"are included."
|
||||
"\033[0m"
|
||||
)
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def py_type(package: str, imports: set, field: FieldDescriptorProto) -> str:
|
||||
if field.type in [1, 2]:
|
||||
return "float"
|
||||
elif field.type in [3, 4, 5, 6, 7, 13, 15, 16, 17, 18]:
|
||||
return "int"
|
||||
elif field.type == 8:
|
||||
return "bool"
|
||||
elif field.type == 9:
|
||||
return "str"
|
||||
elif field.type in [11, 14]:
|
||||
# Type referencing another defined Message or a named enum
|
||||
return get_type_reference(package, imports, field.type_name)
|
||||
elif field.type == 12:
|
||||
return "bytes"
|
||||
else:
|
||||
raise NotImplementedError(f"Unknown type {field.type}")
|
||||
|
||||
|
||||
def get_py_zero(type_num: int) -> Union[str, float]:
|
||||
zero: Union[str, float] = 0
|
||||
if type_num in []:
|
||||
zero = 0.0
|
||||
elif type_num == 8:
|
||||
zero = "False"
|
||||
elif type_num == 9:
|
||||
zero = '""'
|
||||
elif type_num == 11:
|
||||
zero = "None"
|
||||
elif type_num == 12:
|
||||
zero = 'b""'
|
||||
|
||||
return zero
|
||||
|
||||
|
||||
def traverse(proto_file):
|
||||
def _traverse(path, items, prefix=""):
|
||||
for i, item in enumerate(items):
|
||||
# Adjust the name since we flatten the heirarchy.
|
||||
item.name = next_prefix = prefix + item.name
|
||||
yield item, path + [i]
|
||||
|
||||
if isinstance(item, DescriptorProto):
|
||||
for enum in item.enum_type:
|
||||
enum.name = next_prefix + enum.name
|
||||
yield enum, path + [i, 4]
|
||||
|
||||
if item.nested_type:
|
||||
for n, p in _traverse(path + [i, 3], item.nested_type, next_prefix):
|
||||
yield n, p
|
||||
|
||||
return itertools.chain(
|
||||
_traverse([5], proto_file.enum_type), _traverse([4], proto_file.message_type)
|
||||
)
|
||||
|
||||
|
||||
def get_comment(proto_file, path: List[int], indent: int = 4) -> str:
|
||||
pad = " " * indent
|
||||
for sci in proto_file.source_code_info.location:
|
||||
# print(list(sci.path), path, file=sys.stderr)
|
||||
if list(sci.path) == path and sci.leading_comments:
|
||||
lines = textwrap.wrap(
|
||||
sci.leading_comments.strip().replace("\n", ""), width=79 - indent
|
||||
)
|
||||
|
||||
if path[-2] == 2 and path[-4] != 6:
|
||||
# This is a field
|
||||
return f"{pad}# " + f"\n{pad}# ".join(lines)
|
||||
else:
|
||||
# This is a message, enum, service, or method
|
||||
if len(lines) == 1 and len(lines[0]) < 79 - indent - 6:
|
||||
lines[0] = lines[0].strip('"')
|
||||
return f'{pad}"""{lines[0]}"""'
|
||||
else:
|
||||
joined = f"\n{pad}".join(lines)
|
||||
return f'{pad}"""\n{pad}{joined}\n{pad}"""'
|
||||
|
||||
return ""
|
||||
|
||||
|
||||
def generate_code(request, response):
|
||||
plugin_options = request.parameter.split(",") if request.parameter else []
|
||||
|
||||
env = jinja2.Environment(
|
||||
trim_blocks=True,
|
||||
lstrip_blocks=True,
|
||||
loader=jinja2.FileSystemLoader("%s/templates/" % os.path.dirname(__file__)),
|
||||
)
|
||||
template = env.get_template("template.py.j2")
|
||||
|
||||
output_map = {}
|
||||
for proto_file in request.proto_file:
|
||||
if (
|
||||
proto_file.package == "google.protobuf"
|
||||
and "INCLUDE_GOOGLE" not in plugin_options
|
||||
):
|
||||
continue
|
||||
|
||||
output_file = str(pathlib.Path(*proto_file.package.split("."), "__init__.py"))
|
||||
|
||||
if output_file not in output_map:
|
||||
output_map[output_file] = {"package": proto_file.package, "files": []}
|
||||
output_map[output_file]["files"].append(proto_file)
|
||||
|
||||
# TODO: Figure out how to handle gRPC request/response messages and add
|
||||
# processing below for Service.
|
||||
|
||||
for filename, options in output_map.items():
|
||||
package = options["package"]
|
||||
# print(package, filename, file=sys.stderr)
|
||||
output = {
|
||||
"package": package,
|
||||
"files": [f.name for f in options["files"]],
|
||||
"imports": set(),
|
||||
"datetime_imports": set(),
|
||||
"typing_imports": set(),
|
||||
"messages": [],
|
||||
"enums": [],
|
||||
"services": [],
|
||||
}
|
||||
|
||||
for proto_file in options["files"]:
|
||||
item: DescriptorProto
|
||||
for item, path in traverse(proto_file):
|
||||
data = {"name": item.name, "py_name": pythonize_class_name(item.name)}
|
||||
|
||||
if isinstance(item, DescriptorProto):
|
||||
# print(item, file=sys.stderr)
|
||||
if item.options.map_entry:
|
||||
# Skip generated map entry messages since we just use dicts
|
||||
continue
|
||||
|
||||
data.update(
|
||||
{
|
||||
"type": "Message",
|
||||
"comment": get_comment(proto_file, path),
|
||||
"properties": [],
|
||||
}
|
||||
)
|
||||
|
||||
for i, f in enumerate(item.field):
|
||||
t = py_type(package, output["imports"], f)
|
||||
zero = get_py_zero(f.type)
|
||||
|
||||
repeated = False
|
||||
packed = False
|
||||
|
||||
field_type = f.Type.Name(f.type).lower()[5:]
|
||||
|
||||
field_wraps = ""
|
||||
match_wrapper = re.match(
|
||||
r"\.google\.protobuf\.(.+)Value", f.type_name
|
||||
)
|
||||
if match_wrapper:
|
||||
wrapped_type = "TYPE_" + match_wrapper.group(1).upper()
|
||||
if hasattr(betterproto, wrapped_type):
|
||||
field_wraps = f"betterproto.{wrapped_type}"
|
||||
|
||||
map_types = None
|
||||
if f.type == 11:
|
||||
# This might be a map...
|
||||
message_type = f.type_name.split(".").pop().lower()
|
||||
# message_type = py_type(package)
|
||||
map_entry = f"{f.name.replace('_', '').lower()}entry"
|
||||
|
||||
if message_type == map_entry:
|
||||
for nested in item.nested_type:
|
||||
if (
|
||||
nested.name.replace("_", "").lower()
|
||||
== map_entry
|
||||
):
|
||||
if nested.options.map_entry:
|
||||
# print("Found a map!", file=sys.stderr)
|
||||
k = py_type(
|
||||
package,
|
||||
output["imports"],
|
||||
nested.field[0],
|
||||
)
|
||||
v = py_type(
|
||||
package,
|
||||
output["imports"],
|
||||
nested.field[1],
|
||||
)
|
||||
t = f"Dict[{k}, {v}]"
|
||||
field_type = "map"
|
||||
map_types = (
|
||||
f.Type.Name(nested.field[0].type),
|
||||
f.Type.Name(nested.field[1].type),
|
||||
)
|
||||
output["typing_imports"].add("Dict")
|
||||
|
||||
if f.label == 3 and field_type != "map":
|
||||
# Repeated field
|
||||
repeated = True
|
||||
t = f"List[{t}]"
|
||||
zero = "[]"
|
||||
output["typing_imports"].add("List")
|
||||
|
||||
if f.type in [1, 2, 3, 4, 5, 6, 7, 8, 13, 15, 16, 17, 18]:
|
||||
packed = True
|
||||
|
||||
one_of = ""
|
||||
if f.HasField("oneof_index"):
|
||||
one_of = item.oneof_decl[f.oneof_index].name
|
||||
|
||||
if "Optional[" in t:
|
||||
output["typing_imports"].add("Optional")
|
||||
|
||||
if "timedelta" in t:
|
||||
output["datetime_imports"].add("timedelta")
|
||||
elif "datetime" in t:
|
||||
output["datetime_imports"].add("datetime")
|
||||
|
||||
data["properties"].append(
|
||||
{
|
||||
"name": f.name,
|
||||
"py_name": pythonize_field_name(f.name),
|
||||
"number": f.number,
|
||||
"comment": get_comment(proto_file, path + [2, i]),
|
||||
"proto_type": int(f.type),
|
||||
"field_type": field_type,
|
||||
"field_wraps": field_wraps,
|
||||
"map_types": map_types,
|
||||
"type": t,
|
||||
"zero": zero,
|
||||
"repeated": repeated,
|
||||
"packed": packed,
|
||||
"one_of": one_of,
|
||||
}
|
||||
)
|
||||
# print(f, file=sys.stderr)
|
||||
|
||||
output["messages"].append(data)
|
||||
elif isinstance(item, EnumDescriptorProto):
|
||||
# print(item.name, path, file=sys.stderr)
|
||||
data.update(
|
||||
{
|
||||
"type": "Enum",
|
||||
"comment": get_comment(proto_file, path),
|
||||
"entries": [
|
||||
{
|
||||
"name": v.name,
|
||||
"value": v.number,
|
||||
"comment": get_comment(proto_file, path + [2, i]),
|
||||
}
|
||||
for i, v in enumerate(item.value)
|
||||
],
|
||||
}
|
||||
)
|
||||
|
||||
output["enums"].append(data)
|
||||
|
||||
for i, service in enumerate(proto_file.service):
|
||||
# print(service, file=sys.stderr)
|
||||
|
||||
data = {
|
||||
"name": service.name,
|
||||
"py_name": pythonize_class_name(service.name),
|
||||
"comment": get_comment(proto_file, [6, i]),
|
||||
"methods": [],
|
||||
}
|
||||
|
||||
for j, method in enumerate(service.method):
|
||||
input_message = None
|
||||
input_type = get_type_reference(
|
||||
package, output["imports"], method.input_type
|
||||
).strip('"')
|
||||
for msg in output["messages"]:
|
||||
if msg["name"] == input_type:
|
||||
input_message = msg
|
||||
for field in msg["properties"]:
|
||||
if field["zero"] == "None":
|
||||
output["typing_imports"].add("Optional")
|
||||
break
|
||||
|
||||
data["methods"].append(
|
||||
{
|
||||
"name": method.name,
|
||||
"py_name": pythonize_method_name(method.name),
|
||||
"comment": get_comment(proto_file, [6, i, 2, j], indent=8),
|
||||
"route": f"/{package}.{service.name}/{method.name}",
|
||||
"input": get_type_reference(
|
||||
package, output["imports"], method.input_type
|
||||
).strip('"'),
|
||||
"input_message": input_message,
|
||||
"output": get_type_reference(
|
||||
package,
|
||||
output["imports"],
|
||||
method.output_type,
|
||||
unwrap=False,
|
||||
).strip('"'),
|
||||
"client_streaming": method.client_streaming,
|
||||
"server_streaming": method.server_streaming,
|
||||
}
|
||||
)
|
||||
|
||||
if method.client_streaming:
|
||||
output["typing_imports"].add("AsyncIterable")
|
||||
output["typing_imports"].add("Iterable")
|
||||
output["typing_imports"].add("Union")
|
||||
if method.server_streaming:
|
||||
output["typing_imports"].add("AsyncIterator")
|
||||
|
||||
output["services"].append(data)
|
||||
|
||||
output["imports"] = sorted(output["imports"])
|
||||
output["datetime_imports"] = sorted(output["datetime_imports"])
|
||||
output["typing_imports"] = sorted(output["typing_imports"])
|
||||
|
||||
# Fill response
|
||||
f = response.file.add()
|
||||
f.name = filename
|
||||
|
||||
# Render and then format the output file.
|
||||
f.content = black.format_str(
|
||||
template.render(description=output),
|
||||
mode=black.FileMode(target_versions=set([black.TargetVersion.PY37])),
|
||||
)
|
||||
|
||||
# Make each output directory a package with __init__ file
|
||||
output_paths = set(pathlib.Path(path) for path in output_map.keys())
|
||||
init_files = (
|
||||
set(
|
||||
directory.joinpath("__init__.py")
|
||||
for path in output_paths
|
||||
for directory in path.parents
|
||||
)
|
||||
- output_paths
|
||||
)
|
||||
|
||||
for init_file in init_files:
|
||||
init = response.file.add()
|
||||
init.name = str(init_file)
|
||||
|
||||
for filename in sorted(output_paths.union(init_files)):
|
||||
print(f"Writing {filename}", file=sys.stderr)
|
||||
|
||||
|
||||
def main():
|
||||
"""The plugin's main entry point."""
|
||||
# Read request message from stdin
|
||||
data = sys.stdin.buffer.read()
|
||||
|
||||
# Parse request
|
||||
request = plugin.CodeGeneratorRequest()
|
||||
request.ParseFromString(data)
|
||||
|
||||
# Create response
|
||||
response = plugin.CodeGeneratorResponse()
|
||||
|
||||
# Generate code
|
||||
generate_code(request, response)
|
||||
|
||||
# Serialise response message
|
||||
output = response.SerializeToString()
|
||||
|
||||
# Write to stdout
|
||||
sys.stdout.buffer.write(output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,135 +0,0 @@
|
||||
# Generated by the protocol buffer compiler. DO NOT EDIT!
|
||||
# sources: {{ ', '.join(description.files) }}
|
||||
# plugin: python-betterproto
|
||||
from dataclasses import dataclass
|
||||
{% if description.datetime_imports %}
|
||||
from datetime import {% for i in description.datetime_imports %}{{ i }}{% if not loop.last %}, {% endif %}{% endfor %}
|
||||
|
||||
{% endif%}
|
||||
{% if description.typing_imports %}
|
||||
from typing import {% for i in description.typing_imports %}{{ i }}{% if not loop.last %}, {% endif %}{% endfor %}
|
||||
|
||||
{% endif %}
|
||||
|
||||
import betterproto
|
||||
{% if description.services %}
|
||||
import grpclib
|
||||
{% endif %}
|
||||
|
||||
{% for i in description.imports %}
|
||||
{{ i }}
|
||||
{% endfor %}
|
||||
|
||||
|
||||
{% if description.enums %}{% for enum in description.enums %}
|
||||
class {{ enum.py_name }}(betterproto.Enum):
|
||||
{% if enum.comment %}
|
||||
{{ enum.comment }}
|
||||
|
||||
{% endif %}
|
||||
{% for entry in enum.entries %}
|
||||
{% if entry.comment %}
|
||||
{{ entry.comment }}
|
||||
{% endif %}
|
||||
{{ entry.name }} = {{ entry.value }}
|
||||
{% endfor %}
|
||||
|
||||
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% for message in description.messages %}
|
||||
@dataclass
|
||||
class {{ message.py_name }}(betterproto.Message):
|
||||
{% if message.comment %}
|
||||
{{ message.comment }}
|
||||
|
||||
{% endif %}
|
||||
{% for field in message.properties %}
|
||||
{% if field.comment %}
|
||||
{{ field.comment }}
|
||||
{% endif %}
|
||||
{{ field.py_name }}: {{ field.type }} = betterproto.{{ field.field_type }}_field({{ field.number }}{% if field.field_type == 'map'%}, betterproto.{{ field.map_types[0] }}, betterproto.{{ field.map_types[1] }}{% endif %}{% if field.one_of %}, group="{{ field.one_of }}"{% endif %}{% if field.field_wraps %}, wraps={{ field.field_wraps }}{% endif %})
|
||||
{% endfor %}
|
||||
{% if not message.properties %}
|
||||
pass
|
||||
{% endif %}
|
||||
|
||||
|
||||
{% endfor %}
|
||||
{% for service in description.services %}
|
||||
class {{ service.py_name }}Stub(betterproto.ServiceStub):
|
||||
{% if service.comment %}
|
||||
{{ service.comment }}
|
||||
|
||||
{% endif %}
|
||||
{% for method in service.methods %}
|
||||
async def {{ method.py_name }}(self
|
||||
{%- if not method.client_streaming -%}
|
||||
{%- if method.input_message and method.input_message.properties -%}, *,
|
||||
{%- for field in method.input_message.properties -%}
|
||||
{{ field.py_name }}: {% if field.zero == "None" and not field.type.startswith("Optional[") -%}
|
||||
Optional[{{ field.type }}]
|
||||
{%- else -%}
|
||||
{{ field.type }}
|
||||
{%- endif -%} = {{ field.zero }}
|
||||
{%- if not loop.last %}, {% endif -%}
|
||||
{%- endfor -%}
|
||||
{%- endif -%}
|
||||
{%- else -%}
|
||||
{# Client streaming: need a request iterator instead #}
|
||||
, request_iterator: Union[AsyncIterable["{{ method.input }}"], Iterable["{{ method.input }}"]]
|
||||
{%- endif -%}
|
||||
) -> {% if method.server_streaming %}AsyncIterator[{{ method.output }}]{% else %}{{ method.output }}{% endif %}:
|
||||
{% if method.comment %}
|
||||
{{ method.comment }}
|
||||
|
||||
{% endif %}
|
||||
{% if not method.client_streaming %}
|
||||
request = {{ method.input }}()
|
||||
{% for field in method.input_message.properties %}
|
||||
{% if field.field_type == 'message' %}
|
||||
if {{ field.py_name }} is not None:
|
||||
request.{{ field.py_name }} = {{ field.py_name }}
|
||||
{% else %}
|
||||
request.{{ field.py_name }} = {{ field.py_name }}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
{% if method.server_streaming %}
|
||||
{% if method.client_streaming %}
|
||||
async for response in self._stream_stream(
|
||||
"{{ method.route }}",
|
||||
request_iterator,
|
||||
{{ method.input }},
|
||||
{{ method.output }},
|
||||
):
|
||||
yield response
|
||||
{% else %}{# i.e. not client streaming #}
|
||||
async for response in self._unary_stream(
|
||||
"{{ method.route }}",
|
||||
request,
|
||||
{{ method.output }},
|
||||
):
|
||||
yield response
|
||||
|
||||
{% endif %}{# if client streaming #}
|
||||
{% else %}{# i.e. not server streaming #}
|
||||
{% if method.client_streaming %}
|
||||
return await self._stream_unary(
|
||||
"{{ method.route }}",
|
||||
request_iterator,
|
||||
{{ method.input }},
|
||||
{{ method.output }}
|
||||
)
|
||||
{% else %}{# i.e. not client streaming #}
|
||||
return await self._unary_unary(
|
||||
"{{ method.route }}",
|
||||
request,
|
||||
{{ method.output }}
|
||||
)
|
||||
{% endif %}{# client streaming #}
|
||||
{% endif %}
|
||||
|
||||
{% endfor %}
|
||||
{% endfor %}
|
||||
@@ -1,154 +0,0 @@
|
||||
import asyncio
|
||||
from betterproto.tests.output_betterproto.service.service import (
|
||||
DoThingResponse,
|
||||
DoThingRequest,
|
||||
GetThingRequest,
|
||||
GetThingResponse,
|
||||
TestStub as ThingServiceClient,
|
||||
)
|
||||
import grpclib
|
||||
from grpclib.testing import ChannelFor
|
||||
import pytest
|
||||
from betterproto.grpc.util.async_channel import AsyncChannel
|
||||
from .thing_service import ThingService
|
||||
|
||||
|
||||
async def _test_client(client, name="clean room", **kwargs):
|
||||
response = await client.do_thing(name=name)
|
||||
assert response.names == [name]
|
||||
|
||||
|
||||
def _assert_request_meta_recieved(deadline, metadata):
|
||||
def server_side_test(stream):
|
||||
assert stream.deadline._timestamp == pytest.approx(
|
||||
deadline._timestamp, 1
|
||||
), "The provided deadline should be recieved serverside"
|
||||
assert (
|
||||
stream.metadata["authorization"] == metadata["authorization"]
|
||||
), "The provided authorization metadata should be recieved serverside"
|
||||
|
||||
return server_side_test
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_simple_service_call():
|
||||
async with ChannelFor([ThingService()]) as channel:
|
||||
await _test_client(ThingServiceClient(channel))
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_service_call_with_upfront_request_params():
|
||||
# Setting deadline
|
||||
deadline = grpclib.metadata.Deadline.from_timeout(22)
|
||||
metadata = {"authorization": "12345"}
|
||||
async with ChannelFor(
|
||||
[ThingService(test_hook=_assert_request_meta_recieved(deadline, metadata),)]
|
||||
) as channel:
|
||||
await _test_client(
|
||||
ThingServiceClient(channel, deadline=deadline, metadata=metadata)
|
||||
)
|
||||
|
||||
# Setting timeout
|
||||
timeout = 99
|
||||
deadline = grpclib.metadata.Deadline.from_timeout(timeout)
|
||||
metadata = {"authorization": "12345"}
|
||||
async with ChannelFor(
|
||||
[ThingService(test_hook=_assert_request_meta_recieved(deadline, metadata),)]
|
||||
) as channel:
|
||||
await _test_client(
|
||||
ThingServiceClient(channel, timeout=timeout, metadata=metadata)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_service_call_lower_level_with_overrides():
|
||||
THING_TO_DO = "get milk"
|
||||
|
||||
# Setting deadline
|
||||
deadline = grpclib.metadata.Deadline.from_timeout(22)
|
||||
metadata = {"authorization": "12345"}
|
||||
kwarg_deadline = grpclib.metadata.Deadline.from_timeout(28)
|
||||
kwarg_metadata = {"authorization": "12345"}
|
||||
async with ChannelFor(
|
||||
[ThingService(test_hook=_assert_request_meta_recieved(deadline, metadata),)]
|
||||
) as channel:
|
||||
client = ThingServiceClient(channel, deadline=deadline, metadata=metadata)
|
||||
response = await client._unary_unary(
|
||||
"/service.Test/DoThing",
|
||||
DoThingRequest(THING_TO_DO),
|
||||
DoThingResponse,
|
||||
deadline=kwarg_deadline,
|
||||
metadata=kwarg_metadata,
|
||||
)
|
||||
assert response.names == [THING_TO_DO]
|
||||
|
||||
# Setting timeout
|
||||
timeout = 99
|
||||
deadline = grpclib.metadata.Deadline.from_timeout(timeout)
|
||||
metadata = {"authorization": "12345"}
|
||||
kwarg_timeout = 9000
|
||||
kwarg_deadline = grpclib.metadata.Deadline.from_timeout(kwarg_timeout)
|
||||
kwarg_metadata = {"authorization": "09876"}
|
||||
async with ChannelFor(
|
||||
[
|
||||
ThingService(
|
||||
test_hook=_assert_request_meta_recieved(kwarg_deadline, kwarg_metadata),
|
||||
)
|
||||
]
|
||||
) as channel:
|
||||
client = ThingServiceClient(channel, deadline=deadline, metadata=metadata)
|
||||
response = await client._unary_unary(
|
||||
"/service.Test/DoThing",
|
||||
DoThingRequest(THING_TO_DO),
|
||||
DoThingResponse,
|
||||
timeout=kwarg_timeout,
|
||||
metadata=kwarg_metadata,
|
||||
)
|
||||
assert response.names == [THING_TO_DO]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_gen_for_unary_stream_request():
|
||||
thing_name = "my milkshakes"
|
||||
|
||||
async with ChannelFor([ThingService()]) as channel:
|
||||
client = ThingServiceClient(channel)
|
||||
expected_versions = [5, 4, 3, 2, 1]
|
||||
async for response in client.get_thing_versions(name=thing_name):
|
||||
assert response.name == thing_name
|
||||
assert response.version == expected_versions.pop()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_gen_for_stream_stream_request():
|
||||
some_things = ["cake", "cricket", "coral reef"]
|
||||
more_things = ["ball", "that", "56kmodem", "liberal humanism", "cheesesticks"]
|
||||
expected_things = (*some_things, *more_things)
|
||||
|
||||
async with ChannelFor([ThingService()]) as channel:
|
||||
client = ThingServiceClient(channel)
|
||||
# Use an AsyncChannel to decouple sending and recieving, it'll send some_things
|
||||
# immediately and we'll use it to send more_things later, after recieving some
|
||||
# results
|
||||
request_chan = AsyncChannel()
|
||||
send_initial_requests = asyncio.ensure_future(
|
||||
request_chan.send_from(GetThingRequest(name) for name in some_things)
|
||||
)
|
||||
response_index = 0
|
||||
async for response in client.get_different_things(request_chan):
|
||||
assert response.name == expected_things[response_index]
|
||||
assert response.version == response_index + 1
|
||||
response_index += 1
|
||||
if more_things:
|
||||
# Send some more requests as we recieve reponses to be sure coordination of
|
||||
# send/recieve events doesn't matter
|
||||
await request_chan.send(GetThingRequest(more_things.pop(0)))
|
||||
elif not send_initial_requests.done():
|
||||
# Make sure the sending task it completed
|
||||
await send_initial_requests
|
||||
else:
|
||||
# No more things to send make sure channel is closed
|
||||
request_chan.close()
|
||||
assert response_index == len(
|
||||
expected_things
|
||||
), "Didn't recieve all exptected responses"
|
||||
@@ -1,6 +0,0 @@
|
||||
from betterproto.tests.output_betterproto.bool import Test
|
||||
|
||||
|
||||
def test_value():
|
||||
message = Test()
|
||||
assert not message.value, "Boolean is False by default"
|
||||
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"greeting": "HEY"
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
syntax = "proto3";
|
||||
|
||||
// Enum for the different greeting types
|
||||
enum Greeting {
|
||||
HI = 0;
|
||||
HEY = 1;
|
||||
// Formal greeting
|
||||
HELLO = 2;
|
||||
}
|
||||
|
||||
message Test {
|
||||
// Greeting enum example
|
||||
Greeting greeting = 1;
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package hello;
|
||||
|
||||
// Greeting represents a message you can tell a user.
|
||||
message Greeting {
|
||||
string message = 1;
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
syntax = "proto3";
|
||||
|
||||
|
||||
package Capitalized;
|
||||
|
||||
message Message {
|
||||
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package package.childpackage;
|
||||
|
||||
message ChildMessage {
|
||||
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package childpackage;
|
||||
|
||||
message Message {
|
||||
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package cousin.cousin_subpackage;
|
||||
|
||||
message CousinMessage {
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package cousin.subpackage;
|
||||
|
||||
message CousinMessage {
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package posts.v1;
|
||||
|
||||
message Post {
|
||||
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package users.v1;
|
||||
|
||||
message User {
|
||||
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
syntax = "proto3";
|
||||
|
||||
import "request_message.proto";
|
||||
|
||||
// Tests generated service correctly imports the RequestMessage
|
||||
|
||||
service Test {
|
||||
rpc DoThing (RequestMessage) returns (RequestResponse);
|
||||
}
|
||||
|
||||
|
||||
message RequestResponse {
|
||||
int32 value = 1;
|
||||
}
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import pytest
|
||||
|
||||
from betterproto.tests.mocks import MockChannel
|
||||
from betterproto.tests.output_betterproto.import_service_input_message import (
|
||||
RequestResponse,
|
||||
TestStub,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.xfail(reason="#68 Request Input Messages are not imported for service")
|
||||
@pytest.mark.asyncio
|
||||
async def test_service_correctly_imports_reference_message():
|
||||
mock_response = RequestResponse(value=10)
|
||||
service = TestStub(MockChannel([mock_response]))
|
||||
response = await service.do_thing()
|
||||
assert mock_response == response
|
||||
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"name": "foobar"
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"count": 100
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
syntax = "proto3";
|
||||
|
||||
message Test {
|
||||
oneof foo {
|
||||
int32 count = 1;
|
||||
string name = 2;
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
import betterproto
|
||||
from betterproto.tests.output_betterproto.oneof import Test
|
||||
from betterproto.tests.util import get_test_case_json_data
|
||||
|
||||
|
||||
def test_which_count():
|
||||
message = Test()
|
||||
message.from_json(get_test_case_json_data("oneof"))
|
||||
assert betterproto.which_one_of(message, "foo") == ("count", 100)
|
||||
|
||||
|
||||
def test_which_name():
|
||||
message = Test()
|
||||
message.from_json(get_test_case_json_data("oneof", "oneof-name.json"))
|
||||
assert betterproto.which_one_of(message, "foo") == ("name", "foobar")
|
||||
@@ -1,265 +0,0 @@
|
||||
import betterproto
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
|
||||
def test_has_field():
|
||||
@dataclass
|
||||
class Bar(betterproto.Message):
|
||||
baz: int = betterproto.int32_field(1)
|
||||
|
||||
@dataclass
|
||||
class Foo(betterproto.Message):
|
||||
bar: Bar = betterproto.message_field(1)
|
||||
|
||||
# Unset by default
|
||||
foo = Foo()
|
||||
assert betterproto.serialized_on_wire(foo.bar) == False
|
||||
|
||||
# Serialized after setting something
|
||||
foo.bar.baz = 1
|
||||
assert betterproto.serialized_on_wire(foo.bar) == True
|
||||
|
||||
# Still has it after setting the default value
|
||||
foo.bar.baz = 0
|
||||
assert betterproto.serialized_on_wire(foo.bar) == True
|
||||
|
||||
# Manual override (don't do this)
|
||||
foo.bar._serialized_on_wire = False
|
||||
assert betterproto.serialized_on_wire(foo.bar) == False
|
||||
|
||||
# Can manually set it but defaults to false
|
||||
foo.bar = Bar()
|
||||
assert betterproto.serialized_on_wire(foo.bar) == False
|
||||
|
||||
|
||||
def test_class_init():
|
||||
@dataclass
|
||||
class Bar(betterproto.Message):
|
||||
name: str = betterproto.string_field(1)
|
||||
|
||||
@dataclass
|
||||
class Foo(betterproto.Message):
|
||||
name: str = betterproto.string_field(1)
|
||||
child: Bar = betterproto.message_field(2)
|
||||
|
||||
foo = Foo(name="foo", child=Bar(name="bar"))
|
||||
|
||||
assert foo.to_dict() == {"name": "foo", "child": {"name": "bar"}}
|
||||
|
||||
|
||||
def test_enum_as_int_json():
|
||||
class TestEnum(betterproto.Enum):
|
||||
ZERO = 0
|
||||
ONE = 1
|
||||
|
||||
@dataclass
|
||||
class Foo(betterproto.Message):
|
||||
bar: TestEnum = betterproto.enum_field(1)
|
||||
|
||||
# JSON strings are supported, but ints should still be supported too.
|
||||
foo = Foo().from_dict({"bar": 1})
|
||||
assert foo.bar == TestEnum.ONE
|
||||
|
||||
# Plain-ol'-ints should serialize properly too.
|
||||
foo.bar = 1
|
||||
assert foo.to_dict() == {"bar": "ONE"}
|
||||
|
||||
|
||||
def test_unknown_fields():
|
||||
@dataclass
|
||||
class Newer(betterproto.Message):
|
||||
foo: bool = betterproto.bool_field(1)
|
||||
bar: int = betterproto.int32_field(2)
|
||||
baz: str = betterproto.string_field(3)
|
||||
|
||||
@dataclass
|
||||
class Older(betterproto.Message):
|
||||
foo: bool = betterproto.bool_field(1)
|
||||
|
||||
newer = Newer(foo=True, bar=1, baz="Hello")
|
||||
serialized_newer = bytes(newer)
|
||||
|
||||
# Unknown fields in `Newer` should round trip with `Older`
|
||||
round_trip = bytes(Older().parse(serialized_newer))
|
||||
assert serialized_newer == round_trip
|
||||
|
||||
new_again = Newer().parse(round_trip)
|
||||
assert newer == new_again
|
||||
|
||||
|
||||
def test_oneof_support():
|
||||
@dataclass
|
||||
class Sub(betterproto.Message):
|
||||
val: int = betterproto.int32_field(1)
|
||||
|
||||
@dataclass
|
||||
class Foo(betterproto.Message):
|
||||
bar: int = betterproto.int32_field(1, group="group1")
|
||||
baz: str = betterproto.string_field(2, group="group1")
|
||||
sub: Sub = betterproto.message_field(3, group="group2")
|
||||
abc: str = betterproto.string_field(4, group="group2")
|
||||
|
||||
foo = Foo()
|
||||
|
||||
assert betterproto.which_one_of(foo, "group1")[0] == ""
|
||||
|
||||
foo.bar = 1
|
||||
foo.baz = "test"
|
||||
|
||||
# Other oneof fields should now be unset
|
||||
assert foo.bar == 0
|
||||
assert betterproto.which_one_of(foo, "group1")[0] == "baz"
|
||||
|
||||
foo.sub.val = 1
|
||||
assert betterproto.serialized_on_wire(foo.sub)
|
||||
|
||||
foo.abc = "test"
|
||||
|
||||
# Group 1 shouldn't be touched, group 2 should have reset
|
||||
assert foo.sub.val == 0
|
||||
assert betterproto.serialized_on_wire(foo.sub) == False
|
||||
assert betterproto.which_one_of(foo, "group2")[0] == "abc"
|
||||
|
||||
# Zero value should always serialize for one-of
|
||||
foo = Foo(bar=0)
|
||||
assert betterproto.which_one_of(foo, "group1")[0] == "bar"
|
||||
assert bytes(foo) == b"\x08\x00"
|
||||
|
||||
# Round trip should also work
|
||||
foo2 = Foo().parse(bytes(foo))
|
||||
assert betterproto.which_one_of(foo2, "group1")[0] == "bar"
|
||||
assert foo.bar == 0
|
||||
assert betterproto.which_one_of(foo2, "group2")[0] == ""
|
||||
|
||||
|
||||
def test_json_casing():
|
||||
@dataclass
|
||||
class CasingTest(betterproto.Message):
|
||||
pascal_case: int = betterproto.int32_field(1)
|
||||
camel_case: int = betterproto.int32_field(2)
|
||||
snake_case: int = betterproto.int32_field(3)
|
||||
kabob_case: int = betterproto.int32_field(4)
|
||||
|
||||
# Parsing should accept almost any input
|
||||
test = CasingTest().from_dict(
|
||||
{"PascalCase": 1, "camelCase": 2, "snake_case": 3, "kabob-case": 4}
|
||||
)
|
||||
|
||||
assert test == CasingTest(1, 2, 3, 4)
|
||||
|
||||
# Serializing should be strict.
|
||||
assert test.to_dict() == {
|
||||
"pascalCase": 1,
|
||||
"camelCase": 2,
|
||||
"snakeCase": 3,
|
||||
"kabobCase": 4,
|
||||
}
|
||||
|
||||
assert test.to_dict(casing=betterproto.Casing.SNAKE) == {
|
||||
"pascal_case": 1,
|
||||
"camel_case": 2,
|
||||
"snake_case": 3,
|
||||
"kabob_case": 4,
|
||||
}
|
||||
|
||||
|
||||
def test_optional_flag():
|
||||
@dataclass
|
||||
class Request(betterproto.Message):
|
||||
flag: Optional[bool] = betterproto.message_field(1, wraps=betterproto.TYPE_BOOL)
|
||||
|
||||
# Serialization of not passed vs. set vs. zero-value.
|
||||
assert bytes(Request()) == b""
|
||||
assert bytes(Request(flag=True)) == b"\n\x02\x08\x01"
|
||||
assert bytes(Request(flag=False)) == b"\n\x00"
|
||||
|
||||
# Differentiate between not passed and the zero-value.
|
||||
assert Request().parse(b"").flag == None
|
||||
assert Request().parse(b"\n\x00").flag == False
|
||||
|
||||
|
||||
def test_to_dict_default_values():
|
||||
@dataclass
|
||||
class TestMessage(betterproto.Message):
|
||||
some_int: int = betterproto.int32_field(1)
|
||||
some_double: float = betterproto.double_field(2)
|
||||
some_str: str = betterproto.string_field(3)
|
||||
some_bool: bool = betterproto.bool_field(4)
|
||||
|
||||
# Empty dict
|
||||
test = TestMessage().from_dict({})
|
||||
|
||||
assert test.to_dict(include_default_values=True) == {
|
||||
"someInt": 0,
|
||||
"someDouble": 0.0,
|
||||
"someStr": "",
|
||||
"someBool": False,
|
||||
}
|
||||
|
||||
# All default values
|
||||
test = TestMessage().from_dict(
|
||||
{"someInt": 0, "someDouble": 0.0, "someStr": "", "someBool": False}
|
||||
)
|
||||
|
||||
assert test.to_dict(include_default_values=True) == {
|
||||
"someInt": 0,
|
||||
"someDouble": 0.0,
|
||||
"someStr": "",
|
||||
"someBool": False,
|
||||
}
|
||||
|
||||
# Some default and some other values
|
||||
@dataclass
|
||||
class TestMessage2(betterproto.Message):
|
||||
some_int: int = betterproto.int32_field(1)
|
||||
some_double: float = betterproto.double_field(2)
|
||||
some_str: str = betterproto.string_field(3)
|
||||
some_bool: bool = betterproto.bool_field(4)
|
||||
some_default_int: int = betterproto.int32_field(5)
|
||||
some_default_double: float = betterproto.double_field(6)
|
||||
some_default_str: str = betterproto.string_field(7)
|
||||
some_default_bool: bool = betterproto.bool_field(8)
|
||||
|
||||
test = TestMessage2().from_dict(
|
||||
{
|
||||
"someInt": 2,
|
||||
"someDouble": 1.2,
|
||||
"someStr": "hello",
|
||||
"someBool": True,
|
||||
"someDefaultInt": 0,
|
||||
"someDefaultDouble": 0.0,
|
||||
"someDefaultStr": "",
|
||||
"someDefaultBool": False,
|
||||
}
|
||||
)
|
||||
|
||||
assert test.to_dict(include_default_values=True) == {
|
||||
"someInt": 2,
|
||||
"someDouble": 1.2,
|
||||
"someStr": "hello",
|
||||
"someBool": True,
|
||||
"someDefaultInt": 0,
|
||||
"someDefaultDouble": 0.0,
|
||||
"someDefaultStr": "",
|
||||
"someDefaultBool": False,
|
||||
}
|
||||
|
||||
# Nested messages
|
||||
@dataclass
|
||||
class TestChildMessage(betterproto.Message):
|
||||
some_other_int: int = betterproto.int32_field(1)
|
||||
|
||||
@dataclass
|
||||
class TestParentMessage(betterproto.Message):
|
||||
some_int: int = betterproto.int32_field(1)
|
||||
some_double: float = betterproto.double_field(2)
|
||||
some_message: TestChildMessage = betterproto.message_field(3)
|
||||
|
||||
test = TestParentMessage().from_dict({"someInt": 0, "someDouble": 1.2})
|
||||
|
||||
assert test.to_dict(include_default_values=True) == {
|
||||
"someInt": 0,
|
||||
"someDouble": 1.2,
|
||||
"someMessage": {"someOtherInt": 0},
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
import asyncio
|
||||
import importlib
|
||||
import os
|
||||
import pathlib
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
from typing import Callable, Generator, Optional
|
||||
|
||||
os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python"
|
||||
|
||||
root_path = Path(__file__).resolve().parent
|
||||
inputs_path = root_path.joinpath("inputs")
|
||||
output_path_reference = root_path.joinpath("output_reference")
|
||||
output_path_betterproto = root_path.joinpath("output_betterproto")
|
||||
|
||||
if os.name == "nt":
|
||||
plugin_path = root_path.joinpath("..", "plugin.bat").resolve()
|
||||
else:
|
||||
plugin_path = root_path.joinpath("..", "plugin.py").resolve()
|
||||
|
||||
|
||||
def get_files(path, suffix: str) -> Generator[str, None, None]:
|
||||
for r, dirs, files in os.walk(path):
|
||||
for filename in [f for f in files if f.endswith(suffix)]:
|
||||
yield os.path.join(r, filename)
|
||||
|
||||
|
||||
def get_directories(path):
|
||||
for root, directories, files in os.walk(path):
|
||||
for directory in directories:
|
||||
yield directory
|
||||
|
||||
|
||||
async def protoc_plugin(path: str, output_dir: str):
|
||||
proc = await asyncio.create_subprocess_shell(
|
||||
f"protoc --plugin=protoc-gen-custom={plugin_path} --custom_out={output_dir} --proto_path={path} {path}/*.proto",
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
return (*(await proc.communicate()), proc.returncode)
|
||||
|
||||
|
||||
async def protoc_reference(path: str, output_dir: str):
|
||||
proc = await asyncio.create_subprocess_shell(
|
||||
f"protoc --python_out={output_dir} --proto_path={path} {path}/*.proto",
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
return (*(await proc.communicate()), proc.returncode)
|
||||
|
||||
|
||||
def get_test_case_json_data(test_case_name: str, json_file_name: Optional[str] = None):
|
||||
test_data_file_name = json_file_name if json_file_name else f"{test_case_name}.json"
|
||||
test_data_file_path = inputs_path.joinpath(test_case_name, test_data_file_name)
|
||||
|
||||
if not test_data_file_path.exists():
|
||||
return None
|
||||
|
||||
with test_data_file_path.open("r") as fh:
|
||||
return fh.read()
|
||||
|
||||
|
||||
def find_module(
|
||||
module: ModuleType, predicate: Callable[[ModuleType], bool]
|
||||
) -> Optional[ModuleType]:
|
||||
"""
|
||||
Recursively search module tree for a module that matches the search predicate.
|
||||
Assumes that the submodules are directories containing __init__.py.
|
||||
|
||||
Example:
|
||||
|
||||
# find module inside foo that contains Test
|
||||
import foo
|
||||
test_module = find_module(foo, lambda m: hasattr(m, 'Test'))
|
||||
"""
|
||||
if predicate(module):
|
||||
return module
|
||||
|
||||
module_path = pathlib.Path(*module.__path__)
|
||||
|
||||
for sub in list(sub.parent for sub in module_path.glob("**/__init__.py")):
|
||||
if sub == module_path:
|
||||
continue
|
||||
sub_module_path = sub.relative_to(module_path)
|
||||
sub_module_name = ".".join(sub_module_path.parts)
|
||||
|
||||
sub_module = importlib.import_module(f".{sub_module_name}", module.__name__)
|
||||
|
||||
if predicate(sub_module):
|
||||
return sub_module
|
||||
|
||||
return None
|
||||
31
docs/api.rst
Normal file
31
docs/api.rst
Normal file
@@ -0,0 +1,31 @@
|
||||
.. currentmodule:: betterproto
|
||||
|
||||
API reference
|
||||
=============
|
||||
|
||||
The following document outlines betterproto's api. **None** of these classes should be
|
||||
extended by the user manually.
|
||||
|
||||
|
||||
Message
|
||||
--------
|
||||
|
||||
.. autoclass:: betterproto.Message
|
||||
:members:
|
||||
:special-members: __bytes__, __bool__
|
||||
|
||||
|
||||
.. autofunction:: betterproto.serialized_on_wire
|
||||
|
||||
.. autofunction:: betterproto.which_one_of
|
||||
|
||||
|
||||
Enumerations
|
||||
-------------
|
||||
|
||||
.. autoclass:: betterproto.Enum()
|
||||
:members:
|
||||
|
||||
|
||||
.. autoclass:: betterproto.Casing()
|
||||
:members:
|
||||
60
docs/conf.py
Normal file
60
docs/conf.py
Normal file
@@ -0,0 +1,60 @@
|
||||
# Configuration file for the Sphinx documentation builder.
|
||||
#
|
||||
# This file only contains a selection of the most common options. For a full
|
||||
# list see the documentation:
|
||||
# https://www.sphinx-doc.org/en/master/usage/configuration.html
|
||||
|
||||
# If extensions (or modules to document with autodoc) are in another directory,
|
||||
# add these directories to sys.path here. If the directory is relative to the
|
||||
# documentation root, use os.path.abspath to make it absolute, like shown here.
|
||||
|
||||
import pathlib
|
||||
|
||||
import toml
|
||||
|
||||
|
||||
# -- Project information -----------------------------------------------------
|
||||
|
||||
project = "betterproto"
|
||||
copyright = "2019 Daniel G. Taylor"
|
||||
author = "danielgtaylor"
|
||||
pyproject = toml.load(open(pathlib.Path(__file__).parent.parent / "pyproject.toml"))
|
||||
|
||||
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = pyproject["tool"]["poetry"]["version"]
|
||||
|
||||
|
||||
# -- General configuration ---------------------------------------------------
|
||||
|
||||
# Add any Sphinx extension module names here, as strings. They can be
|
||||
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
|
||||
# ones.
|
||||
extensions = [
|
||||
"sphinx.ext.autodoc",
|
||||
"sphinx.ext.intersphinx",
|
||||
"sphinx.ext.napoleon",
|
||||
]
|
||||
|
||||
autodoc_member_order = "bysource"
|
||||
autodoc_typehints = "none"
|
||||
|
||||
extlinks = {
|
||||
"issue": ("https://github.com/danielgtaylor/python-betterproto/issues/%s", "GH-"),
|
||||
}
|
||||
|
||||
# Links used for cross-referencing stuff in other documentation
|
||||
intersphinx_mapping = {
|
||||
"py": ("https://docs.python.org/3", None),
|
||||
}
|
||||
|
||||
|
||||
# -- Options for HTML output -------------------------------------------------
|
||||
|
||||
# The name of the Pygments (syntax highlighting) style to use.
|
||||
pygments_style = "friendly"
|
||||
|
||||
# The theme to use for HTML and HTML Help pages. See the documentation for
|
||||
# a list of builtin themes.
|
||||
|
||||
html_theme = "sphinx_rtd_theme"
|
||||
33
docs/index.rst
Normal file
33
docs/index.rst
Normal file
@@ -0,0 +1,33 @@
|
||||
Welcome to betterproto's documentation!
|
||||
=======================================
|
||||
|
||||
betterproto is a protobuf compiler and interpreter. It improves the experience of using
|
||||
Protobuf and gRPC in Python, by generating readable, understandable, and idiomatic
|
||||
Python code, using modern language features.
|
||||
|
||||
|
||||
Features:
|
||||
~~~~~~~~~
|
||||
|
||||
- Generated messages are both binary & JSON serializable
|
||||
- Messages use relevant python types, e.g. ``Enum``, ``datetime`` and ``timedelta``
|
||||
objects
|
||||
- ``async``/``await`` support for gRPC Clients and Servers
|
||||
- Generates modern, readable, idiomatic python code
|
||||
|
||||
Contents:
|
||||
~~~~~~~~~
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
|
||||
quick-start
|
||||
api
|
||||
migrating
|
||||
|
||||
|
||||
If you still can't find what you're looking for, try in one of the following pages:
|
||||
|
||||
* :ref:`genindex`
|
||||
* :ref:`modindex`
|
||||
* :ref:`search`
|
||||
157
docs/migrating.rst
Normal file
157
docs/migrating.rst
Normal file
@@ -0,0 +1,157 @@
|
||||
Migrating Guide
|
||||
===============
|
||||
|
||||
Google's protocolbuffers
|
||||
------------------------
|
||||
|
||||
betterproto has a mostly 1 to 1 drop in replacement for Google's protocolbuffers (after
|
||||
regenerating your protobufs of course) although there are some minor differences.
|
||||
|
||||
.. note::
|
||||
|
||||
betterproto implements the same basic methods including:
|
||||
|
||||
- :meth:`betterproto.Message.FromString`
|
||||
- :meth:`betterproto.Message.SerializeToString`
|
||||
|
||||
for compatibility purposes, however it is important to note that these are
|
||||
effectively aliases for :meth:`betterproto.Message.parse` and
|
||||
:meth:`betterproto.Message.__bytes__` respectively.
|
||||
|
||||
|
||||
Determining if a message was sent
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Sometimes it is useful to be able to determine whether a message has been sent on
|
||||
the wire. This is how the Google wrapper types work to let you know whether a value is
|
||||
unset (set as the default/zero value), or set as something else, for example.
|
||||
|
||||
Use ``betterproto.serialized_on_wire(message)`` to determine if it was sent. This is
|
||||
a little bit different from the official Google generated Python code, and it lives
|
||||
outside the generated ``Message`` class to prevent name clashes. Note that it only
|
||||
supports Proto 3 and thus can only be used to check if ``Message`` fields are set.
|
||||
You cannot check if a scalar was sent on the wire.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# Old way (official Google Protobuf package)
|
||||
>>> mymessage.HasField('myfield')
|
||||
True
|
||||
|
||||
# New way (this project)
|
||||
>>> betterproto.serialized_on_wire(mymessage.myfield)
|
||||
True
|
||||
|
||||
|
||||
One-of Support
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Protobuf supports grouping fields in a oneof clause. Only one of the fields in the group
|
||||
may be set at a given time. For example, given the proto:
|
||||
|
||||
.. code-block:: proto
|
||||
|
||||
syntax = "proto3";
|
||||
|
||||
message Test {
|
||||
oneof foo {
|
||||
bool on = 1;
|
||||
int32 count = 2;
|
||||
string name = 3;
|
||||
}
|
||||
}
|
||||
|
||||
You can use ``betterproto.which_one_of(message, group_name)`` to determine which of the
|
||||
fields was set. It returns a tuple of the field name and value, or a blank string and
|
||||
``None`` if unset. Again this is a little different than the official Google code
|
||||
generator:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# Old way (official Google protobuf package)
|
||||
>>> message.WhichOneof("group")
|
||||
"foo"
|
||||
|
||||
# New way (this project)
|
||||
>>> betterproto.which_one_of(message, "group")
|
||||
("foo", "foo's value")
|
||||
|
||||
|
||||
Well-Known Google Types
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Google provides several well-known message types like a timestamp, duration, and several
|
||||
wrappers used to provide optional zero value support. Each of these has a special JSON
|
||||
representation and is handled a little differently from normal messages. The Python
|
||||
mapping for these is as follows:
|
||||
|
||||
+-------------------------------+-----------------------------------------------+--------------------------+
|
||||
| ``Google Message`` | ``Python Type`` | ``Default`` |
|
||||
+===============================+===============================================+==========================+
|
||||
| ``google.protobuf.duration`` | :class:`datetime.timedelta` | ``0`` |
|
||||
+-------------------------------+-----------------------------------------------+--------------------------+
|
||||
| ``google.protobuf.timestamp`` | ``Timezone-aware`` :class:`datetime.datetime` | ``1970-01-01T00:00:00Z`` |
|
||||
+-------------------------------+-----------------------------------------------+--------------------------+
|
||||
| ``google.protobuf.*Value`` | ``Optional[...]``/``None`` | ``None`` |
|
||||
+-------------------------------+-----------------------------------------------+--------------------------+
|
||||
| ``google.protobuf.*`` | ``betterproto.lib.google.protobuf.*`` | ``None`` |
|
||||
+-------------------------------+-----------------------------------------------+--------------------------+
|
||||
|
||||
|
||||
For the wrapper types, the Python type corresponds to the wrapped type, e.g.
|
||||
``google.protobuf.BoolValue`` becomes ``Optional[bool]`` while
|
||||
``google.protobuf.Int32Value`` becomes ``Optional[int]``. All of the optional values
|
||||
default to None, so don't forget to check for that possible state.
|
||||
|
||||
Given:
|
||||
|
||||
.. code-block:: proto
|
||||
|
||||
syntax = "proto3";
|
||||
|
||||
import "google/protobuf/duration.proto";
|
||||
import "google/protobuf/timestamp.proto";
|
||||
import "google/protobuf/wrappers.proto";
|
||||
|
||||
message Test {
|
||||
google.protobuf.BoolValue maybe = 1;
|
||||
google.protobuf.Timestamp ts = 2;
|
||||
google.protobuf.Duration duration = 3;
|
||||
}
|
||||
|
||||
You can use it as such:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> t = Test().from_dict({"maybe": True, "ts": "2019-01-01T12:00:00Z", "duration": "1.200s"})
|
||||
>>> t
|
||||
Test(maybe=True, ts=datetime.datetime(2019, 1, 1, 12, 0, tzinfo=datetime.timezone.utc), duration=datetime.timedelta(seconds=1, microseconds=200000))
|
||||
|
||||
>>> t.ts - t.duration
|
||||
datetime.datetime(2019, 1, 1, 11, 59, 58, 800000, tzinfo=datetime.timezone.utc)
|
||||
|
||||
>>> t.ts.isoformat()
|
||||
'2019-01-01T12:00:00+00:00'
|
||||
|
||||
>>> t.maybe = None
|
||||
>>> t.to_dict()
|
||||
{'ts': '2019-01-01T12:00:00Z', 'duration': '1.200s'}
|
||||
|
||||
|
||||
[1.2.5] to [2.0.0b1]
|
||||
--------------------
|
||||
|
||||
Updated package structures
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Generated code now strictly follows the *package structure* of the ``.proto`` files.
|
||||
Consequently ``.proto`` files without a package will be combined in a single
|
||||
``__init__.py`` file. To avoid overwriting existing ``__init__.py`` files, its best
|
||||
to compile into a dedicated subdirectory.
|
||||
|
||||
Upgrading:
|
||||
|
||||
- Remove your previously compiled ``.py`` files.
|
||||
- Create a new *empty* directory, e.g. ``generated`` or ``lib/generated/proto`` etc.
|
||||
- Regenerate your python files into this directory
|
||||
- Update import statements, e.g. ``import ExampleMessage from generated``
|
||||
222
docs/quick-start.rst
Normal file
222
docs/quick-start.rst
Normal file
@@ -0,0 +1,222 @@
|
||||
Getting Started
|
||||
===============
|
||||
|
||||
Installation
|
||||
++++++++++++
|
||||
|
||||
Installation from PyPI is as simple as running:
|
||||
|
||||
.. code-block:: sh
|
||||
|
||||
python3 -m pip install -U betterproto
|
||||
|
||||
If you are using Windows, then the following should be used instead:
|
||||
|
||||
.. code-block:: sh
|
||||
|
||||
py -3 -m pip install -U betterproto
|
||||
|
||||
To include the protoc plugin, install betterproto[compiler] instead of betterproto,
|
||||
e.g.
|
||||
|
||||
.. code-block:: sh
|
||||
|
||||
python3 -m pip install -U "betterproto[compiler]"
|
||||
|
||||
Compiling proto files
|
||||
+++++++++++++++++++++
|
||||
|
||||
|
||||
Given you installed the compiler and have a proto file, e.g ``example.proto``:
|
||||
|
||||
.. code-block:: proto
|
||||
|
||||
syntax = "proto3";
|
||||
|
||||
package hello;
|
||||
|
||||
// Greeting represents a message you can tell a user.
|
||||
message Greeting {
|
||||
string message = 1;
|
||||
}
|
||||
|
||||
To compile the proto you would run the following:
|
||||
|
||||
You can run the following to invoke protoc directly:
|
||||
|
||||
.. code-block:: sh
|
||||
|
||||
mkdir hello
|
||||
protoc -I . --python_betterproto_out=lib example.proto
|
||||
|
||||
or run the following to invoke protoc via grpcio-tools:
|
||||
|
||||
.. code-block:: sh
|
||||
|
||||
pip install grpcio-tools
|
||||
python -m grpc_tools.protoc -I . --python_betterproto_out=lib example.proto
|
||||
|
||||
|
||||
This will generate ``lib/__init__.py`` which looks like:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# Generated by the protocol buffer compiler. DO NOT EDIT!
|
||||
# sources: example.proto
|
||||
# plugin: python-betterproto
|
||||
from dataclasses import dataclass
|
||||
|
||||
import betterproto
|
||||
|
||||
|
||||
@dataclass
|
||||
class Greeting(betterproto.Message):
|
||||
"""Greeting represents a message you can tell a user."""
|
||||
|
||||
message: str = betterproto.string_field(1)
|
||||
|
||||
|
||||
Then to use it:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> from lib import Greeting
|
||||
|
||||
>>> test = Greeting()
|
||||
>>> test
|
||||
Greeting(message='')
|
||||
|
||||
>>> test.message = "Hey!"
|
||||
>>> test
|
||||
Greeting(message="Hey!")
|
||||
|
||||
>>> bytes(test)
|
||||
b'\n\x04Hey!'
|
||||
>>> Greeting().parse(serialized)
|
||||
Greeting(message="Hey!")
|
||||
|
||||
|
||||
Async gRPC Support
|
||||
++++++++++++++++++
|
||||
|
||||
The generated code includes `grpclib <https://grpclib.readthedocs.io/en/latest>`_ based
|
||||
stub (client and server) classes for rpc services declared in the input proto files.
|
||||
It is enabled by default.
|
||||
|
||||
|
||||
Given a service definition similar to the one below:
|
||||
|
||||
.. code-block:: proto
|
||||
|
||||
syntax = "proto3";
|
||||
|
||||
package echo;
|
||||
|
||||
message EchoRequest {
|
||||
string value = 1;
|
||||
// Number of extra times to echo
|
||||
uint32 extra_times = 2;
|
||||
}
|
||||
|
||||
message EchoResponse {
|
||||
repeated string values = 1;
|
||||
}
|
||||
|
||||
message EchoStreamResponse {
|
||||
string value = 1;
|
||||
}
|
||||
|
||||
service Echo {
|
||||
rpc Echo(EchoRequest) returns (EchoResponse);
|
||||
rpc EchoStream(EchoRequest) returns (stream EchoStreamResponse);
|
||||
}
|
||||
|
||||
The generated client can be used like so:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
import asyncio
|
||||
from grpclib.client import Channel
|
||||
import echo
|
||||
|
||||
|
||||
async def main():
|
||||
channel = Channel(host="127.0.0.1", port=50051)
|
||||
service = echo.EchoStub(channel)
|
||||
response = await service.echo(value="hello", extra_times=1)
|
||||
print(response)
|
||||
|
||||
async for response in service.echo_stream(value="hello", extra_times=1):
|
||||
print(response)
|
||||
|
||||
# don't forget to close the channel when you're done!
|
||||
channel.close()
|
||||
|
||||
asyncio.run(main()) # python 3.7 only
|
||||
|
||||
# outputs
|
||||
EchoResponse(values=['hello', 'hello'])
|
||||
EchoStreamResponse(value='hello')
|
||||
EchoStreamResponse(value='hello')
|
||||
|
||||
|
||||
The server-facing stubs can be used to implement a Python
|
||||
gRPC server.
|
||||
To use them, simply subclass the base class in the generated files and override the
|
||||
service methods:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from echo import EchoBase
|
||||
from grpclib.server import Server
|
||||
from typing import AsyncIterator
|
||||
|
||||
|
||||
class EchoService(EchoBase):
|
||||
async def echo(self, value: str, extra_times: int) -> "EchoResponse":
|
||||
return value
|
||||
|
||||
async def echo_stream(
|
||||
self, value: str, extra_times: int
|
||||
) -> AsyncIterator["EchoStreamResponse"]:
|
||||
for _ in range(extra_times):
|
||||
yield value
|
||||
|
||||
|
||||
async def start_server():
|
||||
HOST = "127.0.0.1"
|
||||
PORT = 1337
|
||||
server = Server([EchoService()])
|
||||
await server.start(HOST, PORT)
|
||||
await server.serve_forever()
|
||||
|
||||
JSON
|
||||
++++
|
||||
Message objects include :meth:`betterproto.Message.to_json` and
|
||||
:meth:`betterproto.Message.from_json` methods for JSON (de)serialisation, and
|
||||
:meth:`betterproto.Message.to_dict`, :meth:`betterproto.Message.from_dict` for
|
||||
converting back and forth from JSON serializable dicts.
|
||||
|
||||
For compatibility the default is to convert field names to
|
||||
:attr:`betterproto.Casing.CAMEL`. You can control this behavior by passing a
|
||||
different casing value, e.g:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@dataclass
|
||||
class MyMessage(betterproto.Message):
|
||||
a_long_field_name: str = betterproto.string_field(1)
|
||||
|
||||
|
||||
>>> test = MyMessage(a_long_field_name="Hello World!")
|
||||
>>> test.to_dict(betterproto.Casing.SNAKE)
|
||||
{"a_long_field_name": "Hello World!"}
|
||||
>>> test.to_dict(betterproto.Casing.CAMEL)
|
||||
{"aLongFieldName": "Hello World!"}
|
||||
|
||||
>>> test.to_json(indent=2)
|
||||
'{\n "aLongFieldName": "Hello World!"\n}'
|
||||
|
||||
>>> test.from_dict({"aLongFieldName": "Goodbye World!"})
|
||||
>>> test.a_long_field_name
|
||||
"Goodbye World!"
|
||||
@@ -1,16 +0,0 @@
|
||||
# Upgrade Guide
|
||||
|
||||
## [1.2.5] to [2.0.0b1]
|
||||
|
||||
### Updated package structures
|
||||
|
||||
Generated code now strictly follows the *package structure* of the `.proto` files.
|
||||
Consequently `.proto` files without a package will be combined in a single `__init__.py` file.
|
||||
To avoid overwriting existing `__init__.py` files, its best to compile into a dedicated subdirectory.
|
||||
|
||||
Upgrading:
|
||||
|
||||
- Remove your previously compiled `.py` files.
|
||||
- Create a new *empty* directory, e.g. `generated` or `lib/generated/proto` etcetera.
|
||||
- Regenerate your python files into this directory
|
||||
- Update import statements, e.g. `import ExampleMessage from generated`
|
||||
55
example.py
Normal file
55
example.py
Normal file
@@ -0,0 +1,55 @@
|
||||
# dev tests
|
||||
# to be deleted later
|
||||
|
||||
import betterproto
|
||||
from dataclasses import dataclass
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
@dataclass(repr=False)
|
||||
class Baz(betterproto.Message):
|
||||
a: float = betterproto.float_field(1, group = "x")
|
||||
b: int = betterproto.int64_field(2, group = "x")
|
||||
c: float = betterproto.float_field(3, group = "y")
|
||||
d: int = betterproto.int64_field(4, group = "y")
|
||||
e: Optional[int] = betterproto.int32_field(5, group = "_e", optional = True)
|
||||
|
||||
@dataclass(repr=False)
|
||||
class Foo(betterproto.Message):
|
||||
x: int = betterproto.int32_field(1)
|
||||
y: float = betterproto.double_field(2)
|
||||
z: List[Baz] = betterproto.message_field(3)
|
||||
|
||||
class Enm(betterproto.Enum):
|
||||
A = 0
|
||||
B = 1
|
||||
C = 2
|
||||
|
||||
@dataclass(repr=False)
|
||||
class Bar(betterproto.Message):
|
||||
foo1: Foo = betterproto.message_field(1)
|
||||
foo2: Foo = betterproto.message_field(2)
|
||||
packed: List[int] = betterproto.int64_field(3)
|
||||
enm: Enm = betterproto.enum_field(4)
|
||||
map: Dict[int, bool] = betterproto.map_field(5, betterproto.TYPE_INT64, betterproto.TYPE_BOOL)
|
||||
maybe: Optional[bool] = betterproto.message_field(6, wraps=betterproto.TYPE_BOOL)
|
||||
bts: bytes = betterproto.bytes_field(7)
|
||||
|
||||
# Serialization has not been changed yet. So nothing unusual here
|
||||
buffer = bytes(
|
||||
Bar(
|
||||
foo1=Foo(1, 2.34),
|
||||
foo2=Foo(3, 4.56, [Baz(a = 1.234), Baz(b = 5, e=1), Baz(b = 2, d = 3)]),
|
||||
packed=[5, 3, 1],
|
||||
enm=Enm.B,
|
||||
map={
|
||||
1: True,
|
||||
42: False
|
||||
},
|
||||
maybe=True,
|
||||
bts=b'Hi There!'
|
||||
)
|
||||
)
|
||||
|
||||
# Native deserialization happening here
|
||||
bar = Bar().parse(buffer)
|
||||
print(bar)
|
||||
2421
poetry.lock
generated
2421
poetry.lock
generated
File diff suppressed because it is too large
Load Diff
126
pyproject.toml
126
pyproject.toml
@@ -1,43 +1,129 @@
|
||||
[tool.poetry]
|
||||
name = "betterproto"
|
||||
version = "2.0.0b1"
|
||||
version = "2.0.0b6"
|
||||
description = "A better Protobuf / gRPC generator & library"
|
||||
authors = ["Daniel G. Taylor <danielgtaylor@gmail.com>"]
|
||||
readme = "README.md"
|
||||
repository = "https://github.com/danielgtaylor/python-betterproto"
|
||||
keywords = ["protobuf", "gRPC"]
|
||||
license = "MIT"
|
||||
|
||||
exclude = ["betterproto/tests"]
|
||||
packages = [
|
||||
{ include = "betterproto", from = "src" }
|
||||
]
|
||||
|
||||
[tool.poetry.dependencies]
|
||||
python = "^3.6"
|
||||
backports-datetime-fromisoformat = { version = "^1.0.0", python = "<3.7" }
|
||||
black = { version = "^19.10b0", optional = true }
|
||||
dataclasses = { version = "^0.7", python = ">=3.6, <3.7" }
|
||||
grpclib = "^0.3.1"
|
||||
jinja2 = { version = "^2.11.2", optional = true }
|
||||
protobuf = { version = "^3.12.2", optional = true }
|
||||
python = "^3.7"
|
||||
black = { version = ">=23.1.0", optional = true }
|
||||
grpclib = "^0.4.1"
|
||||
importlib-metadata = { version = ">=1.6.0", python = "<3.8" }
|
||||
jinja2 = { version = ">=3.0.3", optional = true }
|
||||
python-dateutil = "^2.8"
|
||||
isort = {version = "^5.11.5", optional = true}
|
||||
betterproto-extras = { path = "betterproto-extras" }
|
||||
|
||||
[tool.poetry.dev-dependencies]
|
||||
black = "^19.10b0"
|
||||
asv = "^0.4.2"
|
||||
bpython = "^0.19"
|
||||
jinja2 = "^2.11.2"
|
||||
mypy = "^0.770"
|
||||
protobuf = "^3.12.2"
|
||||
pytest = "^5.4.2"
|
||||
grpcio-tools = "^1.54.2"
|
||||
jinja2 = ">=3.0.3"
|
||||
mypy = "^0.930"
|
||||
poethepoet = ">=0.9.0"
|
||||
protobuf = "^4.21.6"
|
||||
pytest = "^6.2.5"
|
||||
pytest-asyncio = "^0.12.0"
|
||||
pytest-cov = "^2.9.0"
|
||||
pytest-mock = "^3.1.1"
|
||||
sphinx = "3.1.2"
|
||||
sphinx-rtd-theme = "0.5.0"
|
||||
tomlkit = "^0.7.0"
|
||||
tox = "^3.15.1"
|
||||
pre-commit = "^2.17.0"
|
||||
pydantic = ">=1.8.0"
|
||||
|
||||
|
||||
[tool.poetry.scripts]
|
||||
protoc-gen-python_betterproto = "betterproto.plugin:main"
|
||||
|
||||
[tool.poetry.extras]
|
||||
compiler = ["black", "jinja2", "protobuf"]
|
||||
compiler = ["black", "isort", "jinja2"]
|
||||
|
||||
|
||||
# Dev workflow tasks
|
||||
|
||||
[tool.poe.tasks.generate]
|
||||
script = "tests.generate:main"
|
||||
help = "Generate test cases (do this once before running test)"
|
||||
|
||||
[tool.poe.tasks.test]
|
||||
cmd = "pytest"
|
||||
help = "Run tests"
|
||||
|
||||
[tool.poe.tasks.types]
|
||||
cmd = "mypy src --ignore-missing-imports"
|
||||
help = "Check types with mypy"
|
||||
|
||||
[tool.poe.tasks.format]
|
||||
cmd = "black . --exclude tests/output_ --target-version py310"
|
||||
help = "Apply black formatting to source code"
|
||||
|
||||
[tool.poe.tasks.docs]
|
||||
cmd = "sphinx-build docs docs/build"
|
||||
help = "Build the sphinx docs"
|
||||
|
||||
[tool.poe.tasks.bench]
|
||||
shell = "asv run master^! && asv run HEAD^! && asv compare master HEAD"
|
||||
help = "Benchmark current commit vs. master branch"
|
||||
|
||||
[tool.poe.tasks.clean]
|
||||
cmd = """
|
||||
rm -rf .asv .coverage .mypy_cache .pytest_cache
|
||||
dist betterproto.egg-info **/__pycache__
|
||||
testsoutput_*
|
||||
"""
|
||||
help = "Clean out generated files from the workspace"
|
||||
|
||||
[tool.poe.tasks.generate_lib]
|
||||
cmd = """
|
||||
protoc
|
||||
--plugin=protoc-gen-custom=src/betterproto/plugin/main.py
|
||||
--custom_opt=INCLUDE_GOOGLE
|
||||
--custom_out=src/betterproto/lib
|
||||
-I C:\\work\\include
|
||||
C:\\work\\include\\google\\protobuf\\**\\*.proto
|
||||
"""
|
||||
help = "Regenerate the types in betterproto.lib.google"
|
||||
|
||||
# CI tasks
|
||||
|
||||
[tool.poe.tasks.full-test]
|
||||
shell = "poe generate && tox"
|
||||
help = "Run tests with multiple pythons"
|
||||
|
||||
[tool.poe.tasks.check-style]
|
||||
cmd = "black . --check --diff"
|
||||
help = "Check if code style is correct"
|
||||
|
||||
[tool.isort]
|
||||
py_version = 37
|
||||
profile = "black"
|
||||
force_single_line = false
|
||||
combine_as_imports = true
|
||||
lines_after_imports = 2
|
||||
include_trailing_comma = true
|
||||
force_grid_wrap = 2
|
||||
src_paths = ["src", "tests"]
|
||||
|
||||
[tool.black]
|
||||
target-version = ['py36']
|
||||
target-version = ['py37']
|
||||
|
||||
[tool.doc8]
|
||||
paths = ["docs"]
|
||||
max_line_length = 88
|
||||
|
||||
[tool.doc8.ignore_path_errors]
|
||||
"docs/migrating.rst" = [
|
||||
"D001", # contains table which is longer than 88 characters long
|
||||
]
|
||||
|
||||
[tool.coverage.run]
|
||||
omit = ["betterproto/tests/*"]
|
||||
@@ -46,7 +132,7 @@ omit = ["betterproto/tests/*"]
|
||||
legacy_tox_ini = """
|
||||
[tox]
|
||||
isolated_build = true
|
||||
envlist = py36, py37, py38
|
||||
envlist = py37, py38, py310
|
||||
|
||||
[testenv]
|
||||
whitelist_externals = poetry
|
||||
@@ -56,5 +142,5 @@ commands =
|
||||
"""
|
||||
|
||||
[build-system]
|
||||
requires = ["poetry>=0.12"]
|
||||
build-backend = "poetry.masonry.api"
|
||||
requires = ["poetry-core>=1.0.0,<2"]
|
||||
build-backend = "poetry.core.masonry.api"
|
||||
|
||||
1949
src/betterproto/__init__.py
Normal file
1949
src/betterproto/__init__.py
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,8 +1,13 @@
|
||||
from typing import TYPE_CHECKING, TypeVar
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
TypeVar,
|
||||
)
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from grpclib._typing import IProtoMessage
|
||||
|
||||
from . import Message
|
||||
from grpclib._protocols import IProtoMessage
|
||||
|
||||
# Bound type variable to allow methods to return `self` of subclasses
|
||||
T = TypeVar("T", bound="Message")
|
||||
7
src/betterproto/_version.py
Normal file
7
src/betterproto/_version.py
Normal file
@@ -0,0 +1,7 @@
|
||||
try:
|
||||
from importlib import metadata
|
||||
except ImportError: # for Python<3.8
|
||||
import importlib_metadata as metadata # type: ignore
|
||||
|
||||
|
||||
__version__ = metadata.version("betterproto")
|
||||
@@ -1,5 +1,7 @@
|
||||
import keyword
|
||||
import re
|
||||
|
||||
|
||||
# Word delimiters and symbols that will not be preserved when re-casing.
|
||||
# language=PythonRegExp
|
||||
SYMBOLS = "[^a-zA-Z0-9]*"
|
||||
@@ -16,51 +18,28 @@ WORD_UPPER = "[A-Z]+(?![a-z])[0-9]*"
|
||||
def safe_snake_case(value: str) -> str:
|
||||
"""Snake case a value taking into account Python keywords."""
|
||||
value = snake_case(value)
|
||||
if value in [
|
||||
"and",
|
||||
"as",
|
||||
"assert",
|
||||
"break",
|
||||
"class",
|
||||
"continue",
|
||||
"def",
|
||||
"del",
|
||||
"elif",
|
||||
"else",
|
||||
"except",
|
||||
"finally",
|
||||
"for",
|
||||
"from",
|
||||
"global",
|
||||
"if",
|
||||
"import",
|
||||
"in",
|
||||
"is",
|
||||
"lambda",
|
||||
"nonlocal",
|
||||
"not",
|
||||
"or",
|
||||
"pass",
|
||||
"raise",
|
||||
"return",
|
||||
"try",
|
||||
"while",
|
||||
"with",
|
||||
"yield",
|
||||
]:
|
||||
# https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles
|
||||
value += "_"
|
||||
value = sanitize_name(value)
|
||||
return value
|
||||
|
||||
|
||||
def snake_case(value: str, strict: bool = True):
|
||||
def snake_case(value: str, strict: bool = True) -> str:
|
||||
"""
|
||||
Join words with an underscore into lowercase and remove symbols.
|
||||
@param value: value to convert
|
||||
@param strict: force single underscores
|
||||
|
||||
Parameters
|
||||
-----------
|
||||
value: :class:`str`
|
||||
The value to convert.
|
||||
strict: :class:`bool`
|
||||
Whether or not to force single underscores.
|
||||
|
||||
Returns
|
||||
--------
|
||||
:class:`str`
|
||||
The value in snake_case.
|
||||
"""
|
||||
|
||||
def substitute_word(symbols, word, is_start):
|
||||
def substitute_word(symbols: str, word: str, is_start: bool) -> str:
|
||||
if not word:
|
||||
return ""
|
||||
if strict:
|
||||
@@ -84,11 +63,21 @@ def snake_case(value: str, strict: bool = True):
|
||||
return snake
|
||||
|
||||
|
||||
def pascal_case(value: str, strict: bool = True):
|
||||
def pascal_case(value: str, strict: bool = True) -> str:
|
||||
"""
|
||||
Capitalize each word and remove symbols.
|
||||
@param value: value to convert
|
||||
@param strict: output only alphanumeric characters
|
||||
|
||||
Parameters
|
||||
-----------
|
||||
value: :class:`str`
|
||||
The value to convert.
|
||||
strict: :class:`bool`
|
||||
Whether or not to output only alphanumeric characters.
|
||||
|
||||
Returns
|
||||
--------
|
||||
:class:`str`
|
||||
The value in PascalCase.
|
||||
"""
|
||||
|
||||
def substitute_word(symbols, word):
|
||||
@@ -109,12 +98,42 @@ def pascal_case(value: str, strict: bool = True):
|
||||
)
|
||||
|
||||
|
||||
def camel_case(value: str, strict: bool = True):
|
||||
def camel_case(value: str, strict: bool = True) -> str:
|
||||
"""
|
||||
Capitalize all words except first and remove symbols.
|
||||
|
||||
Parameters
|
||||
-----------
|
||||
value: :class:`str`
|
||||
The value to convert.
|
||||
strict: :class:`bool`
|
||||
Whether or not to output only alphanumeric characters.
|
||||
|
||||
Returns
|
||||
--------
|
||||
:class:`str`
|
||||
The value in camelCase.
|
||||
"""
|
||||
return lowercase_first(pascal_case(value, strict=strict))
|
||||
|
||||
|
||||
def lowercase_first(value: str):
|
||||
def lowercase_first(value: str) -> str:
|
||||
"""
|
||||
Lower cases the first character of the value.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
value: :class:`str`
|
||||
The value to lower case.
|
||||
|
||||
Returns
|
||||
-------
|
||||
:class:`str`
|
||||
The lower cased string.
|
||||
"""
|
||||
return value[0:1].lower() + value[1:]
|
||||
|
||||
|
||||
def sanitize_name(value: str) -> str:
|
||||
# https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles
|
||||
return f"{value}_" if keyword.iskeyword(value) else value
|
||||
@@ -1,10 +1,17 @@
|
||||
import os
|
||||
import re
|
||||
from typing import Dict, List, Set, Type
|
||||
from typing import (
|
||||
Dict,
|
||||
List,
|
||||
Set,
|
||||
Tuple,
|
||||
Type,
|
||||
)
|
||||
|
||||
from ..casing import safe_snake_case
|
||||
from ..lib.google import protobuf as google_protobuf
|
||||
from .naming import pythonize_class_name
|
||||
|
||||
from betterproto import safe_snake_case
|
||||
from betterproto.compile.naming import pythonize_class_name
|
||||
from betterproto.lib.google import protobuf as google_protobuf
|
||||
|
||||
WRAPPER_TYPES: Dict[str, Type] = {
|
||||
".google.protobuf.DoubleValue": google_protobuf.DoubleValue,
|
||||
@@ -19,7 +26,7 @@ WRAPPER_TYPES: Dict[str, Type] = {
|
||||
}
|
||||
|
||||
|
||||
def parse_source_type_name(field_type_name):
|
||||
def parse_source_type_name(field_type_name: str) -> Tuple[str, str]:
|
||||
"""
|
||||
Split full source type name into package and type name.
|
||||
E.g. 'root.package.Message' -> ('root.package', 'Message')
|
||||
@@ -36,7 +43,7 @@ def parse_source_type_name(field_type_name):
|
||||
|
||||
|
||||
def get_type_reference(
|
||||
package: str, imports: set, source_type: str, unwrap: bool = True,
|
||||
*, package: str, imports: set, source_type: str, unwrap: bool = True
|
||||
) -> str:
|
||||
"""
|
||||
Return a Python type name for a proto type reference. Adds the import if
|
||||
@@ -50,7 +57,7 @@ def get_type_reference(
|
||||
if source_type == ".google.protobuf.Duration":
|
||||
return "timedelta"
|
||||
|
||||
if source_type == ".google.protobuf.Timestamp":
|
||||
elif source_type == ".google.protobuf.Timestamp":
|
||||
return "datetime"
|
||||
|
||||
source_package, source_type = parse_source_type_name(source_type)
|
||||
@@ -79,14 +86,14 @@ def get_type_reference(
|
||||
return reference_cousin(current_package, imports, py_package, py_type)
|
||||
|
||||
|
||||
def reference_absolute(imports, py_package, py_type):
|
||||
def reference_absolute(imports: Set[str], py_package: List[str], py_type: str) -> str:
|
||||
"""
|
||||
Returns a reference to a python type located in the root, i.e. sys.path.
|
||||
"""
|
||||
string_import = ".".join(py_package)
|
||||
string_alias = safe_snake_case(string_import)
|
||||
imports.add(f"import {string_import} as {string_alias}")
|
||||
return f"{string_alias}.{py_type}"
|
||||
return f'"{string_alias}.{py_type}"'
|
||||
|
||||
|
||||
def reference_sibling(py_type: str) -> str:
|
||||
@@ -100,8 +107,9 @@ def reference_descendent(
|
||||
current_package: List[str], imports: Set[str], py_package: List[str], py_type: str
|
||||
) -> str:
|
||||
"""
|
||||
Returns a reference to a python type in a package that is a descendent of the current package,
|
||||
and adds the required import that is aliased to avoid name conflicts.
|
||||
Returns a reference to a python type in a package that is a descendent of the
|
||||
current package, and adds the required import that is aliased to avoid name
|
||||
conflicts.
|
||||
"""
|
||||
importing_descendent = py_package[len(current_package) :]
|
||||
string_from = ".".join(importing_descendent[:-1])
|
||||
@@ -109,18 +117,19 @@ def reference_descendent(
|
||||
if string_from:
|
||||
string_alias = "_".join(importing_descendent)
|
||||
imports.add(f"from .{string_from} import {string_import} as {string_alias}")
|
||||
return f"{string_alias}.{py_type}"
|
||||
return f'"{string_alias}.{py_type}"'
|
||||
else:
|
||||
imports.add(f"from . import {string_import}")
|
||||
return f"{string_import}.{py_type}"
|
||||
return f'"{string_import}.{py_type}"'
|
||||
|
||||
|
||||
def reference_ancestor(
|
||||
current_package: List[str], imports: Set[str], py_package: List[str], py_type: str
|
||||
) -> str:
|
||||
"""
|
||||
Returns a reference to a python type in a package which is an ancestor to the current package,
|
||||
and adds the required import that is aliased (if possible) to avoid name conflicts.
|
||||
Returns a reference to a python type in a package which is an ancestor to the
|
||||
current package, and adds the required import that is aliased (if possible) to avoid
|
||||
name conflicts.
|
||||
|
||||
Adds trailing __ to avoid name mangling (python.org/dev/peps/pep-0008/#id34).
|
||||
"""
|
||||
@@ -130,21 +139,21 @@ def reference_ancestor(
|
||||
string_alias = f"_{'_' * distance_up}{string_import}__"
|
||||
string_from = f"..{'.' * distance_up}"
|
||||
imports.add(f"from {string_from} import {string_import} as {string_alias}")
|
||||
return f"{string_alias}.{py_type}"
|
||||
return f'"{string_alias}.{py_type}"'
|
||||
else:
|
||||
string_alias = f"{'_' * distance_up}{py_type}__"
|
||||
imports.add(f"from .{'.' * distance_up} import {py_type} as {string_alias}")
|
||||
return string_alias
|
||||
return f'"{string_alias}"'
|
||||
|
||||
|
||||
def reference_cousin(
|
||||
current_package: List[str], imports: Set[str], py_package: List[str], py_type: str
|
||||
) -> str:
|
||||
"""
|
||||
Returns a reference to a python type in a package that is not descendent, ancestor or sibling,
|
||||
and adds the required import that is aliased to avoid name conflicts.
|
||||
Returns a reference to a python type in a package that is not descendent, ancestor
|
||||
or sibling, and adds the required import that is aliased to avoid name conflicts.
|
||||
"""
|
||||
shared_ancestry = os.path.commonprefix([current_package, py_package])
|
||||
shared_ancestry = os.path.commonprefix([current_package, py_package]) # type: ignore
|
||||
distance_up = len(current_package) - len(shared_ancestry)
|
||||
string_from = f".{'.' * distance_up}" + ".".join(
|
||||
py_package[len(shared_ancestry) : -1]
|
||||
@@ -157,4 +166,4 @@ def reference_cousin(
|
||||
+ "__"
|
||||
)
|
||||
imports.add(f"from {string_from} import {string_import} as {string_alias}")
|
||||
return f"{string_alias}.{py_type}"
|
||||
return f'"{string_alias}.{py_type}"'
|
||||
@@ -1,13 +1,13 @@
|
||||
from betterproto import casing
|
||||
|
||||
|
||||
def pythonize_class_name(name):
|
||||
def pythonize_class_name(name: str) -> str:
|
||||
return casing.pascal_case(name)
|
||||
|
||||
|
||||
def pythonize_field_name(name: str):
|
||||
def pythonize_field_name(name: str) -> str:
|
||||
return casing.safe_snake_case(name)
|
||||
|
||||
|
||||
def pythonize_method_name(name: str):
|
||||
def pythonize_method_name(name: str) -> str:
|
||||
return casing.safe_snake_case(name)
|
||||
@@ -1,8 +1,7 @@
|
||||
from abc import ABC
|
||||
import asyncio
|
||||
import grpclib.const
|
||||
from abc import ABC
|
||||
from typing import (
|
||||
Any,
|
||||
TYPE_CHECKING,
|
||||
AsyncIterable,
|
||||
AsyncIterator,
|
||||
Collection,
|
||||
@@ -10,21 +9,28 @@ from typing import (
|
||||
Mapping,
|
||||
Optional,
|
||||
Tuple,
|
||||
TYPE_CHECKING,
|
||||
Type,
|
||||
Union,
|
||||
)
|
||||
from .._types import ST, T
|
||||
|
||||
import grpclib.const
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from grpclib._protocols import IProtoMessage
|
||||
from grpclib.client import Channel, Stream
|
||||
from grpclib.client import Channel
|
||||
from grpclib.metadata import Deadline
|
||||
|
||||
from .._types import (
|
||||
ST,
|
||||
IProtoMessage,
|
||||
Message,
|
||||
T,
|
||||
)
|
||||
|
||||
_Value = Union[str, bytes]
|
||||
_MetadataLike = Union[Mapping[str, _Value], Collection[Tuple[str, _Value]]]
|
||||
_MessageSource = Union[Iterable["IProtoMessage"], AsyncIterable["IProtoMessage"]]
|
||||
|
||||
Value = Union[str, bytes]
|
||||
MetadataLike = Union[Mapping[str, Value], Collection[Tuple[str, Value]]]
|
||||
MessageSource = Union[Iterable["IProtoMessage"], AsyncIterable["IProtoMessage"]]
|
||||
|
||||
|
||||
class ServiceStub(ABC):
|
||||
@@ -38,7 +44,7 @@ class ServiceStub(ABC):
|
||||
*,
|
||||
timeout: Optional[float] = None,
|
||||
deadline: Optional["Deadline"] = None,
|
||||
metadata: Optional[_MetadataLike] = None,
|
||||
metadata: Optional[MetadataLike] = None,
|
||||
) -> None:
|
||||
self.channel = channel
|
||||
self.timeout = timeout
|
||||
@@ -49,7 +55,7 @@ class ServiceStub(ABC):
|
||||
self,
|
||||
timeout: Optional[float],
|
||||
deadline: Optional["Deadline"],
|
||||
metadata: Optional[_MetadataLike],
|
||||
metadata: Optional[MetadataLike],
|
||||
):
|
||||
return {
|
||||
"timeout": self.timeout if timeout is None else timeout,
|
||||
@@ -61,12 +67,12 @@ class ServiceStub(ABC):
|
||||
self,
|
||||
route: str,
|
||||
request: "IProtoMessage",
|
||||
response_type: Type[T],
|
||||
response_type: Type["T"],
|
||||
*,
|
||||
timeout: Optional[float] = None,
|
||||
deadline: Optional["Deadline"] = None,
|
||||
metadata: Optional[_MetadataLike] = None,
|
||||
) -> T:
|
||||
metadata: Optional[MetadataLike] = None,
|
||||
) -> "T":
|
||||
"""Make a unary request and return the response."""
|
||||
async with self.channel.request(
|
||||
route,
|
||||
@@ -77,19 +83,19 @@ class ServiceStub(ABC):
|
||||
) as stream:
|
||||
await stream.send_message(request, end=True)
|
||||
response = await stream.recv_message()
|
||||
assert response is not None
|
||||
return response
|
||||
assert response is not None
|
||||
return response
|
||||
|
||||
async def _unary_stream(
|
||||
self,
|
||||
route: str,
|
||||
request: "IProtoMessage",
|
||||
response_type: Type[T],
|
||||
response_type: Type["T"],
|
||||
*,
|
||||
timeout: Optional[float] = None,
|
||||
deadline: Optional["Deadline"] = None,
|
||||
metadata: Optional[_MetadataLike] = None,
|
||||
) -> AsyncIterator[T]:
|
||||
metadata: Optional[MetadataLike] = None,
|
||||
) -> AsyncIterator["T"]:
|
||||
"""Make a unary request and return the stream response iterator."""
|
||||
async with self.channel.request(
|
||||
route,
|
||||
@@ -105,14 +111,14 @@ class ServiceStub(ABC):
|
||||
async def _stream_unary(
|
||||
self,
|
||||
route: str,
|
||||
request_iterator: _MessageSource,
|
||||
request_type: Type[ST],
|
||||
response_type: Type[T],
|
||||
request_iterator: MessageSource,
|
||||
request_type: Type["IProtoMessage"],
|
||||
response_type: Type["T"],
|
||||
*,
|
||||
timeout: Optional[float] = None,
|
||||
deadline: Optional["Deadline"] = None,
|
||||
metadata: Optional[_MetadataLike] = None,
|
||||
) -> T:
|
||||
metadata: Optional[MetadataLike] = None,
|
||||
) -> "T":
|
||||
"""Make a stream request and return the response."""
|
||||
async with self.channel.request(
|
||||
route,
|
||||
@@ -123,20 +129,20 @@ class ServiceStub(ABC):
|
||||
) as stream:
|
||||
await self._send_messages(stream, request_iterator)
|
||||
response = await stream.recv_message()
|
||||
assert response is not None
|
||||
return response
|
||||
assert response is not None
|
||||
return response
|
||||
|
||||
async def _stream_stream(
|
||||
self,
|
||||
route: str,
|
||||
request_iterator: _MessageSource,
|
||||
request_type: Type[ST],
|
||||
response_type: Type[T],
|
||||
request_iterator: MessageSource,
|
||||
request_type: Type["IProtoMessage"],
|
||||
response_type: Type["T"],
|
||||
*,
|
||||
timeout: Optional[float] = None,
|
||||
deadline: Optional["Deadline"] = None,
|
||||
metadata: Optional[_MetadataLike] = None,
|
||||
) -> AsyncIterator[T]:
|
||||
metadata: Optional[MetadataLike] = None,
|
||||
) -> AsyncIterator["T"]:
|
||||
"""
|
||||
Make a stream request and return an AsyncIterator to iterate over response
|
||||
messages.
|
||||
@@ -160,7 +166,7 @@ class ServiceStub(ABC):
|
||||
raise
|
||||
|
||||
@staticmethod
|
||||
async def _send_messages(stream, messages: _MessageSource):
|
||||
async def _send_messages(stream, messages: MessageSource):
|
||||
if isinstance(messages, AsyncIterable):
|
||||
async for message in messages:
|
||||
await stream.send_message(message)
|
||||
33
src/betterproto/grpc/grpclib_server.py
Normal file
33
src/betterproto/grpc/grpclib_server.py
Normal file
@@ -0,0 +1,33 @@
|
||||
from abc import ABC
|
||||
from collections.abc import AsyncIterable
|
||||
from typing import (
|
||||
Any,
|
||||
Callable,
|
||||
Dict,
|
||||
)
|
||||
|
||||
import grpclib
|
||||
import grpclib.server
|
||||
|
||||
|
||||
class ServiceBase(ABC):
|
||||
"""
|
||||
Base class for async gRPC servers.
|
||||
"""
|
||||
|
||||
async def _call_rpc_handler_server_stream(
|
||||
self,
|
||||
handler: Callable,
|
||||
stream: grpclib.server.Stream,
|
||||
request: Any,
|
||||
) -> None:
|
||||
response_iter = handler(request)
|
||||
# check if response is actually an AsyncIterator
|
||||
# this might be false if the method just returns without
|
||||
# yielding at least once
|
||||
# in that case, we just interpret it as an empty iterator
|
||||
if isinstance(response_iter, AsyncIterable):
|
||||
async for response_message in response_iter:
|
||||
await stream.send_message(response_message)
|
||||
else:
|
||||
response_iter.close()
|
||||
@@ -8,6 +8,7 @@ from typing import (
|
||||
Union,
|
||||
)
|
||||
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
@@ -16,57 +17,53 @@ class ChannelClosed(Exception):
|
||||
An exception raised on an attempt to send through a closed channel
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class ChannelDone(Exception):
|
||||
"""
|
||||
An exception raised on an attempt to send recieve from a channel that is both closed
|
||||
An exception raised on an attempt to send receive from a channel that is both closed
|
||||
and empty.
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class AsyncChannel(AsyncIterable[T]):
|
||||
"""
|
||||
A buffered async channel for sending items between coroutines with FIFO ordering.
|
||||
|
||||
This makes decoupled bidirection steaming gRPC requests easy if used like:
|
||||
This makes decoupled bidirectional steaming gRPC requests easy if used like:
|
||||
|
||||
.. code-block:: python
|
||||
client = GeneratedStub(grpclib_chan)
|
||||
request_chan = await AsyncChannel()
|
||||
request_channel = await AsyncChannel()
|
||||
# We can start be sending all the requests we already have
|
||||
await request_chan.send_from([ReqestObject(...), ReqestObject(...)])
|
||||
async for response in client.rpc_call(request_chan):
|
||||
await request_channel.send_from([RequestObject(...), RequestObject(...)])
|
||||
async for response in client.rpc_call(request_channel):
|
||||
# The response iterator will remain active until the connection is closed
|
||||
...
|
||||
# More items can be sent at any time
|
||||
await request_chan.send(ReqestObject(...))
|
||||
await request_channel.send(RequestObject(...))
|
||||
...
|
||||
# The channel must be closed to complete the gRPC connection
|
||||
request_chan.close()
|
||||
request_channel.close()
|
||||
|
||||
Items can be sent through the channel by either:
|
||||
- providing an iterable to the send_from method
|
||||
- passing them to the send method one at a time
|
||||
|
||||
Items can be recieved from the channel by either:
|
||||
Items can be received from the channel by either:
|
||||
- iterating over the channel with a for loop to get all items
|
||||
- calling the recieve method to get one item at a time
|
||||
- calling the receive method to get one item at a time
|
||||
|
||||
If the channel is empty then recievers will wait until either an item appears or the
|
||||
If the channel is empty then receivers will wait until either an item appears or the
|
||||
channel is closed.
|
||||
|
||||
Once the channel is closed then subsequent attempt to send through the channel will
|
||||
fail with a ChannelClosed exception.
|
||||
|
||||
When th channel is closed and empty then it is done, and further attempts to recieve
|
||||
When th channel is closed and empty then it is done, and further attempts to receive
|
||||
from it will fail with a ChannelDone exception
|
||||
|
||||
If multiple coroutines recieve from the channel concurrently, each item sent will be
|
||||
recieved by only one of the recievers.
|
||||
If multiple coroutines receive from the channel concurrently, each item sent will be
|
||||
received by only one of the receivers.
|
||||
|
||||
:param source:
|
||||
An optional iterable will items that should be sent through the channel
|
||||
@@ -74,18 +71,16 @@ class AsyncChannel(AsyncIterable[T]):
|
||||
:param buffer_limit:
|
||||
Limit the number of items that can be buffered in the channel, A value less than
|
||||
1 implies no limit. If the channel is full then attempts to send more items will
|
||||
result in the sender waiting until an item is recieved from the channel.
|
||||
result in the sender waiting until an item is received from the channel.
|
||||
:param close:
|
||||
If set to True then the channel will automatically close after exhausting source
|
||||
or immediately if no source is provided.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, *, buffer_limit: int = 0, close: bool = False,
|
||||
):
|
||||
self._queue: asyncio.Queue[Union[T, object]] = asyncio.Queue(buffer_limit)
|
||||
def __init__(self, *, buffer_limit: int = 0, close: bool = False):
|
||||
self._queue: asyncio.Queue[T] = asyncio.Queue(buffer_limit)
|
||||
self._closed = False
|
||||
self._waiting_recievers: int = 0
|
||||
self._waiting_receivers: int = 0
|
||||
# Track whether flush has been invoked so it can only happen once
|
||||
self._flushed = False
|
||||
|
||||
@@ -95,14 +90,14 @@ class AsyncChannel(AsyncIterable[T]):
|
||||
async def __anext__(self) -> T:
|
||||
if self.done():
|
||||
raise StopAsyncIteration
|
||||
self._waiting_recievers += 1
|
||||
self._waiting_receivers += 1
|
||||
try:
|
||||
result = await self._queue.get()
|
||||
if result is self.__flush:
|
||||
raise StopAsyncIteration
|
||||
return result
|
||||
finally:
|
||||
self._waiting_recievers -= 1
|
||||
self._waiting_receivers -= 1
|
||||
self._queue.task_done()
|
||||
|
||||
def closed(self) -> bool:
|
||||
@@ -116,12 +111,12 @@ class AsyncChannel(AsyncIterable[T]):
|
||||
Check if this channel is done.
|
||||
|
||||
:return: True if this channel is closed and and has been drained of items in
|
||||
which case any further attempts to recieve an item from this channel will raise
|
||||
which case any further attempts to receive an item from this channel will raise
|
||||
a ChannelDone exception.
|
||||
"""
|
||||
# After close the channel is not yet done until there is at least one waiting
|
||||
# reciever per enqueued item.
|
||||
return self._closed and self._queue.qsize() <= self._waiting_recievers
|
||||
# receiver per enqueued item.
|
||||
return self._closed and self._queue.qsize() <= self._waiting_receivers
|
||||
|
||||
async def send_from(
|
||||
self, source: Union[Iterable[T], AsyncIterable[T]], close: bool = False
|
||||
@@ -158,22 +153,22 @@ class AsyncChannel(AsyncIterable[T]):
|
||||
await self._queue.put(item)
|
||||
return self
|
||||
|
||||
async def recieve(self) -> Optional[T]:
|
||||
async def receive(self) -> Optional[T]:
|
||||
"""
|
||||
Returns the next item from this channel when it becomes available,
|
||||
or None if the channel is closed before another item is sent.
|
||||
:return: An item from the channel
|
||||
"""
|
||||
if self.done():
|
||||
raise ChannelDone("Cannot recieve from a closed channel")
|
||||
self._waiting_recievers += 1
|
||||
raise ChannelDone("Cannot receive from a closed channel")
|
||||
self._waiting_receivers += 1
|
||||
try:
|
||||
result = await self._queue.get()
|
||||
if result is self.__flush:
|
||||
return None
|
||||
return result
|
||||
finally:
|
||||
self._waiting_recievers -= 1
|
||||
self._waiting_receivers -= 1
|
||||
self._queue.task_done()
|
||||
|
||||
def close(self):
|
||||
@@ -190,8 +185,8 @@ class AsyncChannel(AsyncIterable[T]):
|
||||
"""
|
||||
if not self._flushed:
|
||||
self._flushed = True
|
||||
deadlocked_recievers = max(0, self._waiting_recievers - self._queue.qsize())
|
||||
for _ in range(deadlocked_recievers):
|
||||
deadlocked_receivers = max(0, self._waiting_receivers - self._queue.qsize())
|
||||
for _ in range(deadlocked_receivers):
|
||||
await self._queue.put(self.__flush)
|
||||
|
||||
# A special signal object for flushing the queue when the channel is closed
|
||||
1670
src/betterproto/lib/google/protobuf/__init__.py
Normal file
1670
src/betterproto/lib/google/protobuf/__init__.py
Normal file
File diff suppressed because it is too large
Load Diff
152
src/betterproto/lib/google/protobuf/compiler/__init__.py
Normal file
152
src/betterproto/lib/google/protobuf/compiler/__init__.py
Normal file
@@ -0,0 +1,152 @@
|
||||
# Generated by the protocol buffer compiler. DO NOT EDIT!
|
||||
# sources: google/protobuf/compiler/plugin.proto
|
||||
# plugin: python-betterproto
|
||||
# This file has been @generated
|
||||
from dataclasses import dataclass
|
||||
from typing import List
|
||||
|
||||
import betterproto
|
||||
import betterproto.lib.google.protobuf as betterproto_lib_google_protobuf
|
||||
|
||||
|
||||
class CodeGeneratorResponseFeature(betterproto.Enum):
|
||||
"""Sync with code_generator.h."""
|
||||
|
||||
FEATURE_NONE = 0
|
||||
FEATURE_PROTO3_OPTIONAL = 1
|
||||
|
||||
|
||||
@dataclass(eq=False, repr=False)
|
||||
class Version(betterproto.Message):
|
||||
"""The version number of protocol compiler."""
|
||||
|
||||
major: int = betterproto.int32_field(1)
|
||||
minor: int = betterproto.int32_field(2)
|
||||
patch: int = betterproto.int32_field(3)
|
||||
suffix: str = betterproto.string_field(4)
|
||||
"""
|
||||
A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should
|
||||
be empty for mainline stable releases.
|
||||
"""
|
||||
|
||||
|
||||
@dataclass(eq=False, repr=False)
|
||||
class CodeGeneratorRequest(betterproto.Message):
|
||||
"""An encoded CodeGeneratorRequest is written to the plugin's stdin."""
|
||||
|
||||
file_to_generate: List[str] = betterproto.string_field(1)
|
||||
"""
|
||||
The .proto files that were explicitly listed on the command-line. The code
|
||||
generator should generate code only for these files. Each file's
|
||||
descriptor will be included in proto_file, below.
|
||||
"""
|
||||
|
||||
parameter: str = betterproto.string_field(2)
|
||||
"""The generator parameter passed on the command-line."""
|
||||
|
||||
proto_file: List[
|
||||
"betterproto_lib_google_protobuf.FileDescriptorProto"
|
||||
] = betterproto.message_field(15)
|
||||
"""
|
||||
FileDescriptorProtos for all files in files_to_generate and everything they
|
||||
import. The files will appear in topological order, so each file appears
|
||||
before any file that imports it. protoc guarantees that all proto_files
|
||||
will be written after the fields above, even though this is not technically
|
||||
guaranteed by the protobuf wire format. This theoretically could allow a
|
||||
plugin to stream in the FileDescriptorProtos and handle them one by one
|
||||
rather than read the entire set into memory at once. However, as of this
|
||||
writing, this is not similarly optimized on protoc's end -- it will store
|
||||
all fields in memory at once before sending them to the plugin. Type names
|
||||
of fields and extensions in the FileDescriptorProto are always fully
|
||||
qualified.
|
||||
"""
|
||||
|
||||
compiler_version: "Version" = betterproto.message_field(3)
|
||||
"""The version number of protocol compiler."""
|
||||
|
||||
|
||||
@dataclass(eq=False, repr=False)
|
||||
class CodeGeneratorResponse(betterproto.Message):
|
||||
"""The plugin writes an encoded CodeGeneratorResponse to stdout."""
|
||||
|
||||
error: str = betterproto.string_field(1)
|
||||
"""
|
||||
Error message. If non-empty, code generation failed. The plugin process
|
||||
should exit with status code zero even if it reports an error in this way.
|
||||
This should be used to indicate errors in .proto files which prevent the
|
||||
code generator from generating correct code. Errors which indicate a
|
||||
problem in protoc itself -- such as the input CodeGeneratorRequest being
|
||||
unparseable -- should be reported by writing a message to stderr and
|
||||
exiting with a non-zero status code.
|
||||
"""
|
||||
|
||||
supported_features: int = betterproto.uint64_field(2)
|
||||
"""
|
||||
A bitmask of supported features that the code generator supports. This is a
|
||||
bitwise "or" of values from the Feature enum.
|
||||
"""
|
||||
|
||||
file: List["CodeGeneratorResponseFile"] = betterproto.message_field(15)
|
||||
|
||||
|
||||
@dataclass(eq=False, repr=False)
|
||||
class CodeGeneratorResponseFile(betterproto.Message):
|
||||
"""Represents a single generated file."""
|
||||
|
||||
name: str = betterproto.string_field(1)
|
||||
"""
|
||||
The file name, relative to the output directory. The name must not contain
|
||||
"." or ".." components and must be relative, not be absolute (so, the file
|
||||
cannot lie outside the output directory). "/" must be used as the path
|
||||
separator, not "\". If the name is omitted, the content will be appended to
|
||||
the previous file. This allows the generator to break large files into
|
||||
small chunks, and allows the generated text to be streamed back to protoc
|
||||
so that large files need not reside completely in memory at one time. Note
|
||||
that as of this writing protoc does not optimize for this -- it will read
|
||||
the entire CodeGeneratorResponse before writing files to disk.
|
||||
"""
|
||||
|
||||
insertion_point: str = betterproto.string_field(2)
|
||||
"""
|
||||
If non-empty, indicates that the named file should already exist, and the
|
||||
content here is to be inserted into that file at a defined insertion point.
|
||||
This feature allows a code generator to extend the output produced by
|
||||
another code generator. The original generator may provide insertion
|
||||
points by placing special annotations in the file that look like:
|
||||
@@protoc_insertion_point(NAME) The annotation can have arbitrary text
|
||||
before and after it on the line, which allows it to be placed in a comment.
|
||||
NAME should be replaced with an identifier naming the point -- this is what
|
||||
other generators will use as the insertion_point. Code inserted at this
|
||||
point will be placed immediately above the line containing the insertion
|
||||
point (thus multiple insertions to the same point will come out in the
|
||||
order they were added). The double-@ is intended to make it unlikely that
|
||||
the generated code could contain things that look like insertion points by
|
||||
accident. For example, the C++ code generator places the following line in
|
||||
the .pb.h files that it generates: //
|
||||
@@protoc_insertion_point(namespace_scope) This line appears within the
|
||||
scope of the file's package namespace, but outside of any particular class.
|
||||
Another plugin can then specify the insertion_point "namespace_scope" to
|
||||
generate additional classes or other declarations that should be placed in
|
||||
this scope. Note that if the line containing the insertion point begins
|
||||
with whitespace, the same whitespace will be added to every line of the
|
||||
inserted text. This is useful for languages like Python, where indentation
|
||||
matters. In these languages, the insertion point comment should be
|
||||
indented the same amount as any inserted code will need to be in order to
|
||||
work correctly in that context. The code generator that generates the
|
||||
initial file and the one which inserts into it must both run as part of a
|
||||
single invocation of protoc. Code generators are executed in the order in
|
||||
which they appear on the command line. If |insertion_point| is present,
|
||||
|name| must also be present.
|
||||
"""
|
||||
|
||||
content: str = betterproto.string_field(15)
|
||||
"""The file contents."""
|
||||
|
||||
generated_code_info: "betterproto_lib_google_protobuf.GeneratedCodeInfo" = (
|
||||
betterproto.message_field(16)
|
||||
)
|
||||
"""
|
||||
Information describing the file content being inserted. If an insertion
|
||||
point is used, this information will be appropriately offset and inserted
|
||||
into the code generation metadata for the generated files.
|
||||
"""
|
||||
1
src/betterproto/plugin/__init__.py
Normal file
1
src/betterproto/plugin/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
from .main import main
|
||||
4
src/betterproto/plugin/__main__.py
Normal file
4
src/betterproto/plugin/__main__.py
Normal file
@@ -0,0 +1,4 @@
|
||||
from .main import main
|
||||
|
||||
|
||||
main()
|
||||
50
src/betterproto/plugin/compiler.py
Normal file
50
src/betterproto/plugin/compiler.py
Normal file
@@ -0,0 +1,50 @@
|
||||
import os.path
|
||||
|
||||
|
||||
try:
|
||||
# betterproto[compiler] specific dependencies
|
||||
import black
|
||||
import isort.api
|
||||
import jinja2
|
||||
except ImportError as err:
|
||||
print(
|
||||
"\033[31m"
|
||||
f"Unable to import `{err.name}` from betterproto plugin! "
|
||||
"Please ensure that you've installed betterproto as "
|
||||
'`pip install "betterproto[compiler]"` so that compiler dependencies '
|
||||
"are included."
|
||||
"\033[0m"
|
||||
)
|
||||
raise SystemExit(1)
|
||||
|
||||
from .models import OutputTemplate
|
||||
|
||||
|
||||
def outputfile_compiler(output_file: OutputTemplate) -> str:
|
||||
templates_folder = os.path.abspath(
|
||||
os.path.join(os.path.dirname(__file__), "..", "templates")
|
||||
)
|
||||
|
||||
env = jinja2.Environment(
|
||||
trim_blocks=True,
|
||||
lstrip_blocks=True,
|
||||
loader=jinja2.FileSystemLoader(templates_folder),
|
||||
)
|
||||
template = env.get_template("template.py.j2")
|
||||
|
||||
code = template.render(output_file=output_file)
|
||||
code = isort.api.sort_code_string(
|
||||
code=code,
|
||||
show_diff=False,
|
||||
py_version=37,
|
||||
profile="black",
|
||||
combine_as_imports=True,
|
||||
lines_after_imports=2,
|
||||
quiet=True,
|
||||
force_grid_wrap=2,
|
||||
known_third_party=["grpclib", "betterproto"],
|
||||
)
|
||||
return black.format_str(
|
||||
src_contents=code,
|
||||
mode=black.Mode(),
|
||||
)
|
||||
52
src/betterproto/plugin/main.py
Executable file
52
src/betterproto/plugin/main.py
Executable file
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
from betterproto.lib.google.protobuf.compiler import (
|
||||
CodeGeneratorRequest,
|
||||
CodeGeneratorResponse,
|
||||
)
|
||||
from betterproto.plugin.models import monkey_patch_oneof_index
|
||||
from betterproto.plugin.parser import generate_code
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""The plugin's main entry point."""
|
||||
# Read request message from stdin
|
||||
data = sys.stdin.buffer.read()
|
||||
|
||||
# Apply Work around for proto2/3 difference in protoc messages
|
||||
monkey_patch_oneof_index()
|
||||
|
||||
# Parse request
|
||||
request = CodeGeneratorRequest()
|
||||
request.parse(data)
|
||||
|
||||
dump_file = os.getenv("BETTERPROTO_DUMP")
|
||||
if dump_file:
|
||||
dump_request(dump_file, request)
|
||||
|
||||
# Generate code
|
||||
response = generate_code(request)
|
||||
|
||||
# Serialise response message
|
||||
output = response.SerializeToString()
|
||||
|
||||
# Write to stdout
|
||||
sys.stdout.buffer.write(output)
|
||||
|
||||
|
||||
def dump_request(dump_file: str, request: CodeGeneratorRequest) -> None:
|
||||
"""
|
||||
For developers: Supports running plugin.py standalone so its possible to debug it.
|
||||
Run protoc (or generate.py) with BETTERPROTO_DUMP="yourfile.bin" to write the request to a file.
|
||||
Then run plugin.py from your IDE in debugging mode, and redirect stdin to the file.
|
||||
"""
|
||||
with open(str(dump_file), "wb") as fh:
|
||||
sys.stderr.write(f"\033[31mWriting input from protoc to: {dump_file}\033[0m\n")
|
||||
fh.write(request.SerializeToString())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
843
src/betterproto/plugin/models.py
Normal file
843
src/betterproto/plugin/models.py
Normal file
@@ -0,0 +1,843 @@
|
||||
"""Plugin model dataclasses.
|
||||
|
||||
These classes are meant to be an intermediate representation
|
||||
of protobuf objects. They are used to organize the data collected during parsing.
|
||||
|
||||
The general intention is to create a doubly-linked tree-like structure
|
||||
with the following types of references:
|
||||
- Downwards references: from message -> fields, from output package -> messages
|
||||
or from service -> service methods
|
||||
- Upwards references: from field -> message, message -> package.
|
||||
- Input/output message references: from a service method to it's corresponding
|
||||
input/output messages, which may even be in another package.
|
||||
|
||||
There are convenience methods to allow climbing up and down this tree, for
|
||||
example to retrieve the list of all messages that are in the same package as
|
||||
the current message.
|
||||
|
||||
Most of these classes take as inputs:
|
||||
- proto_obj: A reference to it's corresponding protobuf object as
|
||||
presented by the protoc plugin.
|
||||
- parent: a reference to the parent object in the tree.
|
||||
|
||||
With this information, the class is able to expose attributes,
|
||||
such as a pythonized name, that will be calculated from proto_obj.
|
||||
|
||||
The instantiation should also attach a reference to the new object
|
||||
into the corresponding place within it's parent object. For example,
|
||||
instantiating field `A` with parent message `B` should add a
|
||||
reference to `A` to `B`'s `fields` attribute.
|
||||
"""
|
||||
|
||||
|
||||
import builtins
|
||||
import re
|
||||
import textwrap
|
||||
from dataclasses import (
|
||||
dataclass,
|
||||
field,
|
||||
)
|
||||
from typing import (
|
||||
Dict,
|
||||
Iterable,
|
||||
Iterator,
|
||||
List,
|
||||
Optional,
|
||||
Set,
|
||||
Type,
|
||||
Union,
|
||||
)
|
||||
|
||||
import betterproto
|
||||
from betterproto import which_one_of
|
||||
from betterproto.casing import sanitize_name
|
||||
from betterproto.compile.importing import (
|
||||
get_type_reference,
|
||||
parse_source_type_name,
|
||||
)
|
||||
from betterproto.compile.naming import (
|
||||
pythonize_class_name,
|
||||
pythonize_field_name,
|
||||
pythonize_method_name,
|
||||
)
|
||||
from betterproto.lib.google.protobuf import (
|
||||
DescriptorProto,
|
||||
EnumDescriptorProto,
|
||||
Field,
|
||||
FieldDescriptorProto,
|
||||
FieldDescriptorProtoLabel,
|
||||
FieldDescriptorProtoType,
|
||||
FileDescriptorProto,
|
||||
MethodDescriptorProto,
|
||||
)
|
||||
from betterproto.lib.google.protobuf.compiler import CodeGeneratorRequest
|
||||
|
||||
from ..casing import sanitize_name
|
||||
from ..compile.importing import (
|
||||
get_type_reference,
|
||||
parse_source_type_name,
|
||||
)
|
||||
from ..compile.naming import (
|
||||
pythonize_class_name,
|
||||
pythonize_field_name,
|
||||
pythonize_method_name,
|
||||
)
|
||||
|
||||
|
||||
# Create a unique placeholder to deal with
|
||||
# https://stackoverflow.com/questions/51575931/class-inheritance-in-python-3-7-dataclasses
|
||||
PLACEHOLDER = object()
|
||||
|
||||
# Organize proto types into categories
|
||||
PROTO_FLOAT_TYPES = (
|
||||
FieldDescriptorProtoType.TYPE_DOUBLE, # 1
|
||||
FieldDescriptorProtoType.TYPE_FLOAT, # 2
|
||||
)
|
||||
PROTO_INT_TYPES = (
|
||||
FieldDescriptorProtoType.TYPE_INT64, # 3
|
||||
FieldDescriptorProtoType.TYPE_UINT64, # 4
|
||||
FieldDescriptorProtoType.TYPE_INT32, # 5
|
||||
FieldDescriptorProtoType.TYPE_FIXED64, # 6
|
||||
FieldDescriptorProtoType.TYPE_FIXED32, # 7
|
||||
FieldDescriptorProtoType.TYPE_UINT32, # 13
|
||||
FieldDescriptorProtoType.TYPE_SFIXED32, # 15
|
||||
FieldDescriptorProtoType.TYPE_SFIXED64, # 16
|
||||
FieldDescriptorProtoType.TYPE_SINT32, # 17
|
||||
FieldDescriptorProtoType.TYPE_SINT64, # 18
|
||||
)
|
||||
PROTO_BOOL_TYPES = (FieldDescriptorProtoType.TYPE_BOOL,) # 8
|
||||
PROTO_STR_TYPES = (FieldDescriptorProtoType.TYPE_STRING,) # 9
|
||||
PROTO_BYTES_TYPES = (FieldDescriptorProtoType.TYPE_BYTES,) # 12
|
||||
PROTO_MESSAGE_TYPES = (
|
||||
FieldDescriptorProtoType.TYPE_MESSAGE, # 11
|
||||
FieldDescriptorProtoType.TYPE_ENUM, # 14
|
||||
)
|
||||
PROTO_MAP_TYPES = (FieldDescriptorProtoType.TYPE_MESSAGE,) # 11
|
||||
PROTO_PACKED_TYPES = (
|
||||
FieldDescriptorProtoType.TYPE_DOUBLE, # 1
|
||||
FieldDescriptorProtoType.TYPE_FLOAT, # 2
|
||||
FieldDescriptorProtoType.TYPE_INT64, # 3
|
||||
FieldDescriptorProtoType.TYPE_UINT64, # 4
|
||||
FieldDescriptorProtoType.TYPE_INT32, # 5
|
||||
FieldDescriptorProtoType.TYPE_FIXED64, # 6
|
||||
FieldDescriptorProtoType.TYPE_FIXED32, # 7
|
||||
FieldDescriptorProtoType.TYPE_BOOL, # 8
|
||||
FieldDescriptorProtoType.TYPE_UINT32, # 13
|
||||
FieldDescriptorProtoType.TYPE_SFIXED32, # 15
|
||||
FieldDescriptorProtoType.TYPE_SFIXED64, # 16
|
||||
FieldDescriptorProtoType.TYPE_SINT32, # 17
|
||||
FieldDescriptorProtoType.TYPE_SINT64, # 18
|
||||
)
|
||||
|
||||
|
||||
def monkey_patch_oneof_index():
|
||||
"""
|
||||
The compiler message types are written for proto2, but we read them as proto3.
|
||||
For this to work in the case of the oneof_index fields, which depend on being able
|
||||
to tell whether they were set, we have to treat them as oneof fields. This method
|
||||
monkey patches the generated classes after the fact to force this behaviour.
|
||||
"""
|
||||
object.__setattr__(
|
||||
FieldDescriptorProto.__dataclass_fields__["oneof_index"].metadata[
|
||||
"betterproto"
|
||||
],
|
||||
"group",
|
||||
"_oneof_index",
|
||||
)
|
||||
object.__setattr__(
|
||||
Field.__dataclass_fields__["oneof_index"].metadata["betterproto"],
|
||||
"group",
|
||||
"_oneof_index",
|
||||
)
|
||||
|
||||
|
||||
def get_comment(
|
||||
proto_file: "FileDescriptorProto", path: List[int], indent: int = 4
|
||||
) -> str:
|
||||
pad = " " * indent
|
||||
for sci_loc in proto_file.source_code_info.location:
|
||||
if list(sci_loc.path) == path and sci_loc.leading_comments:
|
||||
lines = textwrap.wrap(
|
||||
sci_loc.leading_comments.strip().replace("\n", ""), width=79 - indent
|
||||
)
|
||||
|
||||
# This is a field, message, enum, service, or method
|
||||
if len(lines) == 1 and len(lines[0]) < 79 - indent - 6:
|
||||
lines[0] = lines[0].strip('"')
|
||||
return f'{pad}"""{lines[0]}"""'
|
||||
else:
|
||||
joined = f"\n{pad}".join(lines)
|
||||
return f'{pad}"""\n{pad}{joined}\n{pad}"""'
|
||||
|
||||
return ""
|
||||
|
||||
|
||||
class ProtoContentBase:
|
||||
"""Methods common to MessageCompiler, ServiceCompiler and ServiceMethodCompiler."""
|
||||
|
||||
source_file: FileDescriptorProto
|
||||
path: List[int]
|
||||
comment_indent: int = 4
|
||||
parent: Union["betterproto.Message", "OutputTemplate"]
|
||||
|
||||
__dataclass_fields__: Dict[str, object]
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
"""Checks that no fake default fields were left as placeholders."""
|
||||
for field_name, field_val in self.__dataclass_fields__.items():
|
||||
if field_val is PLACEHOLDER:
|
||||
raise ValueError(f"`{field_name}` is a required field.")
|
||||
|
||||
@property
|
||||
def output_file(self) -> "OutputTemplate":
|
||||
current = self
|
||||
while not isinstance(current, OutputTemplate):
|
||||
current = current.parent
|
||||
return current
|
||||
|
||||
@property
|
||||
def request(self) -> "PluginRequestCompiler":
|
||||
current = self
|
||||
while not isinstance(current, OutputTemplate):
|
||||
current = current.parent
|
||||
return current.parent_request
|
||||
|
||||
@property
|
||||
def comment(self) -> str:
|
||||
"""Crawl the proto source code and retrieve comments
|
||||
for this object.
|
||||
"""
|
||||
return get_comment(
|
||||
proto_file=self.source_file, path=self.path, indent=self.comment_indent
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class PluginRequestCompiler:
|
||||
plugin_request_obj: CodeGeneratorRequest
|
||||
output_packages: Dict[str, "OutputTemplate"] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def all_messages(self) -> List["MessageCompiler"]:
|
||||
"""All of the messages in this request.
|
||||
|
||||
Returns
|
||||
-------
|
||||
List[MessageCompiler]
|
||||
List of all of the messages in this request.
|
||||
"""
|
||||
return [
|
||||
msg for output in self.output_packages.values() for msg in output.messages
|
||||
]
|
||||
|
||||
|
||||
@dataclass
|
||||
class OutputTemplate:
|
||||
"""Representation of an output .py file.
|
||||
|
||||
Each output file corresponds to a .proto input file,
|
||||
but may need references to other .proto files to be
|
||||
built.
|
||||
"""
|
||||
|
||||
parent_request: PluginRequestCompiler
|
||||
package_proto_obj: FileDescriptorProto
|
||||
input_files: List[str] = field(default_factory=list)
|
||||
imports: Set[str] = field(default_factory=set)
|
||||
datetime_imports: Set[str] = field(default_factory=set)
|
||||
typing_imports: Set[str] = field(default_factory=set)
|
||||
pydantic_imports: Set[str] = field(default_factory=set)
|
||||
builtins_import: bool = False
|
||||
messages: List["MessageCompiler"] = field(default_factory=list)
|
||||
enums: List["EnumDefinitionCompiler"] = field(default_factory=list)
|
||||
services: List["ServiceCompiler"] = field(default_factory=list)
|
||||
imports_type_checking_only: Set[str] = field(default_factory=set)
|
||||
pydantic_dataclasses: bool = False
|
||||
output: bool = True
|
||||
|
||||
@property
|
||||
def package(self) -> str:
|
||||
"""Name of input package.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
Name of input package.
|
||||
"""
|
||||
return self.package_proto_obj.package
|
||||
|
||||
@property
|
||||
def input_filenames(self) -> Iterable[str]:
|
||||
"""Names of the input files used to build this output.
|
||||
|
||||
Returns
|
||||
-------
|
||||
Iterable[str]
|
||||
Names of the input files used to build this output.
|
||||
"""
|
||||
return sorted(f.name for f in self.input_files)
|
||||
|
||||
@property
|
||||
def python_module_imports(self) -> Set[str]:
|
||||
imports = set()
|
||||
if any(x for x in self.messages if any(x.deprecated_fields)):
|
||||
imports.add("warnings")
|
||||
if self.builtins_import:
|
||||
imports.add("builtins")
|
||||
return imports
|
||||
|
||||
|
||||
@dataclass
|
||||
class MessageCompiler(ProtoContentBase):
|
||||
"""Representation of a protobuf message."""
|
||||
|
||||
source_file: FileDescriptorProto
|
||||
parent: Union["MessageCompiler", OutputTemplate] = PLACEHOLDER
|
||||
proto_obj: DescriptorProto = PLACEHOLDER
|
||||
path: List[int] = PLACEHOLDER
|
||||
fields: List[Union["FieldCompiler", "MessageCompiler"]] = field(
|
||||
default_factory=list
|
||||
)
|
||||
deprecated: bool = field(default=False, init=False)
|
||||
builtins_types: Set[str] = field(default_factory=set)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
# Add message to output file
|
||||
if isinstance(self.parent, OutputTemplate):
|
||||
if isinstance(self, EnumDefinitionCompiler):
|
||||
self.output_file.enums.append(self)
|
||||
else:
|
||||
self.output_file.messages.append(self)
|
||||
self.deprecated = self.proto_obj.options.deprecated
|
||||
super().__post_init__()
|
||||
|
||||
@property
|
||||
def proto_name(self) -> str:
|
||||
return self.proto_obj.name
|
||||
|
||||
@property
|
||||
def py_name(self) -> str:
|
||||
return pythonize_class_name(self.proto_name)
|
||||
|
||||
@property
|
||||
def annotation(self) -> str:
|
||||
if self.repeated:
|
||||
return f"List[{self.py_name}]"
|
||||
return self.py_name
|
||||
|
||||
@property
|
||||
def deprecated_fields(self) -> Iterator[str]:
|
||||
for f in self.fields:
|
||||
if f.deprecated:
|
||||
yield f.py_name
|
||||
|
||||
@property
|
||||
def has_deprecated_fields(self) -> bool:
|
||||
return any(self.deprecated_fields)
|
||||
|
||||
@property
|
||||
def has_oneof_fields(self) -> bool:
|
||||
return any(isinstance(field, OneOfFieldCompiler) for field in self.fields)
|
||||
|
||||
@property
|
||||
def has_message_field(self) -> bool:
|
||||
return any(
|
||||
(
|
||||
field.proto_obj.type in PROTO_MESSAGE_TYPES
|
||||
for field in self.fields
|
||||
if isinstance(field.proto_obj, FieldDescriptorProto)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def is_map(
|
||||
proto_field_obj: FieldDescriptorProto, parent_message: DescriptorProto
|
||||
) -> bool:
|
||||
"""True if proto_field_obj is a map, otherwise False."""
|
||||
if proto_field_obj.type == FieldDescriptorProtoType.TYPE_MESSAGE:
|
||||
if not hasattr(parent_message, "nested_type"):
|
||||
return False
|
||||
|
||||
# This might be a map...
|
||||
message_type = proto_field_obj.type_name.split(".").pop().lower()
|
||||
map_entry = f"{proto_field_obj.name.replace('_', '').lower()}entry"
|
||||
if message_type == map_entry:
|
||||
for nested in parent_message.nested_type: # parent message
|
||||
if (
|
||||
nested.name.replace("_", "").lower() == map_entry
|
||||
and nested.options.map_entry
|
||||
):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def is_oneof(proto_field_obj: FieldDescriptorProto) -> bool:
|
||||
"""
|
||||
True if proto_field_obj is a OneOf, otherwise False.
|
||||
|
||||
.. warning::
|
||||
Becuase the message from protoc is defined in proto2, and betterproto works with
|
||||
proto3, and interpreting the FieldDescriptorProto.oneof_index field requires
|
||||
distinguishing between default and unset values (which proto3 doesn't support),
|
||||
we have to hack the generated FieldDescriptorProto class for this to work.
|
||||
The hack consists of setting group="oneof_index" in the field metadata,
|
||||
essentially making oneof_index the sole member of a one_of group, which allows
|
||||
us to tell whether it was set, via the which_one_of interface.
|
||||
"""
|
||||
|
||||
return which_one_of(proto_field_obj, "_oneof_index")[0] == "oneof_index"
|
||||
|
||||
|
||||
@dataclass
|
||||
class FieldCompiler(MessageCompiler):
|
||||
parent: MessageCompiler = PLACEHOLDER
|
||||
proto_obj: FieldDescriptorProto = PLACEHOLDER
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
# Add field to message
|
||||
self.parent.fields.append(self)
|
||||
# Check for new imports
|
||||
self.add_imports_to(self.output_file)
|
||||
super().__post_init__() # call FieldCompiler-> MessageCompiler __post_init__
|
||||
|
||||
def get_field_string(self, indent: int = 4) -> str:
|
||||
"""Construct string representation of this field as a field."""
|
||||
name = f"{self.py_name}"
|
||||
annotations = f": {self.annotation}"
|
||||
field_args = ", ".join(
|
||||
([""] + self.betterproto_field_args) if self.betterproto_field_args else []
|
||||
)
|
||||
betterproto_field_type = (
|
||||
f"betterproto.{self.field_type}_field({self.proto_obj.number}{field_args})"
|
||||
)
|
||||
if self.py_name in dir(builtins):
|
||||
self.parent.builtins_types.add(self.py_name)
|
||||
return f"{name}{annotations} = {betterproto_field_type}"
|
||||
|
||||
@property
|
||||
def betterproto_field_args(self) -> List[str]:
|
||||
args = []
|
||||
if self.field_wraps:
|
||||
args.append(f"wraps={self.field_wraps}")
|
||||
if self.optional:
|
||||
args.append(f"optional=True")
|
||||
return args
|
||||
|
||||
@property
|
||||
def datetime_imports(self) -> Set[str]:
|
||||
imports = set()
|
||||
annotation = self.annotation
|
||||
# FIXME: false positives - e.g. `MyDatetimedelta`
|
||||
if "timedelta" in annotation:
|
||||
imports.add("timedelta")
|
||||
if "datetime" in annotation:
|
||||
imports.add("datetime")
|
||||
return imports
|
||||
|
||||
@property
|
||||
def typing_imports(self) -> Set[str]:
|
||||
imports = set()
|
||||
annotation = self.annotation
|
||||
if "Optional[" in annotation:
|
||||
imports.add("Optional")
|
||||
if "List[" in annotation:
|
||||
imports.add("List")
|
||||
if "Dict[" in annotation:
|
||||
imports.add("Dict")
|
||||
return imports
|
||||
|
||||
@property
|
||||
def pydantic_imports(self) -> Set[str]:
|
||||
return set()
|
||||
|
||||
@property
|
||||
def use_builtins(self) -> bool:
|
||||
return self.py_type in self.parent.builtins_types or (
|
||||
self.py_type == self.py_name and self.py_name in dir(builtins)
|
||||
)
|
||||
|
||||
def add_imports_to(self, output_file: OutputTemplate) -> None:
|
||||
output_file.datetime_imports.update(self.datetime_imports)
|
||||
output_file.typing_imports.update(self.typing_imports)
|
||||
output_file.pydantic_imports.update(self.pydantic_imports)
|
||||
output_file.builtins_import = output_file.builtins_import or self.use_builtins
|
||||
|
||||
@property
|
||||
def field_wraps(self) -> Optional[str]:
|
||||
"""Returns betterproto wrapped field type or None."""
|
||||
match_wrapper = re.match(
|
||||
r"\.google\.protobuf\.(.+)Value$", self.proto_obj.type_name
|
||||
)
|
||||
if match_wrapper:
|
||||
wrapped_type = "TYPE_" + match_wrapper.group(1).upper()
|
||||
if hasattr(betterproto, wrapped_type):
|
||||
return f"betterproto.{wrapped_type}"
|
||||
return None
|
||||
|
||||
@property
|
||||
def repeated(self) -> bool:
|
||||
return (
|
||||
self.proto_obj.label == FieldDescriptorProtoLabel.LABEL_REPEATED
|
||||
and not is_map(self.proto_obj, self.parent)
|
||||
)
|
||||
|
||||
@property
|
||||
def optional(self) -> bool:
|
||||
return self.proto_obj.proto3_optional
|
||||
|
||||
@property
|
||||
def mutable(self) -> bool:
|
||||
"""True if the field is a mutable type, otherwise False."""
|
||||
return self.annotation.startswith(("List[", "Dict["))
|
||||
|
||||
@property
|
||||
def field_type(self) -> str:
|
||||
"""String representation of proto field type."""
|
||||
return (
|
||||
FieldDescriptorProtoType(self.proto_obj.type)
|
||||
.name.lower()
|
||||
.replace("type_", "")
|
||||
)
|
||||
|
||||
@property
|
||||
def default_value_string(self) -> str:
|
||||
"""Python representation of the default proto value."""
|
||||
if self.repeated:
|
||||
return "[]"
|
||||
if self.optional:
|
||||
return "None"
|
||||
if self.py_type == "int":
|
||||
return "0"
|
||||
if self.py_type == "float":
|
||||
return "0.0"
|
||||
elif self.py_type == "bool":
|
||||
return "False"
|
||||
elif self.py_type == "str":
|
||||
return '""'
|
||||
elif self.py_type == "bytes":
|
||||
return 'b""'
|
||||
elif self.field_type == "enum":
|
||||
enum_proto_obj_name = self.proto_obj.type_name.split(".").pop()
|
||||
enum = next(
|
||||
e
|
||||
for e in self.output_file.enums
|
||||
if e.proto_obj.name == enum_proto_obj_name
|
||||
)
|
||||
return enum.default_value_string
|
||||
else:
|
||||
# Message type
|
||||
return "None"
|
||||
|
||||
@property
|
||||
def packed(self) -> bool:
|
||||
"""True if the wire representation is a packed format."""
|
||||
return self.repeated and self.proto_obj.type in PROTO_PACKED_TYPES
|
||||
|
||||
@property
|
||||
def py_name(self) -> str:
|
||||
"""Pythonized name."""
|
||||
return pythonize_field_name(self.proto_name)
|
||||
|
||||
@property
|
||||
def proto_name(self) -> str:
|
||||
"""Original protobuf name."""
|
||||
return self.proto_obj.name
|
||||
|
||||
@property
|
||||
def py_type(self) -> str:
|
||||
"""String representation of Python type."""
|
||||
if self.proto_obj.type in PROTO_FLOAT_TYPES:
|
||||
return "float"
|
||||
elif self.proto_obj.type in PROTO_INT_TYPES:
|
||||
return "int"
|
||||
elif self.proto_obj.type in PROTO_BOOL_TYPES:
|
||||
return "bool"
|
||||
elif self.proto_obj.type in PROTO_STR_TYPES:
|
||||
return "str"
|
||||
elif self.proto_obj.type in PROTO_BYTES_TYPES:
|
||||
return "bytes"
|
||||
elif self.proto_obj.type in PROTO_MESSAGE_TYPES:
|
||||
# Type referencing another defined Message or a named enum
|
||||
return get_type_reference(
|
||||
package=self.output_file.package,
|
||||
imports=self.output_file.imports,
|
||||
source_type=self.proto_obj.type_name,
|
||||
)
|
||||
else:
|
||||
raise NotImplementedError(f"Unknown type {self.proto_obj.type}")
|
||||
|
||||
@property
|
||||
def annotation(self) -> str:
|
||||
py_type = self.py_type
|
||||
if self.use_builtins:
|
||||
py_type = f"builtins.{py_type}"
|
||||
if self.repeated:
|
||||
return f"List[{py_type}]"
|
||||
if self.optional:
|
||||
return f"Optional[{py_type}]"
|
||||
return py_type
|
||||
|
||||
|
||||
@dataclass
|
||||
class OneOfFieldCompiler(FieldCompiler):
|
||||
@property
|
||||
def betterproto_field_args(self) -> List[str]:
|
||||
args = super().betterproto_field_args
|
||||
group = self.parent.proto_obj.oneof_decl[self.proto_obj.oneof_index].name
|
||||
args.append(f'group="{group}"')
|
||||
return args
|
||||
|
||||
|
||||
@dataclass
|
||||
class PydanticOneOfFieldCompiler(OneOfFieldCompiler):
|
||||
@property
|
||||
def optional(self) -> bool:
|
||||
# Force the optional to be True. This will allow the pydantic dataclass
|
||||
# to validate the object correctly by allowing the field to be let empty.
|
||||
# We add a pydantic validator later to ensure exactly one field is defined.
|
||||
return True
|
||||
|
||||
@property
|
||||
def pydantic_imports(self) -> Set[str]:
|
||||
return {"root_validator"}
|
||||
|
||||
|
||||
@dataclass
|
||||
class MapEntryCompiler(FieldCompiler):
|
||||
py_k_type: Type = PLACEHOLDER
|
||||
py_v_type: Type = PLACEHOLDER
|
||||
proto_k_type: str = PLACEHOLDER
|
||||
proto_v_type: str = PLACEHOLDER
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
"""Explore nested types and set k_type and v_type if unset."""
|
||||
map_entry = f"{self.proto_obj.name.replace('_', '').lower()}entry"
|
||||
for nested in self.parent.proto_obj.nested_type:
|
||||
if (
|
||||
nested.name.replace("_", "").lower() == map_entry
|
||||
and nested.options.map_entry
|
||||
):
|
||||
# Get Python types
|
||||
self.py_k_type = FieldCompiler(
|
||||
source_file=self.source_file,
|
||||
parent=self,
|
||||
proto_obj=nested.field[0], # key
|
||||
).py_type
|
||||
self.py_v_type = FieldCompiler(
|
||||
source_file=self.source_file,
|
||||
parent=self,
|
||||
proto_obj=nested.field[1], # value
|
||||
).py_type
|
||||
|
||||
# Get proto types
|
||||
self.proto_k_type = FieldDescriptorProtoType(nested.field[0].type).name
|
||||
self.proto_v_type = FieldDescriptorProtoType(nested.field[1].type).name
|
||||
super().__post_init__() # call FieldCompiler-> MessageCompiler __post_init__
|
||||
|
||||
@property
|
||||
def betterproto_field_args(self) -> List[str]:
|
||||
return [f"betterproto.{self.proto_k_type}", f"betterproto.{self.proto_v_type}"]
|
||||
|
||||
@property
|
||||
def field_type(self) -> str:
|
||||
return "map"
|
||||
|
||||
@property
|
||||
def annotation(self) -> str:
|
||||
return f"Dict[{self.py_k_type}, {self.py_v_type}]"
|
||||
|
||||
@property
|
||||
def repeated(self) -> bool:
|
||||
return False # maps cannot be repeated
|
||||
|
||||
|
||||
@dataclass
|
||||
class EnumDefinitionCompiler(MessageCompiler):
|
||||
"""Representation of a proto Enum definition."""
|
||||
|
||||
proto_obj: EnumDescriptorProto = PLACEHOLDER
|
||||
entries: List["EnumDefinitionCompiler.EnumEntry"] = PLACEHOLDER
|
||||
|
||||
@dataclass(unsafe_hash=True)
|
||||
class EnumEntry:
|
||||
"""Representation of an Enum entry."""
|
||||
|
||||
name: str
|
||||
value: int
|
||||
comment: str
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
# Get entries/allowed values for this Enum
|
||||
self.entries = [
|
||||
self.EnumEntry(
|
||||
name=sanitize_name(entry_proto_value.name),
|
||||
value=entry_proto_value.number,
|
||||
comment=get_comment(
|
||||
proto_file=self.source_file, path=self.path + [2, entry_number]
|
||||
),
|
||||
)
|
||||
for entry_number, entry_proto_value in enumerate(self.proto_obj.value)
|
||||
]
|
||||
super().__post_init__() # call MessageCompiler __post_init__
|
||||
|
||||
@property
|
||||
def default_value_string(self) -> str:
|
||||
"""Python representation of the default value for Enums.
|
||||
|
||||
As per the spec, this is the first value of the Enum.
|
||||
"""
|
||||
return str(self.entries[0].value) # ideally, should ALWAYS be int(0)!
|
||||
|
||||
|
||||
@dataclass
|
||||
class ServiceCompiler(ProtoContentBase):
|
||||
parent: OutputTemplate = PLACEHOLDER
|
||||
proto_obj: DescriptorProto = PLACEHOLDER
|
||||
path: List[int] = PLACEHOLDER
|
||||
methods: List["ServiceMethodCompiler"] = field(default_factory=list)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
# Add service to output file
|
||||
self.output_file.services.append(self)
|
||||
self.output_file.typing_imports.add("Dict")
|
||||
super().__post_init__() # check for unset fields
|
||||
|
||||
@property
|
||||
def proto_name(self) -> str:
|
||||
return self.proto_obj.name
|
||||
|
||||
@property
|
||||
def py_name(self) -> str:
|
||||
return pythonize_class_name(self.proto_name)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ServiceMethodCompiler(ProtoContentBase):
|
||||
parent: ServiceCompiler
|
||||
proto_obj: MethodDescriptorProto
|
||||
path: List[int] = PLACEHOLDER
|
||||
comment_indent: int = 8
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
# Add method to service
|
||||
self.parent.methods.append(self)
|
||||
|
||||
# Check for imports
|
||||
if "Optional" in self.py_output_message_type:
|
||||
self.output_file.typing_imports.add("Optional")
|
||||
|
||||
# Check for Async imports
|
||||
if self.client_streaming:
|
||||
self.output_file.typing_imports.add("AsyncIterable")
|
||||
self.output_file.typing_imports.add("Iterable")
|
||||
self.output_file.typing_imports.add("Union")
|
||||
|
||||
# Required by both client and server
|
||||
if self.client_streaming or self.server_streaming:
|
||||
self.output_file.typing_imports.add("AsyncIterator")
|
||||
|
||||
# add imports required for request arguments timeout, deadline and metadata
|
||||
self.output_file.typing_imports.add("Optional")
|
||||
self.output_file.imports_type_checking_only.add("import grpclib.server")
|
||||
self.output_file.imports_type_checking_only.add(
|
||||
"from betterproto.grpc.grpclib_client import MetadataLike"
|
||||
)
|
||||
self.output_file.imports_type_checking_only.add(
|
||||
"from grpclib.metadata import Deadline"
|
||||
)
|
||||
|
||||
super().__post_init__() # check for unset fields
|
||||
|
||||
@property
|
||||
def py_name(self) -> str:
|
||||
"""Pythonized method name."""
|
||||
return pythonize_method_name(self.proto_obj.name)
|
||||
|
||||
@property
|
||||
def proto_name(self) -> str:
|
||||
"""Original protobuf name."""
|
||||
return self.proto_obj.name
|
||||
|
||||
@property
|
||||
def route(self) -> str:
|
||||
package_part = (
|
||||
f"{self.output_file.package}." if self.output_file.package else ""
|
||||
)
|
||||
return f"/{package_part}{self.parent.proto_name}/{self.proto_name}"
|
||||
|
||||
@property
|
||||
def py_input_message(self) -> Optional[MessageCompiler]:
|
||||
"""Find the input message object.
|
||||
|
||||
Returns
|
||||
-------
|
||||
Optional[MessageCompiler]
|
||||
Method instance representing the input message.
|
||||
If not input message could be found or there are no
|
||||
input messages, None is returned.
|
||||
"""
|
||||
package, name = parse_source_type_name(self.proto_obj.input_type)
|
||||
|
||||
# Nested types are currently flattened without dots.
|
||||
# Todo: keep a fully quantified name in types, that is
|
||||
# comparable with method.input_type
|
||||
for msg in self.request.all_messages:
|
||||
if (
|
||||
msg.py_name == pythonize_class_name(name.replace(".", ""))
|
||||
and msg.output_file.package == package
|
||||
):
|
||||
return msg
|
||||
return None
|
||||
|
||||
@property
|
||||
def py_input_message_type(self) -> str:
|
||||
"""String representation of the Python type corresponding to the
|
||||
input message.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
String representation of the Python type corresponding to the input message.
|
||||
"""
|
||||
return get_type_reference(
|
||||
package=self.output_file.package,
|
||||
imports=self.output_file.imports,
|
||||
source_type=self.proto_obj.input_type,
|
||||
unwrap=False,
|
||||
).strip('"')
|
||||
|
||||
@property
|
||||
def py_input_message_param(self) -> str:
|
||||
"""Param name corresponding to py_input_message_type.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
Param name corresponding to py_input_message_type.
|
||||
"""
|
||||
return pythonize_field_name(self.py_input_message_type)
|
||||
|
||||
@property
|
||||
def py_output_message_type(self) -> str:
|
||||
"""String representation of the Python type corresponding to the
|
||||
output message.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
String representation of the Python type corresponding to the output message.
|
||||
"""
|
||||
return get_type_reference(
|
||||
package=self.output_file.package,
|
||||
imports=self.output_file.imports,
|
||||
source_type=self.proto_obj.output_type,
|
||||
unwrap=False,
|
||||
).strip('"')
|
||||
|
||||
@property
|
||||
def client_streaming(self) -> bool:
|
||||
return self.proto_obj.client_streaming
|
||||
|
||||
@property
|
||||
def server_streaming(self) -> bool:
|
||||
return self.proto_obj.server_streaming
|
||||
221
src/betterproto/plugin/parser.py
Normal file
221
src/betterproto/plugin/parser.py
Normal file
@@ -0,0 +1,221 @@
|
||||
import pathlib
|
||||
import sys
|
||||
from typing import (
|
||||
Generator,
|
||||
List,
|
||||
Set,
|
||||
Tuple,
|
||||
Union,
|
||||
)
|
||||
|
||||
from betterproto.lib.google.protobuf import (
|
||||
DescriptorProto,
|
||||
EnumDescriptorProto,
|
||||
FieldDescriptorProto,
|
||||
FileDescriptorProto,
|
||||
ServiceDescriptorProto,
|
||||
)
|
||||
from betterproto.lib.google.protobuf.compiler import (
|
||||
CodeGeneratorRequest,
|
||||
CodeGeneratorResponse,
|
||||
CodeGeneratorResponseFeature,
|
||||
CodeGeneratorResponseFile,
|
||||
)
|
||||
|
||||
from .compiler import outputfile_compiler
|
||||
from .models import (
|
||||
EnumDefinitionCompiler,
|
||||
FieldCompiler,
|
||||
MapEntryCompiler,
|
||||
MessageCompiler,
|
||||
OneOfFieldCompiler,
|
||||
OutputTemplate,
|
||||
PluginRequestCompiler,
|
||||
PydanticOneOfFieldCompiler,
|
||||
ServiceCompiler,
|
||||
ServiceMethodCompiler,
|
||||
is_map,
|
||||
is_oneof,
|
||||
)
|
||||
|
||||
|
||||
def traverse(
|
||||
proto_file: FileDescriptorProto,
|
||||
) -> Generator[
|
||||
Tuple[Union[EnumDescriptorProto, DescriptorProto], List[int]], None, None
|
||||
]:
|
||||
# Todo: Keep information about nested hierarchy
|
||||
def _traverse(
|
||||
path: List[int],
|
||||
items: Union[List[EnumDescriptorProto], List[DescriptorProto]],
|
||||
prefix: str = "",
|
||||
) -> Generator[
|
||||
Tuple[Union[EnumDescriptorProto, DescriptorProto], List[int]], None, None
|
||||
]:
|
||||
for i, item in enumerate(items):
|
||||
# Adjust the name since we flatten the hierarchy.
|
||||
# Todo: don't change the name, but include full name in returned tuple
|
||||
item.name = next_prefix = f"{prefix}_{item.name}"
|
||||
yield item, [*path, i]
|
||||
|
||||
if isinstance(item, DescriptorProto):
|
||||
# Get nested types.
|
||||
yield from _traverse([*path, i, 4], item.enum_type, next_prefix)
|
||||
yield from _traverse([*path, i, 3], item.nested_type, next_prefix)
|
||||
|
||||
yield from _traverse([5], proto_file.enum_type)
|
||||
yield from _traverse([4], proto_file.message_type)
|
||||
|
||||
|
||||
def generate_code(request: CodeGeneratorRequest) -> CodeGeneratorResponse:
|
||||
response = CodeGeneratorResponse()
|
||||
|
||||
plugin_options = request.parameter.split(",") if request.parameter else []
|
||||
response.supported_features = CodeGeneratorResponseFeature.FEATURE_PROTO3_OPTIONAL
|
||||
|
||||
request_data = PluginRequestCompiler(plugin_request_obj=request)
|
||||
# Gather output packages
|
||||
for proto_file in request.proto_file:
|
||||
output_package_name = proto_file.package
|
||||
if output_package_name not in request_data.output_packages:
|
||||
# Create a new output if there is no output for this package
|
||||
request_data.output_packages[output_package_name] = OutputTemplate(
|
||||
parent_request=request_data, package_proto_obj=proto_file
|
||||
)
|
||||
# Add this input file to the output corresponding to this package
|
||||
request_data.output_packages[output_package_name].input_files.append(proto_file)
|
||||
|
||||
if (
|
||||
proto_file.package == "google.protobuf"
|
||||
and "INCLUDE_GOOGLE" not in plugin_options
|
||||
):
|
||||
# If not INCLUDE_GOOGLE,
|
||||
# skip outputting Google's well-known types
|
||||
request_data.output_packages[output_package_name].output = False
|
||||
|
||||
if "pydantic_dataclasses" in plugin_options:
|
||||
request_data.output_packages[
|
||||
output_package_name
|
||||
].pydantic_dataclasses = True
|
||||
|
||||
# Read Messages and Enums
|
||||
# We need to read Messages before Services in so that we can
|
||||
# get the references to input/output messages for each service
|
||||
for output_package_name, output_package in request_data.output_packages.items():
|
||||
for proto_input_file in output_package.input_files:
|
||||
for item, path in traverse(proto_input_file):
|
||||
read_protobuf_type(
|
||||
source_file=proto_input_file,
|
||||
item=item,
|
||||
path=path,
|
||||
output_package=output_package,
|
||||
)
|
||||
|
||||
# Read Services
|
||||
for output_package_name, output_package in request_data.output_packages.items():
|
||||
for proto_input_file in output_package.input_files:
|
||||
for index, service in enumerate(proto_input_file.service):
|
||||
read_protobuf_service(service, index, output_package)
|
||||
|
||||
# Generate output files
|
||||
output_paths: Set[pathlib.Path] = set()
|
||||
for output_package_name, output_package in request_data.output_packages.items():
|
||||
if not output_package.output:
|
||||
continue
|
||||
|
||||
# Add files to the response object
|
||||
output_path = pathlib.Path(*output_package_name.split("."), "__init__.py")
|
||||
output_paths.add(output_path)
|
||||
|
||||
response.file.append(
|
||||
CodeGeneratorResponseFile(
|
||||
name=str(output_path),
|
||||
# Render and then format the output file
|
||||
content=outputfile_compiler(output_file=output_package),
|
||||
)
|
||||
)
|
||||
|
||||
# Make each output directory a package with __init__ file
|
||||
init_files = {
|
||||
directory.joinpath("__init__.py")
|
||||
for path in output_paths
|
||||
for directory in path.parents
|
||||
if not directory.joinpath("__init__.py").exists()
|
||||
} - output_paths
|
||||
|
||||
for init_file in init_files:
|
||||
response.file.append(CodeGeneratorResponseFile(name=str(init_file)))
|
||||
|
||||
for output_package_name in sorted(output_paths.union(init_files)):
|
||||
print(f"Writing {output_package_name}", file=sys.stderr)
|
||||
|
||||
return response
|
||||
|
||||
|
||||
def _make_one_of_field_compiler(
|
||||
output_package: OutputTemplate,
|
||||
source_file: "FileDescriptorProto",
|
||||
parent: MessageCompiler,
|
||||
proto_obj: "FieldDescriptorProto",
|
||||
path: List[int],
|
||||
) -> FieldCompiler:
|
||||
pydantic = output_package.pydantic_dataclasses
|
||||
Cls = PydanticOneOfFieldCompiler if pydantic else OneOfFieldCompiler
|
||||
return Cls(
|
||||
source_file=source_file,
|
||||
parent=parent,
|
||||
proto_obj=proto_obj,
|
||||
path=path,
|
||||
)
|
||||
|
||||
|
||||
def read_protobuf_type(
|
||||
item: DescriptorProto,
|
||||
path: List[int],
|
||||
source_file: "FileDescriptorProto",
|
||||
output_package: OutputTemplate,
|
||||
) -> None:
|
||||
if isinstance(item, DescriptorProto):
|
||||
if item.options.map_entry:
|
||||
# Skip generated map entry messages since we just use dicts
|
||||
return
|
||||
# Process Message
|
||||
message_data = MessageCompiler(
|
||||
source_file=source_file, parent=output_package, proto_obj=item, path=path
|
||||
)
|
||||
for index, field in enumerate(item.field):
|
||||
if is_map(field, item):
|
||||
MapEntryCompiler(
|
||||
source_file=source_file,
|
||||
parent=message_data,
|
||||
proto_obj=field,
|
||||
path=path + [2, index],
|
||||
)
|
||||
elif is_oneof(field):
|
||||
_make_one_of_field_compiler(
|
||||
output_package, source_file, message_data, field, path + [2, index]
|
||||
)
|
||||
else:
|
||||
FieldCompiler(
|
||||
source_file=source_file,
|
||||
parent=message_data,
|
||||
proto_obj=field,
|
||||
path=path + [2, index],
|
||||
)
|
||||
elif isinstance(item, EnumDescriptorProto):
|
||||
# Enum
|
||||
EnumDefinitionCompiler(
|
||||
source_file=source_file, parent=output_package, proto_obj=item, path=path
|
||||
)
|
||||
|
||||
|
||||
def read_protobuf_service(
|
||||
service: ServiceDescriptorProto, index: int, output_package: OutputTemplate
|
||||
) -> None:
|
||||
service_data = ServiceCompiler(
|
||||
parent=output_package, proto_obj=service, path=[6, index]
|
||||
)
|
||||
for j, method in enumerate(service.method):
|
||||
ServiceMethodCompiler(
|
||||
parent=service_data, proto_obj=method, path=[6, index, 2, j]
|
||||
)
|
||||
2
src/betterproto/plugin/plugin.bat
Normal file
2
src/betterproto/plugin/plugin.bat
Normal file
@@ -0,0 +1,2 @@
|
||||
@SET plugin_dir=%~dp0
|
||||
@python -m %plugin_dir% %*
|
||||
256
src/betterproto/templates/template.py.j2
Normal file
256
src/betterproto/templates/template.py.j2
Normal file
@@ -0,0 +1,256 @@
|
||||
# Generated by the protocol buffer compiler. DO NOT EDIT!
|
||||
# sources: {{ ', '.join(output_file.input_filenames) }}
|
||||
# plugin: python-betterproto
|
||||
# This file has been @generated
|
||||
{% for i in output_file.python_module_imports|sort %}
|
||||
import {{ i }}
|
||||
{% endfor %}
|
||||
|
||||
{% if output_file.pydantic_dataclasses %}
|
||||
from typing import TYPE_CHECKING
|
||||
if TYPE_CHECKING:
|
||||
from dataclasses import dataclass
|
||||
else:
|
||||
from pydantic.dataclasses import dataclass
|
||||
{%- else -%}
|
||||
from dataclasses import dataclass
|
||||
{% endif %}
|
||||
|
||||
{% if output_file.datetime_imports %}
|
||||
from datetime import {% for i in output_file.datetime_imports|sort %}{{ i }}{% if not loop.last %}, {% endif %}{% endfor %}
|
||||
|
||||
{% endif%}
|
||||
{% if output_file.typing_imports %}
|
||||
from typing import {% for i in output_file.typing_imports|sort %}{{ i }}{% if not loop.last %}, {% endif %}{% endfor %}
|
||||
|
||||
{% endif %}
|
||||
|
||||
{% if output_file.pydantic_imports %}
|
||||
from pydantic import {% for i in output_file.pydantic_imports|sort %}{{ i }}{% if not loop.last %}, {% endif %}{% endfor %}
|
||||
|
||||
{% endif %}
|
||||
|
||||
import betterproto
|
||||
{% if output_file.services %}
|
||||
from betterproto.grpc.grpclib_server import ServiceBase
|
||||
import grpclib
|
||||
{% endif %}
|
||||
|
||||
{% for i in output_file.imports|sort %}
|
||||
{{ i }}
|
||||
{% endfor %}
|
||||
|
||||
{% if output_file.imports_type_checking_only %}
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
{% for i in output_file.imports_type_checking_only|sort %} {{ i }}
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
{% if output_file.enums %}{% for enum in output_file.enums %}
|
||||
class {{ enum.py_name }}(betterproto.Enum):
|
||||
{% if enum.comment %}
|
||||
{{ enum.comment }}
|
||||
|
||||
{% endif %}
|
||||
{% for entry in enum.entries %}
|
||||
{{ entry.name }} = {{ entry.value }}
|
||||
{% if entry.comment %}
|
||||
{{ entry.comment }}
|
||||
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
|
||||
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% for message in output_file.messages %}
|
||||
@dataclass(eq=False, repr=False)
|
||||
class {{ message.py_name }}(betterproto.Message):
|
||||
{% if message.comment %}
|
||||
{{ message.comment }}
|
||||
|
||||
{% endif %}
|
||||
{% for field in message.fields %}
|
||||
{{ field.get_field_string() }}
|
||||
{% if field.comment %}
|
||||
{{ field.comment }}
|
||||
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% if not message.fields %}
|
||||
pass
|
||||
{% endif %}
|
||||
|
||||
{% if message.deprecated or message.has_deprecated_fields %}
|
||||
def __post_init__(self) -> None:
|
||||
{% if message.deprecated %}
|
||||
warnings.warn("{{ message.py_name }} is deprecated", DeprecationWarning)
|
||||
{% endif %}
|
||||
super().__post_init__()
|
||||
{% for field in message.deprecated_fields %}
|
||||
if self.is_set("{{ field }}"):
|
||||
warnings.warn("{{ message.py_name }}.{{ field }} is deprecated", DeprecationWarning)
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
{% if output_file.pydantic_dataclasses and message.has_oneof_fields %}
|
||||
@root_validator()
|
||||
def check_oneof(cls, values):
|
||||
return cls._validate_field_groups(values)
|
||||
{% endif %}
|
||||
|
||||
{% endfor %}
|
||||
{% for service in output_file.services %}
|
||||
class {{ service.py_name }}Stub(betterproto.ServiceStub):
|
||||
{% if service.comment %}
|
||||
{{ service.comment }}
|
||||
|
||||
{% elif not service.methods %}
|
||||
pass
|
||||
{% endif %}
|
||||
{% for method in service.methods %}
|
||||
async def {{ method.py_name }}(self
|
||||
{%- if not method.client_streaming -%}
|
||||
{%- if method.py_input_message -%}, {{ method.py_input_message_param }}: "{{ method.py_input_message_type }}"{%- endif -%}
|
||||
{%- else -%}
|
||||
{# Client streaming: need a request iterator instead #}
|
||||
, {{ method.py_input_message_param }}_iterator: Union[AsyncIterable["{{ method.py_input_message_type }}"], Iterable["{{ method.py_input_message_type }}"]]
|
||||
{%- endif -%}
|
||||
,
|
||||
*
|
||||
, timeout: Optional[float] = None
|
||||
, deadline: Optional["Deadline"] = None
|
||||
, metadata: Optional["MetadataLike"] = None
|
||||
) -> {% if method.server_streaming %}AsyncIterator["{{ method.py_output_message_type }}"]{% else %}"{{ method.py_output_message_type }}"{% endif %}:
|
||||
{% if method.comment %}
|
||||
{{ method.comment }}
|
||||
|
||||
{% endif %}
|
||||
{% if method.server_streaming %}
|
||||
{% if method.client_streaming %}
|
||||
async for response in self._stream_stream(
|
||||
"{{ method.route }}",
|
||||
{{ method.py_input_message_param }}_iterator,
|
||||
{{ method.py_input_message_type }},
|
||||
{{ method.py_output_message_type.strip('"') }},
|
||||
timeout=timeout,
|
||||
deadline=deadline,
|
||||
metadata=metadata,
|
||||
):
|
||||
yield response
|
||||
{% else %}{# i.e. not client streaming #}
|
||||
async for response in self._unary_stream(
|
||||
"{{ method.route }}",
|
||||
{{ method.py_input_message_param }},
|
||||
{{ method.py_output_message_type.strip('"') }},
|
||||
timeout=timeout,
|
||||
deadline=deadline,
|
||||
metadata=metadata,
|
||||
):
|
||||
yield response
|
||||
|
||||
{% endif %}{# if client streaming #}
|
||||
{% else %}{# i.e. not server streaming #}
|
||||
{% if method.client_streaming %}
|
||||
return await self._stream_unary(
|
||||
"{{ method.route }}",
|
||||
{{ method.py_input_message_param }}_iterator,
|
||||
{{ method.py_input_message_type }},
|
||||
{{ method.py_output_message_type.strip('"') }},
|
||||
timeout=timeout,
|
||||
deadline=deadline,
|
||||
metadata=metadata,
|
||||
)
|
||||
{% else %}{# i.e. not client streaming #}
|
||||
return await self._unary_unary(
|
||||
"{{ method.route }}",
|
||||
{{ method.py_input_message_param }},
|
||||
{{ method.py_output_message_type.strip('"') }},
|
||||
timeout=timeout,
|
||||
deadline=deadline,
|
||||
metadata=metadata,
|
||||
)
|
||||
{% endif %}{# client streaming #}
|
||||
{% endif %}
|
||||
|
||||
{% endfor %}
|
||||
{% endfor %}
|
||||
|
||||
{% for service in output_file.services %}
|
||||
class {{ service.py_name }}Base(ServiceBase):
|
||||
{% if service.comment %}
|
||||
{{ service.comment }}
|
||||
|
||||
{% endif %}
|
||||
|
||||
{% for method in service.methods %}
|
||||
async def {{ method.py_name }}(self
|
||||
{%- if not method.client_streaming -%}
|
||||
{%- if method.py_input_message -%}, {{ method.py_input_message_param }}: "{{ method.py_input_message_type }}"{%- endif -%}
|
||||
{%- else -%}
|
||||
{# Client streaming: need a request iterator instead #}
|
||||
, {{ method.py_input_message_param }}_iterator: AsyncIterator["{{ method.py_input_message_type }}"]
|
||||
{%- endif -%}
|
||||
) -> {% if method.server_streaming %}AsyncIterator["{{ method.py_output_message_type }}"]{% else %}"{{ method.py_output_message_type }}"{% endif %}:
|
||||
{% if method.comment %}
|
||||
{{ method.comment }}
|
||||
|
||||
{% endif %}
|
||||
raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
|
||||
{% if method.server_streaming %}
|
||||
yield {{ method.py_output_message_type }}()
|
||||
{% endif %}
|
||||
|
||||
{% endfor %}
|
||||
|
||||
{% for method in service.methods %}
|
||||
async def __rpc_{{ method.py_name }}(self, stream: "grpclib.server.Stream[{{ method.py_input_message_type }}, {{ method.py_output_message_type }}]") -> None:
|
||||
{% if not method.client_streaming %}
|
||||
request = await stream.recv_message()
|
||||
{% else %}
|
||||
request = stream.__aiter__()
|
||||
{% endif %}
|
||||
{% if not method.server_streaming %}
|
||||
response = await self.{{ method.py_name }}(request)
|
||||
await stream.send_message(response)
|
||||
{% else %}
|
||||
await self._call_rpc_handler_server_stream(
|
||||
self.{{ method.py_name }},
|
||||
stream,
|
||||
request,
|
||||
)
|
||||
{% endif %}
|
||||
|
||||
{% endfor %}
|
||||
|
||||
def __mapping__(self) -> Dict[str, grpclib.const.Handler]:
|
||||
return {
|
||||
{% for method in service.methods %}
|
||||
"{{ method.route }}": grpclib.const.Handler(
|
||||
self.__rpc_{{ method.py_name }},
|
||||
{% if not method.client_streaming and not method.server_streaming %}
|
||||
grpclib.const.Cardinality.UNARY_UNARY,
|
||||
{% elif not method.client_streaming and method.server_streaming %}
|
||||
grpclib.const.Cardinality.UNARY_STREAM,
|
||||
{% elif method.client_streaming and not method.server_streaming %}
|
||||
grpclib.const.Cardinality.STREAM_UNARY,
|
||||
{% else %}
|
||||
grpclib.const.Cardinality.STREAM_STREAM,
|
||||
{% endif %}
|
||||
{{ method.py_input_message_type }},
|
||||
{{ method.py_output_message_type }},
|
||||
),
|
||||
{% endfor %}
|
||||
}
|
||||
|
||||
{% endfor %}
|
||||
|
||||
{% if output_file.pydantic_dataclasses %}
|
||||
{% for message in output_file.messages %}
|
||||
{% if message.has_message_field %}
|
||||
{{ message.py_name }}.__pydantic_model__.update_forward_refs() # type: ignore
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
@@ -50,7 +50,7 @@ You can add multiple `.proto` files to the test case, as long as one file matche
|
||||
`test_<name>.py` — *Custom test to validate specific aspects of the generated class*
|
||||
|
||||
```python
|
||||
from betterproto.tests.output_betterproto.bool.bool import Test
|
||||
from tests.output_betterproto.bool.bool import Test
|
||||
|
||||
def test_value():
|
||||
message = Test()
|
||||
@@ -1,3 +1,6 @@
|
||||
import copy
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@@ -10,3 +13,10 @@ def pytest_addoption(parser):
|
||||
@pytest.fixture(scope="session")
|
||||
def repeat(request):
|
||||
return request.config.getoption("repeat")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def reset_sys_path():
|
||||
original = copy.deepcopy(sys.path)
|
||||
yield
|
||||
sys.path = original
|
||||
@@ -1,21 +1,22 @@
|
||||
#!/usr/bin/env python
|
||||
import asyncio
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Set
|
||||
|
||||
from betterproto.tests.util import (
|
||||
from tests.util import (
|
||||
get_directories,
|
||||
inputs_path,
|
||||
output_path_betterproto,
|
||||
output_path_betterproto_pydantic,
|
||||
output_path_reference,
|
||||
protoc_plugin,
|
||||
protoc_reference,
|
||||
protoc,
|
||||
)
|
||||
|
||||
|
||||
# Force pure-python implementation instead of C++, otherwise imports
|
||||
# break things because we can't properly reset the symbol database.
|
||||
os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python"
|
||||
@@ -61,13 +62,15 @@ async def generate(whitelist: Set[str], verbose: bool):
|
||||
if result != 0:
|
||||
failed_test_cases.append(test_case_name)
|
||||
|
||||
if failed_test_cases:
|
||||
if len(failed_test_cases) > 0:
|
||||
sys.stderr.write(
|
||||
"\n\033[31;1;4mFailed to generate the following test cases:\033[0m\n"
|
||||
)
|
||||
for failed_test_case in failed_test_cases:
|
||||
sys.stderr.write(f"- {failed_test_case}\n")
|
||||
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
async def generate_test_case_output(
|
||||
test_case_input_path: Path, test_case_name: str, verbose: bool
|
||||
@@ -77,10 +80,12 @@ async def generate_test_case_output(
|
||||
"""
|
||||
|
||||
test_case_output_path_reference = output_path_reference.joinpath(test_case_name)
|
||||
test_case_output_path_betterproto = output_path_betterproto.joinpath(test_case_name)
|
||||
test_case_output_path_betterproto = output_path_betterproto
|
||||
test_case_output_path_betterproto_pyd = output_path_betterproto_pydantic
|
||||
|
||||
os.makedirs(test_case_output_path_reference, exist_ok=True)
|
||||
os.makedirs(test_case_output_path_betterproto, exist_ok=True)
|
||||
os.makedirs(test_case_output_path_betterproto_pyd, exist_ok=True)
|
||||
|
||||
clear_directory(test_case_output_path_reference)
|
||||
clear_directory(test_case_output_path_betterproto)
|
||||
@@ -88,28 +93,72 @@ async def generate_test_case_output(
|
||||
(
|
||||
(ref_out, ref_err, ref_code),
|
||||
(plg_out, plg_err, plg_code),
|
||||
(plg_out_pyd, plg_err_pyd, plg_code_pyd),
|
||||
) = await asyncio.gather(
|
||||
protoc_reference(test_case_input_path, test_case_output_path_reference),
|
||||
protoc_plugin(test_case_input_path, test_case_output_path_betterproto),
|
||||
protoc(test_case_input_path, test_case_output_path_reference, True),
|
||||
protoc(test_case_input_path, test_case_output_path_betterproto, False),
|
||||
protoc(
|
||||
test_case_input_path, test_case_output_path_betterproto_pyd, False, True
|
||||
),
|
||||
)
|
||||
|
||||
message = f"Generated output for {test_case_name!r}"
|
||||
if verbose:
|
||||
print(f"\033[31;1;4m{message}\033[0m")
|
||||
if ref_out:
|
||||
sys.stdout.buffer.write(ref_out)
|
||||
if ref_err:
|
||||
sys.stderr.buffer.write(ref_err)
|
||||
if plg_out:
|
||||
sys.stdout.buffer.write(plg_out)
|
||||
if plg_err:
|
||||
sys.stderr.buffer.write(plg_err)
|
||||
sys.stdout.buffer.flush()
|
||||
sys.stderr.buffer.flush()
|
||||
if ref_code == 0:
|
||||
print(f"\033[31;1;4mGenerated reference output for {test_case_name!r}\033[0m")
|
||||
else:
|
||||
print(message)
|
||||
print(
|
||||
f"\033[31;1;4mFailed to generate reference output for {test_case_name!r}\033[0m"
|
||||
)
|
||||
|
||||
return max(ref_code, plg_code)
|
||||
if verbose:
|
||||
if ref_out:
|
||||
print("Reference stdout:")
|
||||
sys.stdout.buffer.write(ref_out)
|
||||
sys.stdout.buffer.flush()
|
||||
|
||||
if ref_err:
|
||||
print("Reference stderr:")
|
||||
sys.stderr.buffer.write(ref_err)
|
||||
sys.stderr.buffer.flush()
|
||||
|
||||
if plg_code == 0:
|
||||
print(f"\033[31;1;4mGenerated plugin output for {test_case_name!r}\033[0m")
|
||||
else:
|
||||
print(
|
||||
f"\033[31;1;4mFailed to generate plugin output for {test_case_name!r}\033[0m"
|
||||
)
|
||||
|
||||
if verbose:
|
||||
if plg_out:
|
||||
print("Plugin stdout:")
|
||||
sys.stdout.buffer.write(plg_out)
|
||||
sys.stdout.buffer.flush()
|
||||
|
||||
if plg_err:
|
||||
print("Plugin stderr:")
|
||||
sys.stderr.buffer.write(plg_err)
|
||||
sys.stderr.buffer.flush()
|
||||
|
||||
if plg_code_pyd == 0:
|
||||
print(
|
||||
f"\033[31;1;4mGenerated plugin (pydantic compatible) output for {test_case_name!r}\033[0m"
|
||||
)
|
||||
else:
|
||||
print(
|
||||
f"\033[31;1;4mFailed to generate plugin (pydantic compatible) output for {test_case_name!r}\033[0m"
|
||||
)
|
||||
|
||||
if verbose:
|
||||
if plg_out_pyd:
|
||||
print("Plugin stdout:")
|
||||
sys.stdout.buffer.write(plg_out_pyd)
|
||||
sys.stdout.buffer.flush()
|
||||
|
||||
if plg_err_pyd:
|
||||
print("Plugin stderr:")
|
||||
sys.stderr.buffer.write(plg_err_pyd)
|
||||
sys.stderr.buffer.flush()
|
||||
|
||||
return max(ref_code, plg_code, plg_code_pyd)
|
||||
|
||||
|
||||
HELP = "\n".join(
|
||||
@@ -136,7 +185,21 @@ def main():
|
||||
else:
|
||||
verbose = False
|
||||
whitelist = set(sys.argv[1:])
|
||||
asyncio.get_event_loop().run_until_complete(generate(whitelist, verbose))
|
||||
|
||||
if platform.system() == "Windows":
|
||||
# for python version prior to 3.8, loop policy needs to be set explicitly
|
||||
# https://docs.python.org/3/library/asyncio-policy.html#asyncio.DefaultEventLoopPolicy
|
||||
try:
|
||||
asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
|
||||
except AttributeError:
|
||||
# python < 3.7 does not have asyncio.WindowsProactorEventLoopPolicy
|
||||
asyncio.get_event_loop_policy().set_event_loop(asyncio.ProactorEventLoop())
|
||||
|
||||
try:
|
||||
asyncio.run(generate(whitelist, verbose))
|
||||
except AttributeError:
|
||||
# compatibility code for python < 3.7
|
||||
asyncio.get_event_loop().run_until_complete(generate(whitelist, verbose))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
0
tests/grpc/__init__.py
Normal file
0
tests/grpc/__init__.py
Normal file
274
tests/grpc/test_grpclib_client.py
Normal file
274
tests/grpc/test_grpclib_client.py
Normal file
@@ -0,0 +1,274 @@
|
||||
import asyncio
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
import grpclib
|
||||
import grpclib.client
|
||||
import grpclib.metadata
|
||||
import grpclib.server
|
||||
import pytest
|
||||
from grpclib.testing import ChannelFor
|
||||
|
||||
from betterproto.grpc.util.async_channel import AsyncChannel
|
||||
from tests.output_betterproto.service import (
|
||||
DoThingRequest,
|
||||
DoThingResponse,
|
||||
GetThingRequest,
|
||||
TestStub as ThingServiceClient,
|
||||
)
|
||||
|
||||
from .thing_service import ThingService
|
||||
|
||||
|
||||
async def _test_client(client: ThingServiceClient, name="clean room", **kwargs):
|
||||
response = await client.do_thing(DoThingRequest(name=name), **kwargs)
|
||||
assert response.names == [name]
|
||||
|
||||
|
||||
def _assert_request_meta_received(deadline, metadata):
|
||||
def server_side_test(stream):
|
||||
assert stream.deadline._timestamp == pytest.approx(
|
||||
deadline._timestamp, 1
|
||||
), "The provided deadline should be received serverside"
|
||||
assert (
|
||||
stream.metadata["authorization"] == metadata["authorization"]
|
||||
), "The provided authorization metadata should be received serverside"
|
||||
|
||||
return server_side_test
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def handler_trailer_only_unauthenticated():
|
||||
async def handler(stream: grpclib.server.Stream):
|
||||
await stream.recv_message()
|
||||
await stream.send_initial_metadata()
|
||||
await stream.send_trailing_metadata(status=grpclib.Status.UNAUTHENTICATED)
|
||||
|
||||
return handler
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_simple_service_call():
|
||||
async with ChannelFor([ThingService()]) as channel:
|
||||
await _test_client(ThingServiceClient(channel))
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_trailer_only_error_unary_unary(
|
||||
mocker, handler_trailer_only_unauthenticated
|
||||
):
|
||||
service = ThingService()
|
||||
mocker.patch.object(
|
||||
service,
|
||||
"do_thing",
|
||||
side_effect=handler_trailer_only_unauthenticated,
|
||||
autospec=True,
|
||||
)
|
||||
async with ChannelFor([service]) as channel:
|
||||
with pytest.raises(grpclib.exceptions.GRPCError) as e:
|
||||
await ThingServiceClient(channel).do_thing(DoThingRequest(name="something"))
|
||||
assert e.value.status == grpclib.Status.UNAUTHENTICATED
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_trailer_only_error_stream_unary(
|
||||
mocker, handler_trailer_only_unauthenticated
|
||||
):
|
||||
service = ThingService()
|
||||
mocker.patch.object(
|
||||
service,
|
||||
"do_many_things",
|
||||
side_effect=handler_trailer_only_unauthenticated,
|
||||
autospec=True,
|
||||
)
|
||||
async with ChannelFor([service]) as channel:
|
||||
with pytest.raises(grpclib.exceptions.GRPCError) as e:
|
||||
await ThingServiceClient(channel).do_many_things(
|
||||
do_thing_request_iterator=[DoThingRequest(name="something")]
|
||||
)
|
||||
await _test_client(ThingServiceClient(channel))
|
||||
assert e.value.status == grpclib.Status.UNAUTHENTICATED
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.skipif(
|
||||
sys.version_info < (3, 8), reason="async mock spy does works for python3.8+"
|
||||
)
|
||||
async def test_service_call_mutable_defaults(mocker):
|
||||
async with ChannelFor([ThingService()]) as channel:
|
||||
client = ThingServiceClient(channel)
|
||||
spy = mocker.spy(client, "_unary_unary")
|
||||
await _test_client(client)
|
||||
comments = spy.call_args_list[-1].args[1].comments
|
||||
await _test_client(client)
|
||||
assert spy.call_args_list[-1].args[1].comments is not comments
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_service_call_with_upfront_request_params():
|
||||
# Setting deadline
|
||||
deadline = grpclib.metadata.Deadline.from_timeout(22)
|
||||
metadata = {"authorization": "12345"}
|
||||
async with ChannelFor(
|
||||
[ThingService(test_hook=_assert_request_meta_received(deadline, metadata))]
|
||||
) as channel:
|
||||
await _test_client(
|
||||
ThingServiceClient(channel, deadline=deadline, metadata=metadata)
|
||||
)
|
||||
|
||||
# Setting timeout
|
||||
timeout = 99
|
||||
deadline = grpclib.metadata.Deadline.from_timeout(timeout)
|
||||
metadata = {"authorization": "12345"}
|
||||
async with ChannelFor(
|
||||
[ThingService(test_hook=_assert_request_meta_received(deadline, metadata))]
|
||||
) as channel:
|
||||
await _test_client(
|
||||
ThingServiceClient(channel, timeout=timeout, metadata=metadata)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_service_call_lower_level_with_overrides():
|
||||
THING_TO_DO = "get milk"
|
||||
|
||||
# Setting deadline
|
||||
deadline = grpclib.metadata.Deadline.from_timeout(22)
|
||||
metadata = {"authorization": "12345"}
|
||||
kwarg_deadline = grpclib.metadata.Deadline.from_timeout(28)
|
||||
kwarg_metadata = {"authorization": "12345"}
|
||||
async with ChannelFor(
|
||||
[ThingService(test_hook=_assert_request_meta_received(deadline, metadata))]
|
||||
) as channel:
|
||||
client = ThingServiceClient(channel, deadline=deadline, metadata=metadata)
|
||||
response = await client._unary_unary(
|
||||
"/service.Test/DoThing",
|
||||
DoThingRequest(THING_TO_DO),
|
||||
DoThingResponse,
|
||||
deadline=kwarg_deadline,
|
||||
metadata=kwarg_metadata,
|
||||
)
|
||||
assert response.names == [THING_TO_DO]
|
||||
|
||||
# Setting timeout
|
||||
timeout = 99
|
||||
deadline = grpclib.metadata.Deadline.from_timeout(timeout)
|
||||
metadata = {"authorization": "12345"}
|
||||
kwarg_timeout = 9000
|
||||
kwarg_deadline = grpclib.metadata.Deadline.from_timeout(kwarg_timeout)
|
||||
kwarg_metadata = {"authorization": "09876"}
|
||||
async with ChannelFor(
|
||||
[
|
||||
ThingService(
|
||||
test_hook=_assert_request_meta_received(kwarg_deadline, kwarg_metadata),
|
||||
)
|
||||
]
|
||||
) as channel:
|
||||
client = ThingServiceClient(channel, deadline=deadline, metadata=metadata)
|
||||
response = await client._unary_unary(
|
||||
"/service.Test/DoThing",
|
||||
DoThingRequest(THING_TO_DO),
|
||||
DoThingResponse,
|
||||
timeout=kwarg_timeout,
|
||||
metadata=kwarg_metadata,
|
||||
)
|
||||
assert response.names == [THING_TO_DO]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
("overrides_gen",),
|
||||
[
|
||||
(lambda: dict(timeout=10),),
|
||||
(lambda: dict(deadline=grpclib.metadata.Deadline.from_timeout(10)),),
|
||||
(lambda: dict(metadata={"authorization": str(uuid.uuid4())}),),
|
||||
(lambda: dict(timeout=20, metadata={"authorization": str(uuid.uuid4())}),),
|
||||
],
|
||||
)
|
||||
async def test_service_call_high_level_with_overrides(mocker, overrides_gen):
|
||||
overrides = overrides_gen()
|
||||
request_spy = mocker.spy(grpclib.client.Channel, "request")
|
||||
name = str(uuid.uuid4())
|
||||
defaults = dict(
|
||||
timeout=99,
|
||||
deadline=grpclib.metadata.Deadline.from_timeout(99),
|
||||
metadata={"authorization": name},
|
||||
)
|
||||
|
||||
async with ChannelFor(
|
||||
[
|
||||
ThingService(
|
||||
test_hook=_assert_request_meta_received(
|
||||
deadline=grpclib.metadata.Deadline.from_timeout(
|
||||
overrides.get("timeout", 99)
|
||||
),
|
||||
metadata=overrides.get("metadata", defaults.get("metadata")),
|
||||
)
|
||||
)
|
||||
]
|
||||
) as channel:
|
||||
client = ThingServiceClient(channel, **defaults)
|
||||
await _test_client(client, name=name, **overrides)
|
||||
assert request_spy.call_count == 1
|
||||
|
||||
# for python <3.8 request_spy.call_args.kwargs do not work
|
||||
_, request_spy_call_kwargs = request_spy.call_args_list[0]
|
||||
|
||||
# ensure all overrides were successful
|
||||
for key, value in overrides.items():
|
||||
assert key in request_spy_call_kwargs
|
||||
assert request_spy_call_kwargs[key] == value
|
||||
|
||||
# ensure default values were retained
|
||||
for key in set(defaults.keys()) - set(overrides.keys()):
|
||||
assert key in request_spy_call_kwargs
|
||||
assert request_spy_call_kwargs[key] == defaults[key]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_gen_for_unary_stream_request():
|
||||
thing_name = "my milkshakes"
|
||||
|
||||
async with ChannelFor([ThingService()]) as channel:
|
||||
client = ThingServiceClient(channel)
|
||||
expected_versions = [5, 4, 3, 2, 1]
|
||||
async for response in client.get_thing_versions(
|
||||
GetThingRequest(name=thing_name)
|
||||
):
|
||||
assert response.name == thing_name
|
||||
assert response.version == expected_versions.pop()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_gen_for_stream_stream_request():
|
||||
some_things = ["cake", "cricket", "coral reef"]
|
||||
more_things = ["ball", "that", "56kmodem", "liberal humanism", "cheesesticks"]
|
||||
expected_things = (*some_things, *more_things)
|
||||
|
||||
async with ChannelFor([ThingService()]) as channel:
|
||||
client = ThingServiceClient(channel)
|
||||
# Use an AsyncChannel to decouple sending and recieving, it'll send some_things
|
||||
# immediately and we'll use it to send more_things later, after recieving some
|
||||
# results
|
||||
request_chan = AsyncChannel()
|
||||
send_initial_requests = asyncio.ensure_future(
|
||||
request_chan.send_from(GetThingRequest(name) for name in some_things)
|
||||
)
|
||||
response_index = 0
|
||||
async for response in client.get_different_things(request_chan):
|
||||
assert response.name == expected_things[response_index]
|
||||
assert response.version == response_index + 1
|
||||
response_index += 1
|
||||
if more_things:
|
||||
# Send some more requests as we receive responses to be sure coordination of
|
||||
# send/receive events doesn't matter
|
||||
await request_chan.send(GetThingRequest(more_things.pop(0)))
|
||||
elif not send_initial_requests.done():
|
||||
# Make sure the sending task it completed
|
||||
await send_initial_requests
|
||||
else:
|
||||
# No more things to send make sure channel is closed
|
||||
request_chan.close()
|
||||
assert response_index == len(
|
||||
expected_things
|
||||
), "Didn't receive all expected responses"
|
||||
@@ -1,9 +1,11 @@
|
||||
import asyncio
|
||||
from dataclasses import dataclass
|
||||
from typing import AsyncIterator
|
||||
|
||||
import pytest
|
||||
|
||||
import betterproto
|
||||
from betterproto.grpc.util.async_channel import AsyncChannel
|
||||
from dataclasses import dataclass
|
||||
import pytest
|
||||
from typing import AsyncIterator
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -27,10 +29,7 @@ class ClientStub:
|
||||
|
||||
|
||||
async def to_list(generator: AsyncIterator):
|
||||
result = []
|
||||
async for value in generator:
|
||||
result.append(value)
|
||||
return result
|
||||
return [value async for value in generator]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -1,12 +1,14 @@
|
||||
from betterproto.tests.output_betterproto.service.service import (
|
||||
DoThingResponse,
|
||||
from typing import Dict
|
||||
|
||||
import grpclib
|
||||
import grpclib.server
|
||||
|
||||
from tests.output_betterproto.service import (
|
||||
DoThingRequest,
|
||||
DoThingResponse,
|
||||
GetThingRequest,
|
||||
GetThingResponse,
|
||||
TestStub as ThingServiceClient,
|
||||
)
|
||||
import grpclib
|
||||
from typing import Any, Dict
|
||||
|
||||
|
||||
class ThingService:
|
||||
@@ -1,5 +1,7 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package bool;
|
||||
|
||||
message Test {
|
||||
bool value = 1;
|
||||
}
|
||||
19
tests/inputs/bool/test_bool.py
Normal file
19
tests/inputs/bool/test_bool.py
Normal file
@@ -0,0 +1,19 @@
|
||||
import pytest
|
||||
|
||||
from tests.output_betterproto.bool import Test
|
||||
from tests.output_betterproto_pydantic.bool import Test as TestPyd
|
||||
|
||||
|
||||
def test_value():
|
||||
message = Test()
|
||||
assert not message.value, "Boolean is False by default"
|
||||
|
||||
|
||||
def test_pydantic_no_value():
|
||||
with pytest.raises(ValueError):
|
||||
TestPyd()
|
||||
|
||||
|
||||
def test_pydantic_value():
|
||||
message = Test(value=False)
|
||||
assert not message.value
|
||||
@@ -1,5 +1,7 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package bytes;
|
||||
|
||||
message Test {
|
||||
bytes data = 1;
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package casing;
|
||||
|
||||
enum my_enum {
|
||||
ZERO = 0;
|
||||
ONE = 1;
|
||||
@@ -1,5 +1,5 @@
|
||||
import betterproto.tests.output_betterproto.casing as casing
|
||||
from betterproto.tests.output_betterproto.casing import Test
|
||||
import tests.output_betterproto.casing as casing
|
||||
from tests.output_betterproto.casing import Test
|
||||
|
||||
|
||||
def test_message_attributes():
|
||||
11
tests/inputs/casing_inner_class/casing_inner_class.proto
Normal file
11
tests/inputs/casing_inner_class/casing_inner_class.proto
Normal file
@@ -0,0 +1,11 @@
|
||||
// https://github.com/danielgtaylor/python-betterproto/issues/344
|
||||
syntax = "proto3";
|
||||
|
||||
package casing_inner_class;
|
||||
|
||||
message Test {
|
||||
message inner_class {
|
||||
sint32 old_exp = 1;
|
||||
}
|
||||
inner_class inner = 2;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user