generic-remote-graphql 0.0.3b4806__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- generic_remote_graphql-0.0.3b4806/.env.example +11 -0
- generic_remote_graphql-0.0.3b4806/.env.local1.example +25 -0
- generic_remote_graphql-0.0.3b4806/.env.play1.example +26 -0
- generic_remote_graphql-0.0.3b4806/.flake8 +2 -0
- generic_remote_graphql-0.0.3b4806/.logger.json5 +7 -0
- generic_remote_graphql-0.0.3b4806/CODEOWNERS +2 -0
- generic_remote_graphql-0.0.3b4806/PKG-INFO +27 -0
- generic_remote_graphql-0.0.3b4806/README.md +45 -0
- generic_remote_graphql-0.0.3b4806/__init__.py +0 -0
- generic_remote_graphql-0.0.3b4806/bin/cmd/profile.bat +3 -0
- generic_remote_graphql-0.0.3b4806/bin/powershell/ExamplePowerShellModule/ExamplePowershellModule.psm1 +0 -0
- generic_remote_graphql-0.0.3b4806/bin/powershell/profile.ps1 +5 -0
- generic_remote_graphql-0.0.3b4806/bin/sh/profile.sh +5 -0
- generic_remote_graphql-0.0.3b4806/bin/sh/run.sh +7 -0
- generic_remote_graphql-0.0.3b4806/component.local1.json5.example +11 -0
- generic_remote_graphql-0.0.3b4806/generic_remote_graphql.egg-info/PKG-INFO +27 -0
- generic_remote_graphql-0.0.3b4806/generic_remote_graphql.egg-info/SOURCES.txt +39 -0
- generic_remote_graphql-0.0.3b4806/generic_remote_graphql.egg-info/dependency_links.txt +1 -0
- generic_remote_graphql-0.0.3b4806/generic_remote_graphql.egg-info/requires.txt +3 -0
- generic_remote_graphql-0.0.3b4806/generic_remote_graphql.egg-info/top_level.txt +1 -0
- generic_remote_graphql-0.0.3b4806/mypy.ini +12 -0
- generic_remote_graphql-0.0.3b4806/pyproject.toml +32 -0
- generic_remote_graphql-0.0.3b4806/pytest.ini +5 -0
- generic_remote_graphql-0.0.3b4806/python_packages/generic_remote_graphql/__init__.py +0 -0
- generic_remote_graphql-0.0.3b4806/python_packages/generic_remote_graphql/src/__init__.py +5 -0
- generic_remote_graphql-0.0.3b4806/python_packages/generic_remote_graphql/src/constants.py +32 -0
- generic_remote_graphql-0.0.3b4806/python_packages/generic_remote_graphql/src/generic_remote_graphql.py +109 -0
- generic_remote_graphql-0.0.3b4806/python_packages/generic_remote_graphql/src/graphql_requests.py +54 -0
- generic_remote_graphql-0.0.3b4806/python_packages/generic_remote_graphql/src/transports.py +76 -0
- generic_remote_graphql-0.0.3b4806/python_packages/generic_remote_graphql/src/version.py +1 -0
- generic_remote_graphql-0.0.3b4806/python_packages/generic_remote_graphql/tests/__init__.py +0 -0
- generic_remote_graphql-0.0.3b4806/python_packages/generic_remote_graphql/tests/conftest.py +6 -0
- generic_remote_graphql-0.0.3b4806/python_packages/generic_remote_graphql/tests/system/__init__.py +0 -0
- generic_remote_graphql-0.0.3b4806/python_packages/generic_remote_graphql/tests/system/generic_remote_graphql_system_test.py +37 -0
- generic_remote_graphql-0.0.3b4806/python_packages/generic_remote_graphql/tests/unit/__init__.py +0 -0
- generic_remote_graphql-0.0.3b4806/python_packages/generic_remote_graphql/tests/unit/generic_remote_graphql_local_server_unit_test.py +118 -0
- generic_remote_graphql-0.0.3b4806/python_packages/generic_remote_graphql/tests/unit/generic_remote_graphql_unit_test.py +220 -0
- generic_remote_graphql-0.0.3b4806/requirements-dev.txt +5 -0
- generic_remote_graphql-0.0.3b4806/requirements.txt +12 -0
- generic_remote_graphql-0.0.3b4806/setup.cfg +4 -0
- generic_remote_graphql-0.0.3b4806/setup.py +98 -0
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
BRAND_NAME=None
|
|
2
|
+
ENVIRONMENT_NAME=None
|
|
3
|
+
LOGZIO_TOKEN=None
|
|
4
|
+
DATADOG_SITE=None
|
|
5
|
+
DATADOG_API_KEY=None
|
|
6
|
+
LOGGER_CONFIGURATION_JSON_PATH=None
|
|
7
|
+
LOGGER_MINIMUM_SEVERITY=None
|
|
8
|
+
LOGGER_IS_WRITE_TO_SQL=false
|
|
9
|
+
LOGGER_COLORS_IN_LOGS=
|
|
10
|
+
TEST_GRAPHQL_APPSYNC_URL=None
|
|
11
|
+
TEST_GRAPHQL_APPSYNC_API_KEY=None
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# TODO Please add all the environment variables uses in this repo here without any sensative/private information/credentials
|
|
2
|
+
|
|
3
|
+
# This is the .env file for play1 environment in the project directory and not in the root directory
|
|
4
|
+
# Please do not delete/rename this file
|
|
5
|
+
|
|
6
|
+
BRAND_NAME=Circlez
|
|
7
|
+
ENVIRONMENT_NAME=local1
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
# LOGZIO_TOKEN=
|
|
12
|
+
DATADOG_API_KEY=
|
|
13
|
+
|
|
14
|
+
# Needed by the logger-local
|
|
15
|
+
# TODO: Please update you username in the product i.e. tal.r@circ.zone and the password in the product
|
|
16
|
+
PRODUCT_USER_IDENTIFIER=
|
|
17
|
+
PRODUCT_PASSWORD=
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
# Only for tests/system (a real AppSync test table). Leave empty here; set them in your own .env
|
|
24
|
+
TEST_GRAPHQL_APPSYNC_URL=
|
|
25
|
+
TEST_GRAPHQL_APPSYNC_API_KEY=
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# TODO Please add all the environment variables used in this repo here without any sensative/private information/credentials
|
|
2
|
+
|
|
3
|
+
# This is the .env file for play1 environment in the project directory and not in the root directory
|
|
4
|
+
# Please do not delete/rename this file
|
|
5
|
+
|
|
6
|
+
BRAND_NAME=Circlez
|
|
7
|
+
ENVIRONMENT_NAME=play1
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
# LOGZIO_TOKEN=
|
|
12
|
+
DATADOG_API_KEY=
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
# Needed by the logger-local
|
|
16
|
+
# TODO: Please update your username in the product, i.e., tal.r@circ.zone, and the password in the product
|
|
17
|
+
PRODUCT_USER_IDENTIFIER=
|
|
18
|
+
PRODUCT_PASSWORD=
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
# Only for tests/system (a real AppSync test table). Leave empty here; set them in your own .env
|
|
25
|
+
TEST_GRAPHQL_APPSYNC_URL=
|
|
26
|
+
TEST_GRAPHQL_APPSYNC_API_KEY=
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: generic-remote-graphql
|
|
3
|
+
Version: 0.0.3b4806
|
|
4
|
+
Summary: PyPI generic-remote-graphql Python Package owned by Circlez.ai
|
|
5
|
+
Home-page: https://github.com/circles-zone/generic-remote-graphql-python-package
|
|
6
|
+
Author: Circles
|
|
7
|
+
Author-email: info@circlez.ai
|
|
8
|
+
License: MIT
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
Requires-Dist: requests>=2.31.0
|
|
13
|
+
Requires-Dist: python-sdk-remote>=0.0.216
|
|
14
|
+
Requires-Dist: logger-local>=0.0.195
|
|
15
|
+
Dynamic: author
|
|
16
|
+
Dynamic: author-email
|
|
17
|
+
Dynamic: classifier
|
|
18
|
+
Dynamic: description
|
|
19
|
+
Dynamic: description-content-type
|
|
20
|
+
Dynamic: home-page
|
|
21
|
+
Dynamic: license
|
|
22
|
+
Dynamic: requires-dist
|
|
23
|
+
Dynamic: summary
|
|
24
|
+
|
|
25
|
+
PyPI generic-remote-graphql Python Package owned by Circlez.ai
|
|
26
|
+
JIRA Work Item: https://circles-zone.atlassian.net/browse/BU-4806
|
|
27
|
+
GHA: https://github.com/circles-zone/generic-remote-graphql-python-package/actions
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# generic-remote-graphql-python-package
|
|
2
|
+
|
|
3
|
+
Generic Python client for GraphQL tables. Python twin of `generic-remote-graphql-typescript-package`.
|
|
4
|
+
AppSync (API key) is supported first; Apollo (Bearer token / custom headers) uses the same client with
|
|
5
|
+
`ApolloTransport`.
|
|
6
|
+
|
|
7
|
+
## Usage
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
from generic_remote_graphql import GenericRemoteGraphQL, AppSyncTransport
|
|
11
|
+
|
|
12
|
+
transport = AppSyncTransport("https://<appsync-url>/graphql", api_key="<ENTITY>_GRAPHQL_APPSYNC_API_KEY value")
|
|
13
|
+
offers = GenericRemoteGraphQL(table_name="Offer", primary_key_name="offer_id", transport=transport)
|
|
14
|
+
|
|
15
|
+
offers.create("offer_id name", {"name": "Eilat hotel"})
|
|
16
|
+
offers.get_by_id(7, "offer_id name")
|
|
17
|
+
page = offers.list_items("offer_id name", filter_input={"end_timestamp": {"attributeExists": False}}) # one page
|
|
18
|
+
for item in offers.list_all("offer_id name"): # every page, follows nextToken
|
|
19
|
+
...
|
|
20
|
+
offers.update("offer_id", {"offer_id": 7, "name": "Eilat hotel 2"})
|
|
21
|
+
offers.delete("offer_id", {"offer_id": 7}) # soft delete (end_timestamp)
|
|
22
|
+
offers.total_delete("offer_id", {"offer_id": 7}) # real delete
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
| TypeScript | Python |
|
|
26
|
+
|---|---|
|
|
27
|
+
| `getByIdAsync` | `get_by_id` |
|
|
28
|
+
| `listAsync` | `list_items` (one page), `list_all` (all pages, extra) |
|
|
29
|
+
| `createAsync` | `create` |
|
|
30
|
+
| `updateAsync` | `update` |
|
|
31
|
+
| `deleteAsync` | `delete` (soft) |
|
|
32
|
+
| `totalDeleteAsync` | `total_delete` |
|
|
33
|
+
|
|
34
|
+
## Tests
|
|
35
|
+
|
|
36
|
+
```shell
|
|
37
|
+
pip install -r requirements.txt -r requirements-dev.txt
|
|
38
|
+
# logger-local needs BRAND_NAME and ENVIRONMENT_NAME: put them in your .env (see the .env example files)
|
|
39
|
+
pytest
|
|
40
|
+
python -m mypy python_packages/generic_remote_graphql
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
- `python_packages/generic_remote_graphql/tests/unit/`: no network, no database (includes a tiny GraphQL server on localhost).
|
|
44
|
+
- `python_packages/generic_remote_graphql/tests/system/`: real AppSync table; skipped unless `TEST_GRAPHQL_APPSYNC_URL` and
|
|
45
|
+
`TEST_GRAPHQL_APPSYNC_API_KEY` are set. Created objects use `is_test_data=True`.
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: generic-remote-graphql
|
|
3
|
+
Version: 0.0.3b4806
|
|
4
|
+
Summary: PyPI generic-remote-graphql Python Package owned by Circlez.ai
|
|
5
|
+
Home-page: https://github.com/circles-zone/generic-remote-graphql-python-package
|
|
6
|
+
Author: Circles
|
|
7
|
+
Author-email: info@circlez.ai
|
|
8
|
+
License: MIT
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
Requires-Dist: requests>=2.31.0
|
|
13
|
+
Requires-Dist: python-sdk-remote>=0.0.216
|
|
14
|
+
Requires-Dist: logger-local>=0.0.195
|
|
15
|
+
Dynamic: author
|
|
16
|
+
Dynamic: author-email
|
|
17
|
+
Dynamic: classifier
|
|
18
|
+
Dynamic: description
|
|
19
|
+
Dynamic: description-content-type
|
|
20
|
+
Dynamic: home-page
|
|
21
|
+
Dynamic: license
|
|
22
|
+
Dynamic: requires-dist
|
|
23
|
+
Dynamic: summary
|
|
24
|
+
|
|
25
|
+
PyPI generic-remote-graphql Python Package owned by Circlez.ai
|
|
26
|
+
JIRA Work Item: https://circles-zone.atlassian.net/browse/BU-4806
|
|
27
|
+
GHA: https://github.com/circles-zone/generic-remote-graphql-python-package/actions
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
.env.example
|
|
2
|
+
.env.local1.example
|
|
3
|
+
.env.play1.example
|
|
4
|
+
.flake8
|
|
5
|
+
.logger.json5
|
|
6
|
+
CODEOWNERS
|
|
7
|
+
README.md
|
|
8
|
+
__init__.py
|
|
9
|
+
component.local1.json5.example
|
|
10
|
+
mypy.ini
|
|
11
|
+
pyproject.toml
|
|
12
|
+
pytest.ini
|
|
13
|
+
requirements-dev.txt
|
|
14
|
+
requirements.txt
|
|
15
|
+
setup.py
|
|
16
|
+
bin/cmd/profile.bat
|
|
17
|
+
bin/powershell/profile.ps1
|
|
18
|
+
bin/powershell/ExamplePowerShellModule/ExamplePowershellModule.psm1
|
|
19
|
+
bin/sh/profile.sh
|
|
20
|
+
bin/sh/run.sh
|
|
21
|
+
generic_remote_graphql.egg-info/PKG-INFO
|
|
22
|
+
generic_remote_graphql.egg-info/SOURCES.txt
|
|
23
|
+
generic_remote_graphql.egg-info/dependency_links.txt
|
|
24
|
+
generic_remote_graphql.egg-info/requires.txt
|
|
25
|
+
generic_remote_graphql.egg-info/top_level.txt
|
|
26
|
+
python_packages/generic_remote_graphql/__init__.py
|
|
27
|
+
python_packages/generic_remote_graphql/src/__init__.py
|
|
28
|
+
python_packages/generic_remote_graphql/src/constants.py
|
|
29
|
+
python_packages/generic_remote_graphql/src/generic_remote_graphql.py
|
|
30
|
+
python_packages/generic_remote_graphql/src/graphql_requests.py
|
|
31
|
+
python_packages/generic_remote_graphql/src/transports.py
|
|
32
|
+
python_packages/generic_remote_graphql/src/version.py
|
|
33
|
+
python_packages/generic_remote_graphql/tests/__init__.py
|
|
34
|
+
python_packages/generic_remote_graphql/tests/conftest.py
|
|
35
|
+
python_packages/generic_remote_graphql/tests/system/__init__.py
|
|
36
|
+
python_packages/generic_remote_graphql/tests/system/generic_remote_graphql_system_test.py
|
|
37
|
+
python_packages/generic_remote_graphql/tests/unit/__init__.py
|
|
38
|
+
python_packages/generic_remote_graphql/tests/unit/generic_remote_graphql_local_server_unit_test.py
|
|
39
|
+
python_packages/generic_remote_graphql/tests/unit/generic_remote_graphql_unit_test.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
generic_remote_graphql
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
[mypy]
|
|
2
|
+
python_version = 3.13
|
|
3
|
+
explicit_package_bases = True
|
|
4
|
+
mypy_path = python_packages
|
|
5
|
+
|
|
6
|
+
# Circles' own packages ship no type information (no py.typed), so mypy cannot read them.
|
|
7
|
+
# Only these two are exempted, not everything.
|
|
8
|
+
[mypy-logger_local.*]
|
|
9
|
+
ignore_missing_imports = True
|
|
10
|
+
|
|
11
|
+
[mypy-python_sdk_remote.*]
|
|
12
|
+
ignore_missing_imports = True
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# This file should be in the future instead of setup.py
|
|
2
|
+
# https://python-poetry.org/docs/pyproject
|
|
3
|
+
# https://stackoverflow.com/questions/78048223/adding-folder-with-data-with-pyproject-toml
|
|
4
|
+
# https://packaging.python.org/en/latest/guides/writing-pyproject-toml/#license
|
|
5
|
+
|
|
6
|
+
# This file is mandatory for the `poetry version patch`
|
|
7
|
+
|
|
8
|
+
# It seems we need to copy this file also to serverless-com repo, as required by dialog-workflow-python-package
|
|
9
|
+
|
|
10
|
+
[build-system]
|
|
11
|
+
# "setuptools_scm>=6.2" is required for writing the version in my_package/_version.py and may be also for "poetry version patch" to work
|
|
12
|
+
requires = ["setuptools>=61.0", "setuptools_scm>=6.2"]
|
|
13
|
+
build-backend = "setuptools.build_meta"
|
|
14
|
+
|
|
15
|
+
[tool.setuptools_scm]
|
|
16
|
+
write_to = "generic_remote_graphql/_version.py"
|
|
17
|
+
|
|
18
|
+
[tool.poetry]
|
|
19
|
+
# TODO: Please update the name, similar to storage-local (suffix -local)
|
|
20
|
+
name = "generic-remote-graphql"
|
|
21
|
+
# TODO After the b (beta), you should add the Jira Work Item ID (was generated by Jira). If you run sdk-local Makec.ps1 it should do it for you.
|
|
22
|
+
# I believe we are still using the version from setup.py and not from here until Potery will work
|
|
23
|
+
version = "0.0.3b4806" # https://pypi.org/project/generic-remote-graphql
|
|
24
|
+
description = "generic-remote-graphql Python Package"
|
|
25
|
+
readme = "README.md"
|
|
26
|
+
authors = [
|
|
27
|
+
"Circlez.ai <info@circlez.ai>",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[tool.poetry.dev-dependencies]
|
|
31
|
+
pytest = "^8.0"
|
|
32
|
+
pytest-cov = "^5.0"
|
|
File without changes
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
from .generic_remote_graphql import GenericRemoteGraphQL
|
|
2
|
+
from .transports import ApolloTransport, AppSyncTransport, GraphQLRequestError, GraphQLTransport
|
|
3
|
+
|
|
4
|
+
__all__ = ["GenericRemoteGraphQL", "AppSyncTransport", "ApolloTransport", "GraphQLTransport",
|
|
5
|
+
"GraphQLRequestError"]
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Constants of generic-remote-graphql (mirrors generic-remote-graphql-typescript-package)."""
|
|
2
|
+
|
|
3
|
+
from logger_local.LoggerComponentEnum import LoggerComponentEnum
|
|
4
|
+
|
|
5
|
+
# Real ids, inserted into component.component_table on 2026-11-21 (BU-4806):
|
|
6
|
+
# 5000025 = "generic-remote-graphql-python-package code", 5000026 = "... test"
|
|
7
|
+
GENERIC_REMOTE_GRAPHQL_PYTHON_COMPONENT_ID = 5000025 # CODE component id
|
|
8
|
+
GENERIC_REMOTE_GRAPHQL_PYTHON_TEST_COMPONENT_ID = 5000026 # TEST component id
|
|
9
|
+
GENERIC_REMOTE_GRAPHQL_PYTHON_COMPONENT_NAME = "generic-remote-graphql-python-package"
|
|
10
|
+
DEVELOPER_EMAIL = "noy.s@circ.zone"
|
|
11
|
+
|
|
12
|
+
GENERIC_REMOTE_GRAPHQL_CODE_LOGGER_OBJECT = {
|
|
13
|
+
"component_id": GENERIC_REMOTE_GRAPHQL_PYTHON_COMPONENT_ID,
|
|
14
|
+
"component_name": GENERIC_REMOTE_GRAPHQL_PYTHON_COMPONENT_NAME,
|
|
15
|
+
"component_category": LoggerComponentEnum.ComponentCategory.Code.value,
|
|
16
|
+
"developer_email_address": DEVELOPER_EMAIL, # newer logger-local name ("developer_email" is deprecated)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
# Same defaults as the TypeScript package (src/constants.ts)
|
|
20
|
+
DEFAULT_NO_FILTER: dict = {}
|
|
21
|
+
DEFAULT_NEXT_TOKEN = ""
|
|
22
|
+
DEFAULT_NO_ORDER_BY: dict = {}
|
|
23
|
+
DEFAULT_LIST_ITEMS_LIMIT = 100
|
|
24
|
+
DEFAULT_MAX_PAGES = 250 # list_all stops after this many pages (protects from an endless server)
|
|
25
|
+
TEMPORARY_AUTO_USER_ID = 2 # used when no user context is given (same as TypeScript)
|
|
26
|
+
|
|
27
|
+
ORDER_BY_ASCENDING_CREATED_TIMESTAMP = {"created_timestamp": "ASC"}
|
|
28
|
+
ORDER_BY_DESCENDING_CREATED_TIMESTAMP = {"created_timestamp": "DESC"}
|
|
29
|
+
FILTER_BY_ACTIVE_ITEMS = {"end_timestamp": {"attributeExists": False}}
|
|
30
|
+
|
|
31
|
+
# Soft removal: sending any string in end_timestamp makes the server write the current time
|
|
32
|
+
END_TIMESTAMP_AUTO_NOW_VALUE = "now"
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Generic Python client for GraphQL tables (AppSync first, Apollo through the transport).
|
|
2
|
+
|
|
3
|
+
Python twin of generic-remote-graphql-typescript-package (GenericRemoteGraphQL.ts):
|
|
4
|
+
get / list / create / update / soft delete / total delete.
|
|
5
|
+
"""
|
|
6
|
+
from typing import Iterator, Optional
|
|
7
|
+
|
|
8
|
+
from . import graphql_requests as requests_text
|
|
9
|
+
from .constants import (DEFAULT_LIST_ITEMS_LIMIT, DEFAULT_MAX_PAGES, DEFAULT_NEXT_TOKEN, DEFAULT_NO_FILTER,
|
|
10
|
+
DEFAULT_NO_ORDER_BY, GENERIC_REMOTE_GRAPHQL_CODE_LOGGER_OBJECT,
|
|
11
|
+
END_TIMESTAMP_AUTO_NOW_VALUE, TEMPORARY_AUTO_USER_ID)
|
|
12
|
+
from logger_local import MetaLogger
|
|
13
|
+
from .transports import GraphQLTransport
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
# mypy does not know the `object=` argument of Circles' MetaLogger (every Circles class that uses it reports this)
|
|
17
|
+
class GenericRemoteGraphQL(metaclass=MetaLogger, object=GENERIC_REMOTE_GRAPHQL_CODE_LOGGER_OBJECT): # type: ignore[call-arg] # noqa: E501
|
|
18
|
+
"""One instance = one GraphQL table.
|
|
19
|
+
|
|
20
|
+
table_name e.g. "Location" (the GraphQL type name)
|
|
21
|
+
primary_key_name e.g. "location_id"
|
|
22
|
+
transport AppSyncTransport(...) or ApolloTransport(...)
|
|
23
|
+
user_id effective user id; TEMPORARY_AUTO_USER_ID when not given (as in TypeScript)
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def __init__(self, *, table_name: str, primary_key_name: str, transport: GraphQLTransport,
|
|
27
|
+
list_items_limit: int = DEFAULT_LIST_ITEMS_LIMIT, user_id: Optional[int] = None,
|
|
28
|
+
is_test_data: bool = False):
|
|
29
|
+
self.table_name = table_name
|
|
30
|
+
self.primary_key_name = primary_key_name
|
|
31
|
+
self.transport = transport
|
|
32
|
+
self.list_items_limit = list_items_limit
|
|
33
|
+
self.user_id = user_id
|
|
34
|
+
# Circles rule: objects created by tests must have is_test_data = true.
|
|
35
|
+
# (The TypeScript package keeps this flag but never sends it; here create() sends it when True.)
|
|
36
|
+
self.is_test_data = is_test_data
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def _effective_user_id(self) -> int:
|
|
40
|
+
return self.user_id if self.user_id else TEMPORARY_AUTO_USER_ID
|
|
41
|
+
|
|
42
|
+
def get_by_id(self, item_id: int, return_fields: str) -> Optional[dict]:
|
|
43
|
+
query = requests_text.get_query(self.table_name, return_fields, self.primary_key_name)
|
|
44
|
+
data = self.transport.execute(query, {"id": item_id})
|
|
45
|
+
return data.get(f"get{self.table_name}")
|
|
46
|
+
|
|
47
|
+
def list_all(self, return_fields: str, filter_input: Optional[dict] = None, order_by: Optional[dict] = None,
|
|
48
|
+
page_size: Optional[int] = None, max_pages: int = DEFAULT_MAX_PAGES) -> Iterator[dict]:
|
|
49
|
+
"""Yields every item, following nextToken page after page (max_pages protects from endless loops)."""
|
|
50
|
+
next_token: Optional[str] = None
|
|
51
|
+
for _ in range(max_pages):
|
|
52
|
+
page = self.list_items(return_fields, filter_input, next_token, page_size, order_by)
|
|
53
|
+
yield from page.get("items") or []
|
|
54
|
+
next_token = page.get("nextToken")
|
|
55
|
+
if not next_token:
|
|
56
|
+
return
|
|
57
|
+
raise RuntimeError(f"list_all stopped after {max_pages} pages; the table may be huge or the server loops")
|
|
58
|
+
|
|
59
|
+
def list_items(self, return_fields: str, filter_input: Optional[dict] = None, next_token: Optional[str] = None,
|
|
60
|
+
limit: Optional[int] = None, order_by: Optional[dict] = None) -> dict:
|
|
61
|
+
"""One page. Returns {"items": [...], "nextToken": str | None}; pass nextToken back for the next page.
|
|
62
|
+
(TypeScript name: listAsync.)"""
|
|
63
|
+
token = next_token or DEFAULT_NEXT_TOKEN
|
|
64
|
+
query = requests_text.list_query(self.table_name, return_fields, token)
|
|
65
|
+
variables = {
|
|
66
|
+
"filter": dict(filter_input if filter_input is not None else DEFAULT_NO_FILTER),
|
|
67
|
+
"limit": limit or self.list_items_limit,
|
|
68
|
+
"nextToken": token,
|
|
69
|
+
"orderBy": order_by if order_by else DEFAULT_NO_ORDER_BY,
|
|
70
|
+
}
|
|
71
|
+
data = self.transport.execute(query, variables)
|
|
72
|
+
return data.get(f"list{self.table_name}s") or {"items": [], "nextToken": None}
|
|
73
|
+
|
|
74
|
+
def create(self, return_fields: str, create_input: dict) -> Optional[dict]:
|
|
75
|
+
query = requests_text.create_query(self.table_name, return_fields)
|
|
76
|
+
user_id = self._effective_user_id
|
|
77
|
+
create_data = {**create_input, "created_user_id": user_id, "updated_user_id": user_id}
|
|
78
|
+
if self.is_test_data:
|
|
79
|
+
create_data["is_test_data"] = True
|
|
80
|
+
variables = {"createInput": create_data}
|
|
81
|
+
data = self.transport.execute(query, variables)
|
|
82
|
+
return data.get(f"create{self.table_name}")
|
|
83
|
+
|
|
84
|
+
def update(self, return_fields: str, update_input: dict, condition: Optional[dict] = None) -> Optional[dict]:
|
|
85
|
+
query = requests_text.update_query(self.table_name, return_fields)
|
|
86
|
+
# Same as TypeScript: updated_user_id is added only when we know the user (no user context = untouched)
|
|
87
|
+
update_data = {**update_input, "updated_user_id": self.user_id} if self.user_id else dict(update_input)
|
|
88
|
+
variables = {
|
|
89
|
+
"updateInput": update_data,
|
|
90
|
+
"condition": dict(condition if condition is not None else DEFAULT_NO_FILTER),
|
|
91
|
+
}
|
|
92
|
+
data = self.transport.execute(query, variables)
|
|
93
|
+
return data.get(f"update{self.table_name}")
|
|
94
|
+
|
|
95
|
+
def delete(self, return_fields: str, delete_input: dict, condition: Optional[dict] = None) -> Optional[dict]:
|
|
96
|
+
"""Soft delete: marks the row with end_timestamp instead of removing it."""
|
|
97
|
+
# Same as TypeScript deleteAsync: updated_user_id is always sent here (temporary id without a user)
|
|
98
|
+
return self.update(return_fields,
|
|
99
|
+
{**delete_input, "end_timestamp": END_TIMESTAMP_AUTO_NOW_VALUE,
|
|
100
|
+
"updated_user_id": self._effective_user_id},
|
|
101
|
+
condition)
|
|
102
|
+
|
|
103
|
+
def total_delete(self, return_fields: str, delete_input: dict, condition: Optional[dict] = None) -> Optional[dict]:
|
|
104
|
+
"""Real delete: the row is removed from the table. Use delete() unless you really mean it."""
|
|
105
|
+
query = requests_text.delete_query(self.table_name, return_fields)
|
|
106
|
+
variables = {"deleteInput": delete_input,
|
|
107
|
+
"condition": dict(condition if condition is not None else DEFAULT_NO_FILTER)}
|
|
108
|
+
data = self.transport.execute(query, variables)
|
|
109
|
+
return data.get(f"delete{self.table_name}")
|
generic_remote_graphql-0.0.3b4806/python_packages/generic_remote_graphql/src/graphql_requests.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Builds the GraphQL query text. Same shapes as the TypeScript package (src/graphQLRequests.ts)."""
|
|
2
|
+
import json
|
|
3
|
+
|
|
4
|
+
from .constants import DEFAULT_NEXT_TOKEN
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def get_query(table_name: str, return_fields: str, id_field_name: str) -> str:
|
|
8
|
+
return f"""
|
|
9
|
+
query get{table_name}($id: Int!) {{
|
|
10
|
+
get{table_name}({id_field_name}: $id) {{
|
|
11
|
+
{return_fields}
|
|
12
|
+
}}
|
|
13
|
+
}}"""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def list_query(table_name: str, return_fields: str, next_token: str = DEFAULT_NEXT_TOKEN) -> str:
|
|
17
|
+
# json.dumps makes a safe string literal (a quote inside the token cannot break the query text)
|
|
18
|
+
next_token_param = f", nextToken: {json.dumps(next_token)}" if next_token != DEFAULT_NEXT_TOKEN else ""
|
|
19
|
+
return f"""
|
|
20
|
+
query list{table_name}s($filter: Table{table_name}FilterInput, $limit: Int, $orderBy: [OrderBy{table_name}Input]) {{
|
|
21
|
+
list{table_name}s(filter: $filter, limit: $limit, orderBy: $orderBy {next_token_param}) {{
|
|
22
|
+
items {{
|
|
23
|
+
{return_fields}
|
|
24
|
+
}}
|
|
25
|
+
nextToken
|
|
26
|
+
}}
|
|
27
|
+
}}"""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def create_query(table_name: str, return_fields: str) -> str:
|
|
31
|
+
return f"""
|
|
32
|
+
mutation create{table_name}($createInput: Create{table_name}Input!) {{
|
|
33
|
+
create{table_name}(input: $createInput) {{
|
|
34
|
+
{return_fields}
|
|
35
|
+
}}
|
|
36
|
+
}}"""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def update_query(table_name: str, return_fields: str) -> str:
|
|
40
|
+
return f"""
|
|
41
|
+
mutation update{table_name}($updateInput: Update{table_name}Input!, $condition: Table{table_name}ConditionInput) {{
|
|
42
|
+
update{table_name}(input: $updateInput, condition: $condition) {{
|
|
43
|
+
{return_fields}
|
|
44
|
+
}}
|
|
45
|
+
}}"""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def delete_query(table_name: str, return_fields: str) -> str:
|
|
49
|
+
return f"""
|
|
50
|
+
mutation delete{table_name}($deleteInput: Delete{table_name}Input!, $condition: Table{table_name}ConditionInput) {{
|
|
51
|
+
delete{table_name}(input: $deleteInput, condition: $condition) {{
|
|
52
|
+
{return_fields}
|
|
53
|
+
}}
|
|
54
|
+
}}"""
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""How a query travels to the server. AppSync and Apollo differ only in the authentication headers,
|
|
2
|
+
so both are a plain GraphQL-over-HTTP POST with different headers."""
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from typing import Optional
|
|
5
|
+
|
|
6
|
+
import requests
|
|
7
|
+
from python_sdk_remote.our_request import OurRequest
|
|
8
|
+
|
|
9
|
+
DEFAULT_TIMEOUT_SECONDS = 30
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class GraphQLRequestError(Exception):
|
|
13
|
+
"""The server answered, but with GraphQL errors (response contains an "errors" list)."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, errors: list):
|
|
16
|
+
self.errors = errors
|
|
17
|
+
super().__init__(f"GraphQL errors: {errors}")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class GraphQLTransport(ABC):
|
|
21
|
+
"""Sends one query and returns the "data" part of the answer."""
|
|
22
|
+
|
|
23
|
+
def __init__(self, url: str, timeout: int = DEFAULT_TIMEOUT_SECONDS):
|
|
24
|
+
self.url = url
|
|
25
|
+
self.timeout = timeout
|
|
26
|
+
|
|
27
|
+
@abstractmethod
|
|
28
|
+
def headers(self) -> dict:
|
|
29
|
+
...
|
|
30
|
+
|
|
31
|
+
def execute(self, query: str, variables: Optional[dict] = None) -> dict:
|
|
32
|
+
try:
|
|
33
|
+
# OurRequest.post (python-sdk-remote) wraps the requests library with logging, retries on 5xx and
|
|
34
|
+
# network errors, and raise_for_status. It is the Circles way (the TypeScript twin has OurAxios.post)
|
|
35
|
+
response = OurRequest.post(url=self.url, json={"query": query, "variables": variables or {}},
|
|
36
|
+
headers=self.headers(), timeout=self.timeout)
|
|
37
|
+
except requests.HTTPError as error:
|
|
38
|
+
# the server's own message (for example "UnauthorizedException") explains a 401/403 much better
|
|
39
|
+
server_text = error.response.text[:300] if error.response is not None else ""
|
|
40
|
+
raise requests.HTTPError(f"{error} | server said: {server_text}", response=error.response) from error
|
|
41
|
+
try:
|
|
42
|
+
body = response.json()
|
|
43
|
+
except ValueError as error:
|
|
44
|
+
raise GraphQLRequestError([{"message": f"answer is not JSON: {response.text[:200]}"}]) from error
|
|
45
|
+
if body.get("errors"):
|
|
46
|
+
raise GraphQLRequestError(body["errors"])
|
|
47
|
+
return body.get("data") or {}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class AppSyncTransport(GraphQLTransport):
|
|
51
|
+
"""AWS AppSync with an API key (header x-api-key), like the TypeScript package."""
|
|
52
|
+
|
|
53
|
+
def __init__(self, url: str, api_key: str, timeout: int = DEFAULT_TIMEOUT_SECONDS):
|
|
54
|
+
super().__init__(url, timeout)
|
|
55
|
+
if not api_key:
|
|
56
|
+
raise ValueError("AppSync api_key is empty (look for <ENTITY>_GRAPHQL_APPSYNC_API_KEY in your .env)")
|
|
57
|
+
self._api_key = api_key
|
|
58
|
+
|
|
59
|
+
def headers(self) -> dict:
|
|
60
|
+
return {"Content-Type": "application/json", "x-api-key": self._api_key}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class ApolloTransport(GraphQLTransport):
|
|
64
|
+
"""Apollo GraphQL server: optional Bearer token plus any extra headers."""
|
|
65
|
+
|
|
66
|
+
def __init__(self, url: str, token: Optional[str] = None, extra_headers: Optional[dict] = None,
|
|
67
|
+
timeout: int = DEFAULT_TIMEOUT_SECONDS):
|
|
68
|
+
super().__init__(url, timeout)
|
|
69
|
+
self._token = token
|
|
70
|
+
self._extra_headers = dict(extra_headers or {})
|
|
71
|
+
|
|
72
|
+
def headers(self) -> dict:
|
|
73
|
+
headers = {"Content-Type": "application/json", **self._extra_headers}
|
|
74
|
+
if self._token:
|
|
75
|
+
headers["Authorization"] = f"Bearer {self._token}"
|
|
76
|
+
return headers
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
PACKAGE_VERSION = "0.0.0"
|
|
File without changes
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
# logger-local needs these to start. In Circles repos they come from .env (ENVIRONMENT_NAME is set by .env or by Makec,
|
|
4
|
+
# never hardcoded here); these are only defaults for tests.
|
|
5
|
+
os.environ.setdefault("BRAND_NAME", "Circlez")
|
|
6
|
+
os.environ.setdefault("LOGGER_IS_WRITE_TO_SQL", "false")
|
generic_remote_graphql-0.0.3b4806/python_packages/generic_remote_graphql/tests/system/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""System test: talks to a REAL AppSync table (needs the environment). Skipped when it is not configured.
|
|
2
|
+
|
|
3
|
+
Needs in your .env: TEST_GRAPHQL_APPSYNC_URL and TEST_GRAPHQL_APPSYNC_API_KEY (names are a proposal, like the
|
|
4
|
+
<ENTITY>_GRAPHQL_APPSYNC_API_KEY of the TypeScript package; confirm with Tal), and a test table.
|
|
5
|
+
Objects created here must have is_test_data = true (Circles rule), hence is_test_data=True below.
|
|
6
|
+
"""
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
from generic_remote_graphql.src import AppSyncTransport, GenericRemoteGraphQL
|
|
10
|
+
|
|
11
|
+
our_get_env = pytest.importorskip("python_sdk_remote.utilities").our_get_env
|
|
12
|
+
|
|
13
|
+
TEST_TABLE_NAME = "Test_orm_table" # the table used by the TypeScript package tests
|
|
14
|
+
TEST_PRIMARY_KEY = "test_orm_id"
|
|
15
|
+
RETURN_FIELDS = "test_orm_id created_user_id updated_user_id end_timestamp"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@pytest.fixture(name="client")
|
|
19
|
+
def client_fixture():
|
|
20
|
+
url = our_get_env("TEST_GRAPHQL_APPSYNC_URL", raise_if_not_found=False)
|
|
21
|
+
api_key = our_get_env("TEST_GRAPHQL_APPSYNC_API_KEY", raise_if_not_found=False)
|
|
22
|
+
if not url or not api_key:
|
|
23
|
+
pytest.skip("TEST_GRAPHQL_APPSYNC_URL / TEST_GRAPHQL_APPSYNC_API_KEY are not set")
|
|
24
|
+
return GenericRemoteGraphQL(table_name=TEST_TABLE_NAME, primary_key_name=TEST_PRIMARY_KEY,
|
|
25
|
+
transport=AppSyncTransport(url, api_key), is_test_data=True)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def test_create_get_update_delete_cycle(client):
|
|
29
|
+
created = client.create(RETURN_FIELDS, {})
|
|
30
|
+
item_id = created[TEST_PRIMARY_KEY]
|
|
31
|
+
try:
|
|
32
|
+
assert client.get_by_id(item_id, RETURN_FIELDS)[TEST_PRIMARY_KEY] == item_id
|
|
33
|
+
client.update(RETURN_FIELDS, {TEST_PRIMARY_KEY: item_id})
|
|
34
|
+
deleted = client.delete(RETURN_FIELDS, {TEST_PRIMARY_KEY: item_id})
|
|
35
|
+
assert deleted["end_timestamp"] is not None
|
|
36
|
+
finally:
|
|
37
|
+
client.total_delete(RETURN_FIELDS, {TEST_PRIMARY_KEY: item_id})
|
generic_remote_graphql-0.0.3b4806/python_packages/generic_remote_graphql/tests/unit/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""End-to-end over REAL HTTP, but against a tiny GraphQL-like server that runs on this machine.
|
|
2
|
+
|
|
3
|
+
It proves the whole path (client -> transport -> HTTP -> JSON -> client) and the headers, without AWS.
|
|
4
|
+
It does NOT prove that the real AppSync schema accepts our queries; that needs a system test with a real key.
|
|
5
|
+
"""
|
|
6
|
+
import json
|
|
7
|
+
import re
|
|
8
|
+
import threading
|
|
9
|
+
from http import HTTPStatus
|
|
10
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
11
|
+
|
|
12
|
+
import pytest
|
|
13
|
+
import requests
|
|
14
|
+
|
|
15
|
+
from generic_remote_graphql.src.constants import END_TIMESTAMP_AUTO_NOW_VALUE
|
|
16
|
+
from generic_remote_graphql.src import (ApolloTransport, AppSyncTransport, GenericRemoteGraphQL,
|
|
17
|
+
GraphQLRequestError)
|
|
18
|
+
|
|
19
|
+
ROWS: dict = {}
|
|
20
|
+
SEEN_HEADERS: list = []
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class FakeGraphQLHandler(BaseHTTPRequestHandler):
|
|
24
|
+
def log_message(self, *args): # keep the test output quiet
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
def _send(self, status: HTTPStatus, payload: dict):
|
|
28
|
+
data = json.dumps(payload).encode()
|
|
29
|
+
self.send_response(status.value)
|
|
30
|
+
self.send_header("Content-Type", "application/json")
|
|
31
|
+
self.send_header("Content-Length", str(len(data)))
|
|
32
|
+
self.end_headers()
|
|
33
|
+
self.wfile.write(data)
|
|
34
|
+
|
|
35
|
+
def do_POST(self):
|
|
36
|
+
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
|
|
37
|
+
SEEN_HEADERS.append({k.lower(): v for k, v in self.headers.items()})
|
|
38
|
+
if self.headers.get("x-api-key") == "BAD" or self.headers.get("Authorization") == "Bearer BAD":
|
|
39
|
+
return self._send(HTTPStatus.UNAUTHORIZED, {"errors": [{"errorType": "UnauthorizedException"}]})
|
|
40
|
+
query, variables = body["query"], body["variables"]
|
|
41
|
+
operation = re.search(r"(query|mutation)\s+(\w+)", query).group(2)
|
|
42
|
+
if operation == "getOffer":
|
|
43
|
+
return self._send(HTTPStatus.OK, {"data": {"getOffer": ROWS.get(variables["id"])}})
|
|
44
|
+
if operation == "listOffers":
|
|
45
|
+
items = [row for row in ROWS.values() if "end_timestamp" not in row]
|
|
46
|
+
return self._send(HTTPStatus.OK, {"data": {"listOffers": {"items": items, "nextToken": None}}})
|
|
47
|
+
if operation == "createOffer":
|
|
48
|
+
row = {"offer_id": len(ROWS) + 1, **variables["createInput"]}
|
|
49
|
+
ROWS[row["offer_id"]] = row
|
|
50
|
+
return self._send(HTTPStatus.OK, {"data": {"createOffer": row}})
|
|
51
|
+
if operation == "updateOffer":
|
|
52
|
+
update = variables["updateInput"]
|
|
53
|
+
ROWS[update["offer_id"]].update(update)
|
|
54
|
+
return self._send(HTTPStatus.OK, {"data": {"updateOffer": ROWS[update["offer_id"]]}})
|
|
55
|
+
if operation == "deleteOffer":
|
|
56
|
+
return self._send(HTTPStatus.OK, {"data": {"deleteOffer": ROWS.pop(variables["deleteInput"]["offer_id"])}})
|
|
57
|
+
return self._send(HTTPStatus.OK, {"errors": [{"message": f"unknown operation {operation}"}]})
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@pytest.fixture()
|
|
61
|
+
def server_url():
|
|
62
|
+
ROWS.clear()
|
|
63
|
+
SEEN_HEADERS.clear()
|
|
64
|
+
server = HTTPServer(("127.0.0.1", 0), FakeGraphQLHandler)
|
|
65
|
+
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
|
66
|
+
thread.start()
|
|
67
|
+
yield f"http://127.0.0.1:{server.server_port}/graphql"
|
|
68
|
+
server.shutdown()
|
|
69
|
+
server.server_close()
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def make_client(url, transport=None):
|
|
73
|
+
return GenericRemoteGraphQL(table_name="Offer", primary_key_name="offer_id",
|
|
74
|
+
transport=transport or AppSyncTransport(url, "KEY"))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def test_full_crud_cycle_over_http(server_url):
|
|
78
|
+
client = make_client(server_url)
|
|
79
|
+
|
|
80
|
+
created = client.create("offer_id name", {"name": "Eilat"})
|
|
81
|
+
assert created["offer_id"] == 1 and created["created_user_id"] == 2
|
|
82
|
+
|
|
83
|
+
assert client.get_by_id(1, "offer_id name")["name"] == "Eilat"
|
|
84
|
+
assert [row["name"] for row in client.list_all("offer_id name")] == ["Eilat"]
|
|
85
|
+
|
|
86
|
+
client.update("offer_id name", {"offer_id": 1, "name": "Eilat 2"})
|
|
87
|
+
assert client.get_by_id(1, "offer_id name")["name"] == "Eilat 2"
|
|
88
|
+
|
|
89
|
+
client.delete("offer_id", {"offer_id": 1}) # soft delete: row stays, marked
|
|
90
|
+
assert ROWS[1]["end_timestamp"] == END_TIMESTAMP_AUTO_NOW_VALUE
|
|
91
|
+
assert list(client.list_all("offer_id", )) == [] # hidden from the list
|
|
92
|
+
|
|
93
|
+
client.total_delete("offer_id", {"offer_id": 1}) # real delete
|
|
94
|
+
assert client.get_by_id(1, "offer_id") is None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def test_appsync_header_really_travels(server_url):
|
|
98
|
+
make_client(server_url).get_by_id(1, "offer_id")
|
|
99
|
+
assert SEEN_HEADERS[0]["x-api-key"] == "KEY"
|
|
100
|
+
assert SEEN_HEADERS[0]["content-type"] == "application/json"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def test_apollo_header_really_travels(server_url):
|
|
104
|
+
client = make_client(server_url, ApolloTransport(server_url, token="TOK"))
|
|
105
|
+
client.get_by_id(1, "offer_id")
|
|
106
|
+
assert SEEN_HEADERS[0]["authorization"] == "Bearer TOK"
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def test_wrong_key_gives_readable_error(server_url):
|
|
110
|
+
transport = AppSyncTransport(server_url, "BAD")
|
|
111
|
+
with pytest.raises(requests.HTTPError, match="UnauthorizedException"):
|
|
112
|
+
transport.execute("query getOffer($id: Int!) { getOffer(offer_id: $id) { offer_id } }", {"id": 1})
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def test_graphql_error_in_a_200_answer_is_raised(server_url):
|
|
116
|
+
transport = AppSyncTransport(server_url, "KEY")
|
|
117
|
+
with pytest.raises(GraphQLRequestError, match="unknown operation"):
|
|
118
|
+
transport.execute("query getNothing($id: Int!) { getNothing(id: $id) { id } }", {"id": 1})
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"""Unit tests: no network, no DB. A fake transport records what the client sends."""
|
|
2
|
+
from http import HTTPStatus
|
|
3
|
+
from unittest.mock import MagicMock, patch
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from generic_remote_graphql.src import (ApolloTransport, AppSyncTransport, GenericRemoteGraphQL,
|
|
8
|
+
GraphQLRequestError)
|
|
9
|
+
from generic_remote_graphql.src import graphql_requests as q
|
|
10
|
+
from generic_remote_graphql.src.constants import END_TIMESTAMP_AUTO_NOW_VALUE, TEMPORARY_AUTO_USER_ID
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class FakeTransport:
|
|
14
|
+
def __init__(self, data=None):
|
|
15
|
+
self.data = data or {}
|
|
16
|
+
self.calls = []
|
|
17
|
+
|
|
18
|
+
def execute(self, query, variables=None):
|
|
19
|
+
self.calls.append((query, variables))
|
|
20
|
+
return self.data
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def make_client(data=None, user_id=None):
|
|
24
|
+
transport = FakeTransport(data)
|
|
25
|
+
client = GenericRemoteGraphQL(table_name="Offer", primary_key_name="offer_id",
|
|
26
|
+
transport=transport, user_id=user_id)
|
|
27
|
+
return client, transport
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
# ---- query text (same shapes as the TypeScript package) ----
|
|
31
|
+
|
|
32
|
+
def test_get_query_uses_primary_key_name():
|
|
33
|
+
text = q.get_query("Offer", "offer_id name", "offer_id")
|
|
34
|
+
assert "query getOffer($id: Int!)" in text
|
|
35
|
+
assert "getOffer(offer_id: $id)" in text
|
|
36
|
+
assert "offer_id name" in text
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def test_list_query_adds_next_token_only_when_given():
|
|
40
|
+
assert "nextToken:" not in q.list_query("Offer", "name")
|
|
41
|
+
assert 'nextToken: "abc"' in q.list_query("Offer", "name", "abc")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@pytest.mark.parametrize("builder,word", [(q.create_query, "createOffer"), (q.update_query, "updateOffer"),
|
|
45
|
+
(q.delete_query, "deleteOffer")])
|
|
46
|
+
def test_mutations_are_named_after_the_table(builder, word):
|
|
47
|
+
assert f"mutation {word}" in builder("Offer", "offer_id")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
# ---- client ----
|
|
51
|
+
|
|
52
|
+
def test_get_by_id_returns_the_item():
|
|
53
|
+
client, transport = make_client({"getOffer": {"offer_id": 7, "name": "Eilat"}})
|
|
54
|
+
assert client.get_by_id(7, "offer_id name") == {"offer_id": 7, "name": "Eilat"}
|
|
55
|
+
assert transport.calls[0][1] == {"id": 7}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def test_list_uses_default_limit_and_returns_items_and_token():
|
|
59
|
+
client, transport = make_client({"listOffers": {"items": [{"name": "a"}], "nextToken": "t1"}})
|
|
60
|
+
result = client.list_items("name")
|
|
61
|
+
assert result == {"items": [{"name": "a"}], "nextToken": "t1"}
|
|
62
|
+
variables = transport.calls[0][1]
|
|
63
|
+
assert variables["limit"] == client.list_items_limit and variables["filter"] == {}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def test_list_empty_answer_is_an_empty_page():
|
|
67
|
+
client, _ = make_client({})
|
|
68
|
+
assert client.list_items("name") == {"items": [], "nextToken": None}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def test_create_adds_default_user_ids():
|
|
72
|
+
client, transport = make_client({"createOffer": {"offer_id": 1}})
|
|
73
|
+
client.create("offer_id", {"name": "x"})
|
|
74
|
+
sent = transport.calls[0][1]["createInput"]
|
|
75
|
+
assert sent == {"name": "x", "created_user_id": TEMPORARY_AUTO_USER_ID,
|
|
76
|
+
"updated_user_id": TEMPORARY_AUTO_USER_ID}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def test_create_sends_is_test_data_only_when_asked():
|
|
80
|
+
plain, plain_transport = make_client({"createOffer": {}})
|
|
81
|
+
plain.create("offer_id", {"name": "x"})
|
|
82
|
+
assert "is_test_data" not in plain_transport.calls[0][1]["createInput"]
|
|
83
|
+
|
|
84
|
+
transport = FakeTransport({"createOffer": {}})
|
|
85
|
+
test_client = GenericRemoteGraphQL(table_name="Offer", primary_key_name="offer_id",
|
|
86
|
+
transport=transport, is_test_data=True)
|
|
87
|
+
test_client.create("offer_id", {"name": "x"})
|
|
88
|
+
assert transport.calls[0][1]["createInput"]["is_test_data"] is True
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def test_create_uses_given_user_id():
|
|
92
|
+
client, transport = make_client({"createOffer": {}}, user_id=55)
|
|
93
|
+
client.create("offer_id", {"name": "x"})
|
|
94
|
+
assert transport.calls[0][1]["createInput"]["created_user_id"] == 55
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def test_delete_is_a_soft_delete_through_update():
|
|
98
|
+
client, transport = make_client({"updateOffer": {"offer_id": 3}})
|
|
99
|
+
client.delete("offer_id", {"offer_id": 3})
|
|
100
|
+
query, variables = transport.calls[0]
|
|
101
|
+
assert "mutation updateOffer" in query
|
|
102
|
+
assert variables["updateInput"]["end_timestamp"] == END_TIMESTAMP_AUTO_NOW_VALUE
|
|
103
|
+
assert variables["updateInput"]["offer_id"] == 3
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def test_total_delete_really_deletes():
|
|
107
|
+
client, transport = make_client({"deleteOffer": {"offer_id": 3}})
|
|
108
|
+
client.total_delete("offer_id", {"offer_id": 3})
|
|
109
|
+
assert "mutation deleteOffer" in transport.calls[0][0]
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def test_update_without_user_does_not_invent_updated_user_id():
|
|
113
|
+
"""Same as TypeScript: no user context => updated_user_id is not added by update()."""
|
|
114
|
+
client, transport = make_client({"updateOffer": {}})
|
|
115
|
+
client.update("offer_id", {"offer_id": 3, "name": "n"})
|
|
116
|
+
assert "updated_user_id" not in transport.calls[0][1]["updateInput"]
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def test_update_with_user_adds_updated_user_id():
|
|
120
|
+
client, transport = make_client({"updateOffer": {}}, user_id=9)
|
|
121
|
+
client.update("offer_id", {"offer_id": 3})
|
|
122
|
+
assert transport.calls[0][1]["updateInput"]["updated_user_id"] == 9
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def test_delete_always_sends_updated_user_id():
|
|
126
|
+
client, transport = make_client({"updateOffer": {}})
|
|
127
|
+
client.delete("offer_id", {"offer_id": 3})
|
|
128
|
+
assert transport.calls[0][1]["updateInput"]["updated_user_id"] == TEMPORARY_AUTO_USER_ID
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def test_next_token_with_quote_cannot_break_the_query():
|
|
132
|
+
text = q.list_query("Offer", "name", 'a"b')
|
|
133
|
+
assert 'nextToken: "a\\"b"' in text
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def test_inputs_are_not_modified_by_the_client():
|
|
137
|
+
client, _ = make_client({"createOffer": {}})
|
|
138
|
+
original = {"name": "x"}
|
|
139
|
+
client.create("offer_id", original)
|
|
140
|
+
assert original == {"name": "x"}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class PagedTransport:
|
|
144
|
+
"""Returns 3 pages: tokens None -> "p2" -> "p3" -> None."""
|
|
145
|
+
|
|
146
|
+
def __init__(self):
|
|
147
|
+
self.tokens = []
|
|
148
|
+
|
|
149
|
+
def execute(self, query, variables=None):
|
|
150
|
+
token = variables["nextToken"]
|
|
151
|
+
self.tokens.append(token)
|
|
152
|
+
pages = {"": ("p2", [1, 2]), "p2": ("p3", [3, 4]), "p3": (None, [5])}
|
|
153
|
+
next_token, items = pages[token]
|
|
154
|
+
return {"listOffers": {"items": [{"id": i} for i in items], "nextToken": next_token}}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def test_list_all_follows_every_page():
|
|
158
|
+
transport = PagedTransport()
|
|
159
|
+
client = GenericRemoteGraphQL(table_name="Offer", primary_key_name="offer_id", transport=transport)
|
|
160
|
+
assert [item["id"] for item in client.list_all("id")] == [1, 2, 3, 4, 5]
|
|
161
|
+
assert transport.tokens == ["", "p2", "p3"]
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def test_list_all_stops_an_endless_server():
|
|
165
|
+
class Endless:
|
|
166
|
+
def execute(self, query, variables=None):
|
|
167
|
+
return {"listOffers": {"items": [], "nextToken": "again"}}
|
|
168
|
+
|
|
169
|
+
client = GenericRemoteGraphQL(table_name="Offer", primary_key_name="offer_id", transport=Endless())
|
|
170
|
+
with pytest.raises(RuntimeError, match="stopped after 3 pages"):
|
|
171
|
+
list(client.list_all("id", max_pages=3))
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
# ---- transports ----
|
|
175
|
+
|
|
176
|
+
def test_appsync_sends_api_key_header_and_returns_data():
|
|
177
|
+
response = MagicMock()
|
|
178
|
+
response.json.return_value = {"data": {"getOffer": {"offer_id": 1}}}
|
|
179
|
+
with patch("generic_remote_graphql.src.transports.OurRequest.post", return_value=response) as post:
|
|
180
|
+
data = AppSyncTransport("https://x/graphql", "KEY").execute("query {}", {"id": 1})
|
|
181
|
+
assert data == {"getOffer": {"offer_id": 1}}
|
|
182
|
+
assert post.call_args.kwargs["headers"]["x-api-key"] == "KEY"
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def test_appsync_without_key_fails_early():
|
|
186
|
+
with pytest.raises(ValueError):
|
|
187
|
+
AppSyncTransport("https://x/graphql", "")
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def test_apollo_sends_bearer_token_and_extra_headers():
|
|
191
|
+
headers = ApolloTransport("https://x", token="T", extra_headers={"x-a": "1"}).headers()
|
|
192
|
+
assert headers["Authorization"] == "Bearer T" and headers["x-a"] == "1"
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def test_http_error_includes_what_the_server_said():
|
|
196
|
+
import requests as real_requests
|
|
197
|
+
response = MagicMock()
|
|
198
|
+
response.text = '{"errors":[{"errorType":"UnauthorizedException"}]}'
|
|
199
|
+
# OurRequest.post raises the HTTPError itself (raise_for_status); the transport adds what the server said
|
|
200
|
+
error = real_requests.HTTPError(f"{HTTPStatus.UNAUTHORIZED.value} Client Error", response=response)
|
|
201
|
+
with patch("generic_remote_graphql.src.transports.OurRequest.post", side_effect=error):
|
|
202
|
+
with pytest.raises(real_requests.HTTPError, match="UnauthorizedException"):
|
|
203
|
+
AppSyncTransport("https://x", "KEY").execute("query {}")
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def test_answer_that_is_not_json_raises_a_clear_exception():
|
|
207
|
+
response = MagicMock()
|
|
208
|
+
response.text = "<html>Bad gateway</html>"
|
|
209
|
+
response.json.side_effect = ValueError("no json")
|
|
210
|
+
with patch("generic_remote_graphql.src.transports.OurRequest.post", return_value=response):
|
|
211
|
+
with pytest.raises(GraphQLRequestError, match="not JSON"):
|
|
212
|
+
AppSyncTransport("https://x", "KEY").execute("query {}")
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def test_graphql_errors_raise_a_clear_exception():
|
|
216
|
+
response = MagicMock()
|
|
217
|
+
response.json.return_value = {"errors": [{"message": "boom"}]}
|
|
218
|
+
with patch("generic_remote_graphql.src.transports.OurRequest.post", return_value=response):
|
|
219
|
+
with pytest.raises(GraphQLRequestError, match="boom"):
|
|
220
|
+
AppSyncTransport("https://x", "KEY").execute("query {}")
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
# Requirements for Tests/Testing (Do not add to setup.py install_requires)
|
|
2
|
+
pytest # https://pypi.org/project/pytest/
|
|
3
|
+
pytest-cov # This is used by MakePy.ps1 pytest to simulate the tests running in GHA and save us time and money
|
|
4
|
+
mypy # python-guidelines: every mypy error must be fixed
|
|
5
|
+
types-requests
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# devDependencies (packages for development/testing), production/runtime dependencies in setup.py
|
|
2
|
+
# TODO: add the packages that your package depends on here and in setup.py
|
|
3
|
+
# (everything listed in the imports)
|
|
4
|
+
|
|
5
|
+
# In local-package uncomment the bellow line
|
|
6
|
+
# smart-datastore-local
|
|
7
|
+
|
|
8
|
+
logger-local>=0.0.195 # https://pypi.org/project/logger-local/
|
|
9
|
+
python-sdk-remote>=0.0.216
|
|
10
|
+
|
|
11
|
+
# All packages for tests should be in requirements-dev.txt and not here
|
|
12
|
+
requests>=2.31.0
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# serverless.com repo "python -m build" works without setup.py
|
|
2
|
+
# Should update package_dir if not using our recommended directory structure
|
|
3
|
+
|
|
4
|
+
import setuptools
|
|
5
|
+
|
|
6
|
+
# For reading the version my_package/_version.py or my_package/__init__.py
|
|
7
|
+
|
|
8
|
+
import codecs
|
|
9
|
+
import os
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def read(rel_path):
|
|
13
|
+
here = os.path.abspath(os.path.dirname(__file__))
|
|
14
|
+
with codecs.open(os.path.join(here, rel_path), 'r') as fp:
|
|
15
|
+
return fp.read()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def get_version(rel_path):
|
|
19
|
+
for line in read(rel_path).splitlines():
|
|
20
|
+
if line.startswith('__version__'):
|
|
21
|
+
return line.split('"')[1] # או "'" בהתאם לשימוש
|
|
22
|
+
raise RuntimeError("Unable to find version string.")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
# TODO: Change the PACKAGE_NAME to the package's name - Either xxx-local or
|
|
26
|
+
# xxx-remote (without the -python-package suffix). Only lowercase, no
|
|
27
|
+
# underlines.
|
|
28
|
+
# Used by pypa/gh-action-pypi-publish
|
|
29
|
+
# Package Name should be identical to the inner directory name
|
|
30
|
+
# Changing the package name here, will cause a change in the package directory
|
|
31
|
+
# name as well
|
|
32
|
+
# PACKAGE_NAME should be singular if handling only one instance
|
|
33
|
+
# PACKAGE_NAME should not include the word "main"
|
|
34
|
+
|
|
35
|
+
# e.g.: queue-local, without python-package suffix
|
|
36
|
+
PACKAGE_NAME = "generic-remote-graphql" # TODO: According to GitFlow, in the Feature Branch, please update the Jira Work Item ID after the letter "b" according to simver.org
|
|
37
|
+
|
|
38
|
+
package_dir = PACKAGE_NAME.replace("-", "_")
|
|
39
|
+
# If we need backward-compatible:
|
|
40
|
+
# old_package_dir = "old_package_name"
|
|
41
|
+
|
|
42
|
+
PACKAGE_DESCRIPTION = f"PyPI {PACKAGE_NAME} Python Package owned by Circlez.ai"
|
|
43
|
+
NEW_LINE = "\n" # the template used NEW_LINE below without defining it
|
|
44
|
+
|
|
45
|
+
setuptools.setup(
|
|
46
|
+
license='MIT',
|
|
47
|
+
name=PACKAGE_NAME,
|
|
48
|
+
# Increase this number every time you make a change
|
|
49
|
+
# want to publish. After 0.0.9 switch to 0.0.10 and not 0.1.0
|
|
50
|
+
# version can't be 0.0.
|
|
51
|
+
# If you find yourself increasing the version in more than one patch number (it might indicate there are multiple branches, which you should submit their PRs before your PR) # noqa: E501
|
|
52
|
+
# Updating the bBU-4806 done automatically by makec.ps1 / make_py.ps1
|
|
53
|
+
# TODO add the Jira Work Item (Jira Issue) number after the version, i.e., 0.0.1b2432
|
|
54
|
+
# TODO: According to GitFlow, in the Feature Branch, please update after the letter 'b' the Jira Work Item ID, and in the exceptional case you can't get a Jira Work Item directly or using the Slack Channel, please use the PR number. Semantic Version simver.org
|
|
55
|
+
version="0.0.3b4806", # https://pypi.org/project/generic-remote-graphql#History
|
|
56
|
+
author="Circles",
|
|
57
|
+
author_email="info@circlez.ai",
|
|
58
|
+
description=f"{PACKAGE_DESCRIPTION}",
|
|
59
|
+
# long_description=f"{description}",
|
|
60
|
+
long_description =f"{PACKAGE_DESCRIPTION}" + NEW_LINE # noqa E501
|
|
61
|
+
+ "JIRA Work Item: https://circles-zone.atlassian.net/browse/BU-4806" + NEW_LINE # noqa E501
|
|
62
|
+
+ "GHA: https://github.com/circles-zone/generic-remote-graphql-python-package/actions", # noqa E501
|
|
63
|
+
|
|
64
|
+
long_description_content_type='text/markdown',
|
|
65
|
+
url=f"https://github.com/circles-zone/{PACKAGE_NAME}-python-package",
|
|
66
|
+
packages=[package_dir],
|
|
67
|
+
# packages=[package_dir, old_package_dir],
|
|
68
|
+
|
|
69
|
+
# I'm not sure we need package_dir
|
|
70
|
+
package_dir={package_dir: f'python_packages/{package_dir}/src'},
|
|
71
|
+
# TODO Unfortunately in event-main-local-restapi there are no
|
|
72
|
+
# repo-directory and no package directory (flat directory structure)
|
|
73
|
+
# package_dir={package_dir: f'src'},
|
|
74
|
+
|
|
75
|
+
# package_dir={package_dir: f'{package_dir}/src',
|
|
76
|
+
# old_package_dir: f'{package_dir}/src'},
|
|
77
|
+
package_data={package_dir: ['*.py']},
|
|
78
|
+
classifiers=[
|
|
79
|
+
"Programming Language :: Python :: 3",
|
|
80
|
+
# https://packaging.python.org/en/latest/guides/writing-pyproject-toml/#license
|
|
81
|
+
# TODO Fix all repos, especially the Python templates
|
|
82
|
+
#
|
|
83
|
+
"Operating System :: OS Independent",
|
|
84
|
+
],
|
|
85
|
+
# Do not add packages needed only for tests, i.e., packages for get_test_xxx(
|
|
86
|
+
# TODO: Update which packages to include with this package in production
|
|
87
|
+
# (dependencies) - Not for development/testing
|
|
88
|
+
install_requires=[
|
|
89
|
+
'requests>=2.31.0',
|
|
90
|
+
'python-sdk-remote>=0.0.216',
|
|
91
|
+
# TODO: in -remote package, please use logger-remote instead.
|
|
92
|
+
'logger-local>=0.0.195',
|
|
93
|
+
# TODO: In -local package, please uncomment the line below. In -remote packages, please delete this line. # noqa E501
|
|
94
|
+
# 'smart-datastore-local',
|
|
95
|
+
# 'logzio-python-handler>=4.1.2', # https://pypi.org/project/logzio-python-handler/ # noqa E501
|
|
96
|
+
]
|
|
97
|
+
)
|
|
98
|
+
|