Repository: LuisLuii/FastAPIQuickCRUD Branch: main Commit: 2f959d815ad6 Files: 212 Total size: 2.9 MB Directory structure: gitextract_k7u649z0/ ├── .coveragerc ├── .github/ │ └── workflows/ │ ├── ci.yml │ ├── coverage.yml │ └── release.yml ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── README_zh.md ├── __init__.py ├── __main__.py ├── setup.py ├── src/ │ ├── __init__.py │ └── fastapi_quickcrud/ │ ├── __init__.py │ ├── crud_router.py │ └── misc/ │ ├── __init__.py │ ├── abstract_execute.py │ ├── abstract_parser.py │ ├── abstract_query.py │ ├── abstract_route.py │ ├── covert_model.py │ ├── crud_model.py │ ├── exceptions.py │ ├── memory_sql.py │ ├── schema_builder.py │ ├── type.py │ └── utils.py ├── tests/ │ ├── __init__.py │ ├── conf/ │ │ ├── __init__.py │ │ ├── config.py │ │ ├── dev.docker-compose.yml │ │ └── dev.env │ └── test_implementations/ │ ├── __init__.py │ ├── other/ │ │ └── __init__.py │ ├── test_memory_sqlalchemy/ │ │ ├── __init__.py │ │ ├── api_async_test/ │ │ │ ├── __init__.py │ │ │ ├── foreign_tree/ │ │ │ │ ├── __init__.py │ │ │ │ └── test_relationship_m2m.py │ │ │ ├── test_create_many_api.py │ │ │ ├── test_create_one_api.py │ │ │ ├── test_delete_many_api.py │ │ │ ├── test_delete_one_api.py │ │ │ ├── test_get_many_api.py │ │ │ ├── test_get_one_api.py │ │ │ ├── test_other_default_value.py │ │ │ ├── test_other_set_description.py │ │ │ ├── test_other_single_unique.py │ │ │ ├── test_patch_many_api.py │ │ │ ├── test_patch_one_api.py │ │ │ ├── test_post_redirect_get_api.py │ │ │ ├── test_put_many_api.py │ │ │ └── test_put_one_api.py │ │ ├── api_test/ │ │ │ ├── __init__.py │ │ │ ├── foreign_tree/ │ │ │ │ ├── __init__.py │ │ │ │ └── test_relationship_m2m.py │ │ │ ├── join_relationship/ │ │ │ │ ├── __init__.py │ │ │ │ ├── test_relationship_extra.py │ │ │ │ ├── test_relationship_m2m.py │ │ │ │ ├── test_relationship_m2m_back_populates.py │ │ │ │ ├── test_relationship_m2o.py │ │ │ │ ├── test_relationship_m2o_back_populates.py │ │ │ │ ├── test_relationship_m2o_back_refer.py │ │ │ │ ├── test_relationship_o2m.py │ │ │ │ ├── test_relationship_o2m_back_populates.py │ │ │ │ ├── test_relationship_o2m_back_ref.py │ │ │ │ └── test_relationship_o2o.py │ │ │ ├── test_create_many_api.py │ │ │ ├── test_create_one_api.py │ │ │ ├── test_delete_many_api.py │ │ │ ├── test_delete_one_api.py │ │ │ ├── test_get_many_api.py │ │ │ ├── test_get_one_api.py │ │ │ ├── test_other_default_value.py │ │ │ ├── test_other_set_description.py │ │ │ ├── test_other_single_unique.py │ │ │ ├── test_patch_many_api.py │ │ │ ├── test_patch_one_api.py │ │ │ ├── test_post_redirect_get_api.py │ │ │ ├── test_put_many_api.py │ │ │ └── test_put_one_api.py │ │ └── error_test/ │ │ ├── __init__.py │ │ ├── test_create_null_type.py │ │ ├── test_create_specific_api_when_no_pk.py │ │ ├── test_create_table_with_more_than_one_unique_but_no_use_composite.py │ │ ├── test_use_blob_type_column.py │ │ ├── test_use_composite_primary.py │ │ ├── test_use_more_than_one_pk.py │ │ ├── test_use_more_than_one_unique.py │ │ ├── test_use_unique_and_composite_unique.py │ │ ├── test_use_unsupported_type_pk.py │ │ ├── test_use_unsupported_type_pk_2.py │ │ ├── test_use_unsupported_type_pk_3.py │ │ └── test_use_unsupported_type_pk_4.py │ ├── test_sqlalchemy/ │ │ ├── __init__.py │ │ ├── api_test/ │ │ │ ├── __init__.py │ │ │ ├── join_relationship/ │ │ │ │ ├── __init__.py │ │ │ │ ├── test_relationship_m2m.py │ │ │ │ ├── test_relationship_m2m_back_populates.py │ │ │ │ ├── test_relationship_m2o.py │ │ │ │ ├── test_relationship_m2o_back_populates.py │ │ │ │ ├── test_relationship_m2o_back_refer.py │ │ │ │ ├── test_relationship_o2m.py │ │ │ │ ├── test_relationship_o2m_back_populates.py │ │ │ │ ├── test_relationship_o2m_back_ref.py │ │ │ │ └── test_relationship_o2o.py │ │ │ ├── test_create_many_api.py │ │ │ ├── test_create_one_api.py │ │ │ ├── test_delete_many_api.py │ │ │ ├── test_delete_one_api.py │ │ │ ├── test_get_many_api.py │ │ │ ├── test_get_one_api.py │ │ │ ├── test_other_default_value.py │ │ │ ├── test_other_set_description.py │ │ │ ├── test_other_single_unique.py │ │ │ ├── test_other_uuid_primary.py │ │ │ ├── test_patch_many_api.py │ │ │ ├── test_patch_one_api.py │ │ │ ├── test_post_redirect_get_api.py │ │ │ ├── test_put_many_api.py │ │ │ └── test_put_one_api.py │ │ ├── api_test_async/ │ │ │ ├── __init__.py │ │ │ ├── test_create_many_api.py │ │ │ ├── test_create_one_api.py │ │ │ ├── test_delete_many_api.py │ │ │ ├── test_delete_one_api.py │ │ │ ├── test_get_many_api.py │ │ │ ├── test_get_one_api.py │ │ │ ├── test_other_default_value.py │ │ │ ├── test_other_single_unique.py │ │ │ ├── test_other_uuid_primary.py │ │ │ ├── test_patch_many_api.py │ │ │ ├── test_patch_one_api.py │ │ │ ├── test_post_redirect_get_api.py │ │ │ ├── test_put_many_api.py │ │ │ └── test_put_one_api.py │ │ └── error_test/ │ │ ├── __init__.py │ │ ├── test_create_null_type.py │ │ ├── test_create_specific_api_when_no_pk.py │ │ ├── test_create_table_with_more_than_one_unique_but_no_use_composite.py │ │ ├── test_use_blob_type_column.py │ │ ├── test_use_composite_primary.py │ │ ├── test_use_more_than_one_pk.py │ │ ├── test_use_more_than_one_unique.py │ │ ├── test_use_unique_and_composite_unique.py │ │ ├── test_use_unsupported_type_pk.py │ │ ├── test_use_unsupported_type_pk_2.py │ │ ├── test_use_unsupported_type_pk_3.py │ │ └── test_use_unsupported_type_pk_4.py │ └── test_sqlalchemy_table/ │ ├── __init__.py │ ├── api_test/ │ │ ├── __init__.py │ │ ├── test_delete_many_api.py │ │ ├── test_delete_one_api.py │ │ ├── test_get_many_api.py │ │ ├── test_get_one_api.py │ │ ├── test_other_no_alias.py │ │ ├── test_other_set_description.py │ │ ├── test_other_single_unique.py │ │ ├── test_other_user_default_value.py │ │ ├── test_other_uuid_primary.py │ │ ├── test_patch_many_api.py │ │ ├── test_patch_one_api.py │ │ ├── test_post_redirect_get_api.py │ │ ├── test_put_many_api.py │ │ ├── test_put_one_api.py │ │ ├── test_upsert_many_api.py │ │ └── test_upsert_one_api.py │ ├── api_test_async/ │ │ ├── __init__.py │ │ ├── test_create_many_api.py │ │ ├── test_create_one_api.py │ │ ├── test_delete_many_api.py │ │ ├── test_delete_one_api.py │ │ ├── test_get_many_api.py │ │ ├── test_get_one_api.py │ │ ├── test_other_default_value.py │ │ ├── test_other_no_alias.py │ │ ├── test_other_single_unique.py │ │ ├── test_other_uuid_primary.py │ │ ├── test_patch_many_api.py │ │ ├── test_patch_one_api.py │ │ ├── test_post_redirect_get_api.py │ │ ├── test_put_many_api.py │ │ └── test_put_one_api.py │ └── error_test/ │ ├── __init__.py │ ├── test_create_null_type.py │ ├── test_pk_no_default_value.py │ ├── test_use_composite_primary.py │ ├── test_use_more_than_one_pk.py │ ├── test_use_more_than_one_unique.py │ ├── test_use_unique_and_composite_unique.py │ ├── test_use_unsupported_type.py │ ├── test_use_unsupported_type_2.py │ ├── test_use_unsupported_type_3.py │ └── test_use_unsupported_type_4.py └── tutorial/ ├── __init__.py ├── basic_usage/ │ ├── __init__.py │ ├── depencies_example_auth.py │ ├── quick_usage_with_async_SQLALchemy_Base.py │ ├── quick_usage_with_async_SQLALchemy_table.py │ ├── quick_usage_with_async_SQLALchemy_table_with_out_primary_key.py │ └── quick_usage_with_sync_SQLAlchemy_Base.py ├── foreign_tree/ │ ├── __init__.py │ ├── async_m2m.py │ ├── m2m.py │ └── sample_tree.py ├── relationship/ │ ├── __init__.py │ ├── many_to_many.py │ ├── many_to_one.py │ ├── one_to_many.py │ └── one_to_one.py ├── sample.py ├── sample_case.py └── sample_two_table.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .coveragerc ================================================ [report] show_missing = True omit = /usr/* venv/* tests/* src/fastapi_quickcrud/misc/abstract_execute.py src/fastapi_quickcrud/misc/abstract_query.py # Regexes for lines to exclude from consideration exclude_lines = raise NotImplementedError self._exclude_column = \[\] if __name__ == .__main__.: pass session.expire_all() return async_execute_and_expire_result if 'duplicate key value violates unique constraint' not in err_msg: raise UnknownError(f'Unknown error, {i}') response_result = await parsing_service.async_find_one return response_result parsed_response = await parsing_service.async_find_many* return await parsing_service.async_upsert_one* return await parsing_service.async_upsert_many* return await parsing_service.async_delete_one* return await parsing_service.async_delete_many* return await result_parser.async_post_redirect_get* return await result_parser.async_update_one* return await result_parser.async_patch_many* return await result_parser.async_update_one* return await result_parser.async_update_many* return result raise FindOneApiNotRegister* return RedirectResponse.*?redirect_url raise QueryOperatorNotFound(f'The query operator of {column_name} not found!') raise InvalidRequestMethod(f'{request_method} is not an available request method') raise RequestMissing* raise InvalidRequestMethod.*?f'{value} is not an available request method, Please use CrudMethods delattr(received_insert, received_insert_item) delattr(request_or_response_object, name) routes_source = SQLAlchemyNotSupportRouteSource query_service = SQLAlchemyNotSupportQueryService ================================================ FILE: .github/workflows/ci.yml ================================================ # This is a basic workflow to help you get started with Actions name: Unit testing in 🐍3.7/8/9/10 # Controls when the workflow will run on: push: branches: [ "main", "develop", "feature/*" ] pull_request: branches: [ "main", "develop" ] # Allows you to run this workflow manually from the Actions tab workflow_dispatch: # A workflow run is made up of one or more jobs that can run sequentially or in parallel jobs: ciPython37: runs-on: ubuntu-latest strategy: matrix: python-version: [ 3.7 ] services: postgres: image: postgres:11 env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: ci_db_test ports: - 5432:5432 options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v1 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Enable Postgres Trigram Extension run: | PGPASSWORD=postgres psql -U postgres -h 127.0.0.1 -p ${{ job.services.postgres.ports[5432] }} -d ci_db_test -c "CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";" - name: Test with unittest env: TEST_DATABASE_URL: postgresql://postgres:postgres@localhost/ci_db_test TEST_DATABASE_ASYNC_URL: postgresql+asyncpg://postgres:postgres@localhost/ci_db_test run: | python -m unittest discover -s ./tests/test_implementations ciPython38: runs-on: ubuntu-latest strategy: matrix: python-version: [ 3.8 ] services: postgres: image: postgres:11 env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: ci_db_test ports: - 5432:5432 options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v1 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Enable Postgres Trigram Extension run: | PGPASSWORD=postgres psql -U postgres -h 127.0.0.1 -p ${{ job.services.postgres.ports[5432] }} -d ci_db_test -c "CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";" - name: Test with unittest env: TEST_DATABASE_URL: postgresql://postgres:postgres@localhost/ci_db_test TEST_DATABASE_ASYNC_URL: postgresql+asyncpg://postgres:postgres@localhost/ci_db_test run: | python -m unittest discover -s ./tests/test_implementations ciPython39: runs-on: ubuntu-latest strategy: matrix: python-version: [ 3.9 ] services: postgres: image: postgres:11 env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: ci_db_test ports: - 5432:5432 options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v1 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Enable Postgres Trigram Extension run: | PGPASSWORD=postgres psql -U postgres -h 127.0.0.1 -p ${{ job.services.postgres.ports[5432] }} -d ci_db_test -c "CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";" - name: Test with unittest env: TEST_DATABASE_URL: postgresql://postgres:postgres@localhost/ci_db_test TEST_DATABASE_ASYNC_URL: postgresql+asyncpg://postgres:postgres@localhost/ci_db_test run: | python -m unittest discover -s ./tests/test_implementations ciPython310: runs-on: ubuntu-latest strategy: matrix: python-version: [ '3.10' ] services: postgres: image: postgres:11 env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: ci_db_test ports: - 5432:5432 options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v1 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Enable Postgres Trigram Extension run: | PGPASSWORD=postgres psql -U postgres -h 127.0.0.1 -p ${{ job.services.postgres.ports[5432] }} -d ci_db_test -c "CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";" - name: Test with unittest env: TEST_DATABASE_URL: postgresql://postgres:postgres@localhost/ci_db_test TEST_DATABASE_ASYNC_URL: postgresql+asyncpg://postgres:postgres@localhost/ci_db_test run: | python -m unittest discover -s ./tests/test_implementations ================================================ FILE: .github/workflows/coverage.yml ================================================ # This is a basic workflow to help you get started with Actions name: Coverage # Controls when the workflow will run on: push: branches: [ "main", "develop" ] pull_request: branches: [ "main", "develop" ] # Allows you to run this workflow manually from the Actions tab workflow_dispatch: # A workflow run is made up of one or more jobs that can run sequentially or in parallel jobs: Coverage: runs-on: ubuntu-latest strategy: matrix: python-version: [ '3.10' ] services: postgres: image: postgres:11 env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: ci_db_test ports: - 5432:5432 options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@master - name: Set github token run: echo "GITHUB_TOKEN=${{ secrets.GIT_TOKEN }}" >> $GITHUB_ENV - name: Set coveralls token run: echo "COVERALLS_REPO_TOKEN=${{ secrets.COVERALLS_REPO_TOKEN }}" >> $GITHUB_ENV - name: Enable Postgres Trigram Extension run: | PGPASSWORD=postgres psql -U postgres -h 127.0.0.1 -p ${{ job.services.postgres.ports[5432] }} -d ci_db_test -c "CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";" - name: pip install, make coverage env: TEST_DATABASE_URL: postgresql://postgres:postgres@localhost/ci_db_test TEST_DATABASE_ASYNC_URL: postgresql+asyncpg://postgres:postgres@localhost/ci_db_test run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install coverage pip install coveralls python -m coverage run -m unittest coveralls ================================================ FILE: .github/workflows/release.yml ================================================ # This is a basic workflow to help you get started with Actions name: Publish Python 🐍 distributions 📦 to PyPI on: push: tags: - '**' jobs: ciPython37: runs-on: ubuntu-latest strategy: matrix: python-version: [ 3.7 ] services: postgres: image: postgres:11 env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: ci_db_test ports: - 5432:5432 options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v1 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Enable Postgres Trigram Extension run: | PGPASSWORD=postgres psql -U postgres -h 127.0.0.1 -p ${{ job.services.postgres.ports[5432] }} -d ci_db_test -c "CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";" - name: Test with unittest env: TEST_DATABASE_URL: postgresql://postgres:postgres@localhost/ci_db_test TEST_DATABASE_ASYNC_URL: postgresql+asyncpg://postgres:postgres@localhost/ci_db_test run: | python -m unittest discover -s ./tests/test_implementations ciPython38: runs-on: ubuntu-latest strategy: matrix: python-version: [ 3.8 ] services: postgres: image: postgres:11 env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: ci_db_test ports: - 5432:5432 options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v1 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Enable Postgres Trigram Extension run: | PGPASSWORD=postgres psql -U postgres -h 127.0.0.1 -p ${{ job.services.postgres.ports[5432] }} -d ci_db_test -c "CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";" - name: Test with unittest env: TEST_DATABASE_URL: postgresql://postgres:postgres@localhost/ci_db_test TEST_DATABASE_ASYNC_URL: postgresql+asyncpg://postgres:postgres@localhost/ci_db_test run: | python -m unittest discover -s ./tests/test_implementations ciPython39: runs-on: ubuntu-latest strategy: matrix: python-version: [ 3.9 ] services: postgres: image: postgres:11 env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: ci_db_test ports: - 5432:5432 options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v1 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Enable Postgres Trigram Extension run: | PGPASSWORD=postgres psql -U postgres -h 127.0.0.1 -p ${{ job.services.postgres.ports[5432] }} -d ci_db_test -c "CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";" - name: Test with unittest env: TEST_DATABASE_URL: postgresql://postgres:postgres@localhost/ci_db_test TEST_DATABASE_ASYNC_URL: postgresql+asyncpg://postgres:postgres@localhost/ci_db_test run: | python -m unittest discover -s ./tests/test_implementations ciPython310: runs-on: ubuntu-latest strategy: matrix: python-version: [ '3.10' ] services: postgres: image: postgres:11 env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: ci_db_test ports: - 5432:5432 options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v1 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Enable Postgres Trigram Extension run: | PGPASSWORD=postgres psql -U postgres -h 127.0.0.1 -p ${{ job.services.postgres.ports[5432] }} -d ci_db_test -c "CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";" - name: Test with unittest env: TEST_DATABASE_URL: postgresql://postgres:postgres@localhost/ci_db_test TEST_DATABASE_ASYNC_URL: postgresql+asyncpg://postgres:postgres@localhost/ci_db_test run: | python -m unittest discover -s ./tests/test_implementations build-n-publish: needs: [ciPython37, ciPython38, ciPython39,ciPython310] name: Build and publish Python 🐍 distributions 📦 to PyPI runs-on: ubuntu-latest steps: - uses: actions/checkout@master - name: Set up Python 3.7 uses: actions/setup-python@v3 with: python-version: "3.7" - name: Set release version env run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV - name: Release version run: | echo $RELEASE_VERSION echo ${{ env.RELEASE_VERSION }} - name: Install pypa/build run: >- python -m pip install build --user - name: Build a binary wheel and a source tarball run: >- python -m build --sdist --wheel --outdir dist/ . - name: Publish distribution 📦 to PyPI if: startsWith(github.ref, 'refs/tags') uses: pypa/gh-action-pypi-publish@release/v1 with: user: __token__ password: ${{ secrets.PYPI_API_TOKEN }} ================================================ FILE: .gitignore ================================================ /htmlcov/ .coverage tests/htmlcov /poetry.lock /pyproject.toml *.xml *.pyc workspace.xml *.iml *.xml *.sh *.gz *.txt *. PKG-INFO fastapi_quickcrud_code_generator_beta.egg-info src/fastapi_quickcrud.egg-info dist ================================================ FILE: CHANGELOG.md ================================================ # Change Log All notable changes to this project will be documented in this file. ## [not release] - 2021-09-27 ### FIX pydantic update is not good for this project --- ## [not release] - 2021-09-27 ### Added Full SQL support ### Changed ### Fixed ### ToDo upsert for each sql --- ## [not release] - 2021-09-08 ### Added Field description in docs ### Changed ### Fixed ## [0.0.1a16] - 2021-09-08 ### Added relationship with get api ### Changed disable alias usage is more easy and quick build up ### Fixed ## [0.0.1a13] - 2021-08-23 ### Added ### Changed ### Fixed post redirect get can not rollback when find one api not found with async session --- ## [0.0.1a12] - 2021-08-23 ### Added support create more than one pydantic model with same ### Changed ### Fixed duplicated pydantic model name --- ## [Unreleased] - 2021-08-22 ### Added SQLAlchemy Table is supported, but not support alias yet Support create CRUD route without primary key for SQLAlchemy Table ```python UntitledTable256 = Table( 'test_table', metadata, Column('bool_value', Boolean, nullable=False, server_default=text("false")), Column('bytea_value', LargeBinary), Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float, nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL), Column('json_value', JSON), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric), Column('text_value', Text), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('uuid_value', UUID), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), UniqueConstraint( 'int4_value', 'float4_value'), ) ``` ### Changed - primary key can be optional if autoincrement is True - get many responses 204 if not found ### Fixed --- ## - 2021-08-20 ### Added ### Changed - primary key will be required if no default value or not nullable ### Fixed --- ## - 2021-08-19 ### Added - User don't need to declare crud_service ### Changed - query abstract - Sqlalchemy - route abstract ### Fixed When you ask for a specific resource, say a user or with query param, and the user doesn't exist ```https://0.0.0.0:8080/api/:userid``` then fastapi-qucikcrud should return 404. In this case, the client requested a resource that doesn't exist. ---- In the other case, you have an api that returns all users in the system using the following url: ```https://0.0.0.0:8080/api/user``` If there are no users in the system, then, in this case, you should return 204. --- ## - 2021-08-18 ### Added - FastAPIQuickCRUD support commit by user - for example if autocommit set False ```python def get_transaction_session(): try: db = sync_session() yield db finally: db.commit() db.close() ``` - for example if autocommit set True ```python def get_transaction_session(): try: db = sync_session() yield db finally: db.close() ``` ### Changed - Refactor - Separate the sql result parsing ### Fixed ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2021 Luis Lui 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. ================================================ FILE: README.md ================================================ # FastAPI Quick CRUD ![Imgur](https://i.imgur.com/LsLKQHd.png) [![Codacy Badge](https://app.codacy.com/project/badge/Grade/c2a6306f7f0a41948369d80368eb7abb?style=flat-square)](https://www.codacy.com/gh/LuisLuii/FastAPIQuickCRUD/dashboard?utm_source=github.com&utm_medium=referral&utm_content=LuisLuii/FastAPIQuickCRUD&utm_campaign=Badge_Grade) [![Coverage Status](https://coveralls.io/repos/github/LuisLuii/FastAPIQuickCRUD/badge.svg?branch=main)](https://coveralls.io/github/LuisLuii/FastAPIQuickCRUD?branch=main) [![unit test](https://github.com/LuisLuii/FastAPIQuickCRUD/actions/workflows/ci.yml/badge.svg)](https://github.com/LuisLuii/FastAPIQuickCRUD/actions/workflows/ci.yml) [![SupportedVersion](https://img.shields.io/pypi/pyversions/fastapi-quickcrud?style=flat-square)](https://pypi.org/project/fastapi-quickcrud) [![develop dtatus](https://img.shields.io/pypi/status/fastapi-quickcrud?style=flat-square)](https://pypi.org/project/fastapi-quickcrud) [![PyPI version](https://badge.fury.io/py/fastapi-quickcrud.svg)](https://badge.fury.io/py/fastapi-quickcrud) --- ## [If you need apply business logic or add on some code, you can use my another open source project which supports CRUD router code generator](https://github.com/LuisLuii/fastapi-crud-template-generator) - [Introduction](#introduction) - [Advantages](#advantages) - [Limitations](#limitations) - [Getting started](#getting-started) - [Installation](#installation) - [Usage](#usage) - [Design](#design) - [Path Parameter](#path-parameter) - [Query Parameter](#query-parameter) - [Request Body](#request-body) - [Foreign Tree](#foreign-tree) - [Upsert](#upsert) - [Add description into docs](#add-description-into-docs) - [Relationship](#relationship) - [FastAPI_quickcrud Response Status Code standard](#fastapi_quickcrud-response-status-code-standard) # Introduction I believe that many people who work with FastApi to build RESTful CRUD services end up wasting time writing repitive boilerplate code. `FastAPI Quick CRUD` can generate CRUD methods in FastApi from an SQLAlchemy schema: - Get one - Get one with foreign key - Get many - Get many with foreign key - Update one - Update many - Patch one - Patch many - Create/Upsert one - Create/Upsert many - Delete One - Delete Many - Post Redirect Get `FastAPI Quick CRUD`is developed based on SQLAlchemy `1.4.23` version and supports sync and async. ![docs page](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/page_preview.png?raw=true) ![docs_page_2](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/foreign_tree.png?raw=true) ## Advantages - [x] **Support SQLAlchemy 1.4** - Allows you build a fully asynchronous or synchronous python service - [x] **Full SQLAlchemy DBAPI Support** - Support different SQL for SQLAlchemy - [x] **Support Pagination** - `Get many` API support `order by` `offset` `limit` field in API - [x] **Rich FastAPI CRUD router generation** - Many operations of CRUD are implemented to complete the development and coverage of all aspects of basic CRUD. - [x] **CRUD route automatically generated** - Support Declarative class definitions and Imperative table - [x] **Flexible API request** - `UPDATE ONE/MANY` `FIND ONE/MANY` `PATCH ONE/MANY` `DELETE ONE/MANY` supports Path Parameters (primary key) and Query Parameters as a command to the resource to filter and limit the scope of the scope of data in request. - [x] **SQL Relationship** - `FIND ONE/MANY` supports Path get data with relationship ## Limitations - ❌ If there are multiple **unique constraints**, please use **composite unique constraints** instead - ❌ **Composite primary key** is not supported - ❌ Unsupported API requests with on resources `xxx/{primary key}` for tables without a primary key; - `UPDATE ONE` - `FIND ONE` - `PATCH ONE` - `DELETE ONE` # Getting started ## I try to update the version dependencies as soon as possible to ensure that the core dependencies of this project have the highest version possible. ```bash fastapi<=0.68.2 pydantic<=1.8.2 SQLAlchemy<=1.4.30 starlette==0.14.2 ``` ## Installation ```bash pip install fastapi-quickcrud ``` I suggest the following library if you try to connect to PostgreSQL ```bash pip install psycopg2 pip install asyncpg ``` ## Usage run and go to http://127.0.0.1:port/docs and see the auto-generated API ### Simple Code (or see the longer ([example](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/tutorial/sample.py)) ```python from fastapi import FastAPI from sqlalchemy import Column, Integer, \ String, Table, ForeignKey, orm from fastapi_quickcrud import crud_router_builder Base = orm.declarative_base() class User(Base): __tablename__ = 'test_users' id = Column(Integer, primary_key=True, autoincrement=True, unique=True) name = Column(String, nullable=False) email = Column(String, nullable=False) friend = Table( 'test_friend', Base.metadata, Column('id', ForeignKey('test_users.id', ondelete='CASCADE', onupdate='CASCADE'), nullable=False), Column('friend_name', String, nullable=False) ) crud_route_1 = crud_router_builder(db_model=User, prefix="/user", tags=["User"], async_mode=True ) crud_route_2 = crud_router_builder(db_model=friend, prefix="/friend", tags=["friend"], async_mode=True ) app = FastAPI() app.include_router(crud_route_1) app.include_router(crud_route_2) ``` ### Foreign Tree With Relationship ```python from fastapi import FastAPI from fastapi_quickcrud import crud_router_builder from sqlalchemy import * from sqlalchemy.orm import * from fastapi_quickcrud.crud_router import generic_sql_crud_router_builder Base = declarative_base() class Account(Base): __tablename__ = "account" id = Column(Integer, primary_key=True, autoincrement=True) blog_post = relationship("BlogPost", back_populates="account") class BlogPost(Base): __tablename__ = "blog_post" id = Column(Integer, primary_key=True, autoincrement=True) account_id = Column(Integer, ForeignKey("account.id"), nullable=False) account = relationship("Account", back_populates="blog_post") blog_comment = relationship("BlogComment", back_populates="blog_post") class BlogComment(Base): __tablename__ = "blog_comment" id = Column(Integer, primary_key=True, autoincrement=True) blog_id = Column(Integer, ForeignKey("blog_post.id"), nullable=False) blog_post = relationship("BlogPost", back_populates="blog_comment") crud_route_parent = crud_router_builder( db_model=Account, prefix="/account", tags=["account"], foreign_include=[BlogComment, BlogPost] ) crud_route_child1 = generic_sql_crud_router_builder( db_model=BlogPost, prefix="/blog_post", tags=["blog_post"], foreign_include=[BlogComment] ) crud_route_child2 = generic_sql_crud_router_builder( db_model=BlogComment, prefix="/blog_comment", tags=["blog_comment"] ) app = FastAPI() [app.include_router(i) for i in [crud_route_parent, crud_route_child1, crud_route_child2]] ``` ### SQLAlchemy to Pydantic Model Converter And Build your own API([example](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/tutorial/basic_usage/quick_usage_with_async_SQLALchemy_Base.py)) ```python import uvicorn from fastapi import FastAPI, Depends from fastapi_quickcrud import CrudMethods from fastapi_quickcrud import sqlalchemy_to_pydantic from fastapi_quickcrud.misc.memory_sql import sync_memory_db from sqlalchemy import CHAR, Column, Integer from sqlalchemy.ext.declarative import declarative_base app = FastAPI() Base = declarative_base() metadata = Base.metadata class Child(Base): __tablename__ = 'right' id = Column(Integer, primary_key=True) name = Column(CHAR, nullable=True) friend_model_set = sqlalchemy_to_pydantic(db_model=Child, crud_methods=[ CrudMethods.FIND_MANY, CrudMethods.UPSERT_MANY, CrudMethods.UPDATE_MANY, CrudMethods.DELETE_MANY, CrudMethods.CREATE_ONE, CrudMethods.PATCH_MANY, ], exclude_columns=[]) post_model = friend_model_set.POST[CrudMethods.CREATE_ONE] sync_memory_db.create_memory_table(Child) @app.post("/hello", status_code=201, tags=["Child"], response_model=post_model.responseModel, dependencies=[]) async def my_api( query: post_model.requestBodyModel = Depends(post_model.requestBodyModel), session=Depends(sync_memory_db.get_memory_db_session) ): db_item = Child(**query.__dict__) session.add(db_item) session.commit() session.refresh(db_item) return db_item.__dict__ uvicorn.run(app, host="0.0.0.0", port=8000, debug=False) ``` * Note: you can use [sqlacodegen](https://github.com/agronholm/sqlacodegen) to generate SQLAlchemy models for your table. This project is based on the model development and testing generated by sqlacodegen ### Main module #### Generate CRUD router **crud_router_builder args** - db_session [Optional] `execute session generator` - default using in-memory db with create table automatically - example: - sync SQLALchemy: ```python from sqlalchemy.orm import sessionmaker def get_transaction_session(): try: db = sessionmaker(...) yield db except Exception as e: db.rollback() raise e finally: db.close() ``` - Async SQLALchemy ```python from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.asyncio import AsyncSession async_session = sessionmaker(autocommit=False, autoflush=False, bind=engine, class_=AsyncSession) async def get_transaction_session() -> AsyncSession: async with async_session() as session: async with session.begin(): yield session ``` - db_model [Require] `SQLALchemy Declarative Base Class or Table` > **Note**: There are some constraint in the SQLALchemy Schema - async_mode [Optional (auto set by db_session)] `bool`: if your db session is async > **Note**: require async session generator if True - autocommit [Optional (default True)] `bool`: if you don't need to commit by your self > **Note**: require handle the commit in your async session generator if False - dependencies [Optional]: API dependency injection of fastapi > **Note**: Get the example usage in `./example` - crud_methods: ```CrudMethods``` > - CrudMethods.FIND_ONE > - CrudMethods.FIND_MANY > - CrudMethods.UPDATE_ONE > - CrudMethods.UPDATE_MANY > - CrudMethods.PATCH_ONE > - CrudMethods.PATCH_MANY > - CrudMethods.UPSERT_ONE (only support postgresql yet) > - CrudMethods.UPSERT_MANY (only support postgresql yet) > - CrudMethods.CREATE_ONE > - CrudMethods.CREATE_MANY > - CrudMethods.DELETE_ONE > - CrudMethods.DELETE_MANY > - CrudMethods.POST_REDIRECT_GET - exclude_columns: `list` > set the columns that not to be operated but the columns should nullable or set the default value) - foreign_include: `list[declarative_base()]` > add the SqlAlchemy models here, and build the foreign tree get one/many api (don't support SqlAlchemy table) - dynamic argument (prefix, tags): extra argument for APIRouter() of fastapi # Design In `PUT` `DELETE` `PATCH`, user can use Path Parameters and Query Parameters to limit the scope of the data affected by the operation, and the Query Parameters is same with `FIND` API ## Path Parameter In the design of this tool, **Path Parameters** should be a primary key of table, that why limited primary key can only be one. ## Query Parameter - Query Operation will look like that when python type of column is
string - **support Approximate String Matching that require this** - (____str, ____str_____matching_pattern) - **support In-place Operation, get the value of column in the list of input** - (____list, ____list____comparison_operator) - **preview** ![string](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/string_query.png?raw=true)
numeric or datetime - **support Range Searching from and to** - (____from, ____from_____comparison_operator) - (____to, ____to_____comparison_operator) - **support In-place Operation, get the value of column in the list of input** - (____list, ____list____comparison_operator) - **preview** ![numeric](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/numeric_query.png?raw=true) ![datetime](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/time_query.png?raw=true)
uuid uuid supports In-place Operation only - **support In-place Operation, get the value of column in the list of input** - (____list, ____list____comparison_operator)
- EXTRA query parameter for `GET_MANY`:
Pagination - **limit** - **offset** - **order by** - **preview** ![Pagination](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/Pagination_query.png?raw=true)
### Query to SQL statement example - [**Approximate String Matching**](https://www.postgresql.org/docs/9.3/functions-matching.html)
example - request url ```text /test_CRUD? char_value____str_____matching_pattern=match_regex_with_case_sensitive& char_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive& char_value____str_____matching_pattern=case_sensitive& char_value____str_____matching_pattern=not_case_insensitive& char_value____str=a& char_value____str=b ``` - generated sql ```sql SELECT * FROM untitled_table_256 WHERE (untitled_table_256.char_value ~ 'a') OR (untitled_table_256.char_value ~ 'b' OR (untitled_table_256.char_value !~* 'a') OR (untitled_table_256.char_value !~* 'b' OR untitled_table_256.char_value LIKE 'a' OR untitled_table_256.char_value LIKE 'b' OR untitled_table_256.char_value NOT ILIKE 'a' OR untitled_table_256.char_value NOT ILIKE 'b' ```
- **In-place Operation**
example - In-place support the following operation - generated sql if user select Equal operation and input True and False - preview ![in](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/in_query.png?raw=true) - generated sql ```sql select * FROM untitled_table_256 WHERE untitled_table_256.bool_value = true OR untitled_table_256.bool_value = false ```
- **Range Searching**
example - Range Searching support the following operation ![greater](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/greater_query.png?raw=true) ![less](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/less_query.png?raw=true) - generated sql ```sql select * from untitled_table_256 WHERE untitled_table_256.date_value > %(date_value_1)s ``` ```sql select * from untitled_table_256 WHERE untitled_table_256.date_value < %(date_value_1)s ```
- Also support your custom dependency for each api(there is a example in `./example`) ### Request Body In the design of this tool, the columns of the table will be used as the fields of request body. In the basic request body in the api generated by this tool, some fields are optional if : * [x] it is primary key with `autoincrement` is True or the `server_default` or `default` is True * [x] it is not a primary key, but the `server_default` or `default` is True * [x] The field is nullable ### Foreign Tree TBC ## Upsert ** Upsert supports PosgreSQL only yet POST API will perform the data insertion action with using the basic [Request Body](#request-body), In addition, it also supports upsert(insert on conflict do) The operation will use upsert instead if the unique column in the inserted row that is being inserted already exists in the table The tool uses `unique columns` in the table as a parameter of on conflict , and you can define which column will be updated ![upsert](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/upsert_preview.png?raw=true) ## Add description into docs You can declare `comment` argument for `sqlalchemy.Column` to configure the description of column example: ```python class Parent(Base): __tablename__ = 'parent_o2o' id = Column(Integer, primary_key=True,comment='parent_test') # one-to-many collection children = relationship("Child", back_populates="parent") class Child(Base): __tablename__ = 'child_o2o' id = Column(Integer, primary_key=True,comment='child_pk_test') parent_id = Column(Integer, ForeignKey('parent_o2o.id'),info=({'description':'child_parent_id_test'})) # many-to-one scalar parent = relationship("Parent", back_populates="children") ``` ## Relationship Now, `FIND_ONE` and `FIND_MANY` are supporting select data with join operation ```python class Parent(Base): __tablename__ = 'parent_o2o' id = Column(Integer, primary_key=True) children = relationship("Child", back_populates="parent") class Child(Base): __tablename__ = 'child_o2o' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('parent_o2o.id')) parent = relationship("Parent", back_populates="children") ``` there is a relationship with using back_populates between Parent table and Child table, the `parent_id` in `Child` will refer to `id` column in `Parent`. `FastApi Quick CRUD` will generate an api with a `join_foreign_table` field, and get api will respond to your selection of the reference data row of the corresponding table in `join_foreign_table` field, ![join_1](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/join_preview_1.png?raw=true) ![join_2](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/join_preview_2.png?raw=true) * Try Request now there are some data in these two table ![parent](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/join_parent.png?raw=true) ![child](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/join_child.png?raw=true) when i request * Case One ```commandline curl -X 'GET' \ 'http://0.0.0.0:8000/parent?join_foreign_table=child_o2o' \ -H 'accept: application/json' ``` Response data ```json [ { "id_foreign": [ { "id": 1, "parent_id": 1 }, { "id": 2, "parent_id": 1 } ], "id": 1 }, { "id_foreign": [ { "id": 3, "parent_id": 2 }, { "id": 4, "parent_id": 2 } ], "id": 2 } ] ``` Response headers ```text x-total-count: 4 ``` There are response 4 data, response data will be grouped by the parent row, if the child refer to the same parent row * Case Two ```commandline curl -X 'GET' \ 'http://0.0.0.0:8000/child?join_foreign_table=parent_o2o' \ -H 'accept: application/json' ``` Response data ```json [ { "parent_id_foreign": [ { "id": 1 } ], "id": 1, "parent_id": 1 }, { "parent_id_foreign": [ { "id": 1 } ], "id": 2, "parent_id": 1 }, { "parent_id_foreign": [ { "id": 2 } ], "id": 3, "parent_id": 2 }, { "parent_id_foreign": [ { "id": 2 } ], "id": 4, "parent_id": 2 } ] ``` Response Header ```text x-total-count: 4 ``` #### FastAPI_quickcrud Response Status Code standard When you ask for a specific resource, say a user or with query param, and the user doesn't exist ```GET: get one : https://0.0.0.0:8080/api/:userid?xx=xx``` ```UPDATE: update one : https://0.0.0.0:8080/api/:userid?xx=xx``` ```PATCH: patch one : https://0.0.0.0:8080/api/:userid?xx=xx``` ```DELETE: delete one : https://0.0.0.0:8080/api/:userid?xx=xx``` then fastapi-qucikcrud should return 404. In this case, the client requested a resource that doesn't exist. ---- In the other case, you have an api that operate data on batch in the system using the following url: ```GET: get many : https://0.0.0.0:8080/api/user?xx=xx``` ```UPDATE: update many : https://0.0.0.0:8080/api/user?xx=xx``` ```DELETE: delete many : https://0.0.0.0:8080/api/user?xx=xx``` ```PATCH: patch many : https://0.0.0.0:8080/api/user?xx=xx``` If there are no users in the system, then, in this case, you should return 204. ### TODO [milestones](https://github.com/LuisLuii/FastAPIQuickCRUD/milestones) ================================================ FILE: README_zh.md ================================================ # FastAPI Quick CRUD ![Imgur](https://i.imgur.com/LsLKQHd.png) [![Codacy Badge](https://app.codacy.com/project/badge/Grade/c2a6306f7f0a41948369d80368eb7abb?style=flat-square)](https://www.codacy.com/gh/LuisLuii/FastAPIQuickCRUD/dashboard?utm_source=github.com&utm_medium=referral&utm_content=LuisLuii/FastAPIQuickCRUD&utm_campaign=Badge_Grade) [![Coverage Status](https://coveralls.io/repos/github/LuisLuii/FastAPIQuickCRUD/badge.svg?branch=main)](https://coveralls.io/github/LuisLuii/FastAPIQuickCRUD?branch=main) [![CircleCI](https://circleci.com/gh/LuisLuii/FastAPIQuickCRUD/tree/main.svg?style=svg)](https://circleci.com/gh/LuisLuii/FastAPIQuickCRUD/tree/main) [![PyPidownload](https://img.shields.io/pypi/dm/fastapi-quickcrud?style=flat-square)](https://pypi.org/project/fastapi-quickcrud) [![SupportedVersion](https://img.shields.io/pypi/pyversions/fastapi-quickcrud?style=flat-square)](https://pypi.org/project/fastapi-quickcrud) [![develop dtatus](https://img.shields.io/pypi/status/fastapi-quickcrud?style=flat-square)](https://pypi.org/project/fastapi-quickcrud) [![PyPI version](https://badge.fury.io/py/fastapi-quickcrud.svg)](https://badge.fury.io/py/fastapi-quickcrud) --- - [Introduction](#introduction) - [Advantage](#advantage) - [Constraint](#constraint) - [Getting started](#getting-started) - [Installation](#installation) - [Usage](#usage) - [Design](#design) - [Path Parameter](#path-parameter) - [Query Parameter](#query-parameter) - [Request Body](#request-body) - [Upsert](#upsert) # Introduction 我相信很多人會使用FastAPI寫一些簡單CRUD服務,浪費時間去為每個table 寫高度相似的代碼 如果你使用SQLAlchemy , 你可以通過`FastAPI Quick CRUD` 去生成CRUD API - Get one - Get many - Update one - Update many - Patch one - Patch many - Create/Upsert one - Create/Upsert many - Delete One - Delete Many - Post Redirect Get `FastAPI Quick CRUD`是基於SQLAlchemy `1.4` 版本進行開發,同時支持同步及異步 ![docs page](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/page_preview.png?raw=true) ## 好處 - [x] **支持 SQLAlchemy 1.41版本** - 允許你建立異步或同步的api 服務 - [x] **支持分頁** - Get many API 支持 order by offset limit - [x] **支持全部SQL DBAPI ** - 支持所有SQLAlchemy 支持的SQL DB dialect - [x] **CRUD路由自動生成n** - 豐富的CRUD路由生成選擇 - 多種CRUD操作可供選擇 - [x] **CRUD路由自動生成** - 支持SQLAlchemy的 Declarative class definitions 和 Imperative table - [x] **彈性API 請求** - `UPDATE ONE/MANY` `FIND ONE/MANY` `PATCH ONE/MANY` `DELETE ONE/MANY` 支持利用主鍵作為Path parameter and 以及table的column作Query Parameters,先對數據進行過濾再處理 ## 限制 - ❌ 請使用**composite unique constraints** 代替多個**unique constraints** - ❌ table 只能有一個主鍵 - ❌ 以下API 不支持*Path Parameter* 如果沒有主鍵 - `UPDATE ONE` - `FIND ONE` - `PATCH ONE` - `DELETE ONE` # Getting started ## Installation ```bash pip install fastapi-quickcrud ``` #### Simple Code (到 `./example` 取得更多例子) ```python from fastapi import FastAPI from sqlalchemy import Column, Integer, \ String, Table, ForeignKey, orm from fastapi_quickcrud import crud_router_builder Base = orm.declarative_base() class User(Base): __tablename__ = 'test_users' id = Column(Integer, primary_key=True, autoincrement=True, unique=True) name = Column(String, nullable=False) email = Column(String, nullable=False) friend = Table( 'test_friend', Base.metadata, Column('id', ForeignKey('test_users.id', ondelete='CASCADE', onupdate='CASCADE'), nullable=False), Column('friend_name', String, nullable=False) ) crud_route_1 = crud_router_builder(db_model=User, prefix="/user", tags=["User"], async_mode=True ) crud_route_2 = crud_router_builder(db_model=friend, prefix="/friend", tags=["friend"], async_mode=True ) app = FastAPI() app.include_router(crud_route_1) app.include_router(crud_route_2) ``` ### Main module #### Generate CRUD router **crud_router_builder args** - db_session [Optional] `execute session generator` - 默認使用In-memory DB, 或如以下例子自定義你的數據庫連接 - example: - 同步 SQLALchemy: ```python from sqlalchemy.orm import sessionmaker def get_transaction_session(): try: db = sessionmaker(...) yield db except Exception as e: db.rollback() raise e finally: db.close() ``` - 異步 SQLALchemy ```python from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.asyncio import AsyncSession async_session = sessionmaker(autocommit=False, autoflush=False, bind=engine, class_=AsyncSession) async def get_transaction_session() -> AsyncSession: async with async_session() as session: async with session.begin(): yield session ``` - db_model [Require] `SQLALchemy Declarative Base Class or Table` > **Note**: db_model 會有一些限制,例如數據庫獨特的數據類型 - async_mode [Optional (會通過你的db_session自動判斷)] `bool`: 你的數據庫連接是不是異步 > **Note**: 如果你的數據庫連接是異步,請設置True - autocommit [Optional (default True)] `bool`: 自動幫你commit每一個 CRUD > **Note**: 如果你在你的db_session 自已handle 了commit, 請設置False - dependencies [Optional]: FastAPI 的依赖注入 > **Note**: `./example` 有相關使用例子 - crud_methods [Optional]: ```CrudMethods``` 目前支持的CRUD, 如不設置便會自動設置 > - CrudMethods.FIND_ONE > - CrudMethods.FIND_MANY > - CrudMethods.UPDATE_ONE > - CrudMethods.UPDATE_MANY > - CrudMethods.PATCH_ONE > - CrudMethods.PATCH_MANY > - CrudMethods.UPSERT_ONE (only support postgresql yet) > - CrudMethods.UPSERT_MANY (only support postgresql yet) > - CrudMethods.CREATE_ONE > - CrudMethods.CREATE_MANY > - CrudMethods.DELETE_ONE > - CrudMethods.DELETE_MANY > - CrudMethods.POST_REDIRECT_GET - exclude_columns: `list`1 > 怱略column,不會生成該怱略column的API請求列 - dynamic argument (prefix, tags): 用作FastApi APIRouter() 的參數 # Design In `PUT` `DELETE` `PATCH`, 用戶可以通過 Path Parameters and Query Parameters 去限制受影響的數據 ,當中的Query Parameter 跟 `FIND` API一樣 ## Path Parameter 在這個工具的設計中,**Path Parameters** 應該是表的一個主鍵,所以有限的主鍵只能是一個。 ## Query Parameter - 當列的 python 類型為時,查詢操作將如下所示
string - **support Approximate String Matching that require this** - (____str, ____str_____matching_pattern) - **support In-place Operation, get the value of column in the list of input** - (____list, ____list____comparison_operator) - **preview** ![string](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/string_query.png?raw=true)
numeric or datetime - **support Range Searching from and to** - (____from, ____from_____comparison_operator) - (____to, ____to_____comparison_operator) - **support In-place Operation, get the value of column in the list of input** - (____list, ____list____comparison_operator) - **preview** ![numeric](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/numeric_query.png?raw=true) ![datetime](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/time_query.png?raw=true)
uuid uuid supports In-place Operation only - **support In-place Operation, get the value of column in the list of input** - (____list, ____list____comparison_operator)
- `GET_MANY` 的額外查詢參數:
Pagination - **limit** - **offset** - **order by** - **preview** ![Pagination](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/Pagination_query.png?raw=true)
### Query to SQL statement example - [**Approximate String Matching**](https://www.postgresql.org/docs/9.3/functions-matching.html)
example - request url ```text /test_CRUD? char_value____str_____matching_pattern=match_regex_with_case_sensitive& char_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive& char_value____str_____matching_pattern=case_sensitive& char_value____str_____matching_pattern=not_case_insensitive& char_value____str=a& char_value____str=b ``` - generated sql ```sql SELECT * FROM untitled_table_256 WHERE (untitled_table_256.char_value ~ 'a') OR (untitled_table_256.char_value ~ 'b' OR (untitled_table_256.char_value !~* 'a') OR (untitled_table_256.char_value !~* 'b' OR untitled_table_256.char_value LIKE 'a' OR untitled_table_256.char_value LIKE 'b' OR untitled_table_256.char_value NOT ILIKE 'a' OR untitled_table_256.char_value NOT ILIKE 'b' ```
- **In-place Operation**
example - In-place support the following operation - generated sql if user select Equal operation and input True and False - preview ![in](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/in_query.png?raw=true) - generated sql ```sql select * FROM untitled_table_256 WHERE untitled_table_256.bool_value = true OR untitled_table_256.bool_value = false ```
- **Range Searching**
example - Range Searching support the following operation ![greater](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/greater_query.png?raw=true) ![less](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/less_query.png?raw=true) - generated sql ```sql select * from untitled_table_256 WHERE untitled_table_256.date_value > %(date_value_1)s ``` ```sql select * from untitled_table_256 WHERE untitled_table_256.date_value < %(date_value_1)s ```
- 還支持您對每個 api 的自定義依賴項(there is a example in `./example`) ### 請求正文 在這個工具的設計中,表格的列將被用作請求正文的字段。 在此工俱生成的 api 中的基本請求正文中,某些字段是可選的,如果: * [x] 它是主鍵,`autoincrement` 為 True 或 `server_default` 或 `default` 為 True * [x] 它不是主鍵,但 `server_default` 或 `default` 為 True * [x] 該字段可以為空 ## Upsert ** Upsert 目前僅支持 PosgreSQL POST API 將使用基本的 [Request Body](#request-body) 執行數據插入操作, 此外,它還支持upsert(在衝突時插入) 如果要插入的插入行中的唯一列已存在於表中,則該操作將使用 upsert 該工具使用表中的“唯一列”作為衝突時的參數,您可以定義將更新哪一列 ![upsert](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/upsert_preview.png?raw=true) ## Add description into docs 你可以為`sqlalchemy.Column`聲明`comment`參數來配置列的描述 例子: ```python class Parent(Base): __tablename__ = 'parent_o2o' id = Column(Integer, primary_key=True,comment='parent_test') # one-to-many collection children = relationship("Child", back_populates="parent") class Child(Base): __tablename__ = 'child_o2o' id = Column(Integer, primary_key=True,comment='child_pk_test') parent_id = Column(Integer, ForeignKey('parent_o2o.id'),info=({'description':'child_parent_id_test'})) # many-to-one scalar parent = relationship("Parent", back_populates="children") ``` ## Relationship 現在,`FIND_ONE` 和 `FIND_MANY` 支持 relationship ```python class Parent(Base): __tablename__ = 'parent_o2o' id = Column(Integer, primary_key=True) children = relationship("Child", back_populates="parent") class Child(Base): __tablename__ = 'child_o2o' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('parent_o2o.id')) parent = relationship("Parent", back_populates="children") ``` 父表和子表之間使用back_populates有關係,`Child`中的`parent_id`將引用`Parent`中的`id`列。 `FastApi Quick CRUD`會生成一個帶有`join_foreign_table`字段的api,get api會響應你在`join_foreign_table`字段中選擇對應表的引用數據行, ![join_1](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/join_preview_1.png?raw=true) ![join_2](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/join_preview_2.png?raw=true) * Try Request 現在這兩個表中有一些數據 ![parent](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/join_parent.png?raw=true) ![child](https://github.com/LuisLuii/FastAPIQuickCRUD/blob/main/pic/join_child.png?raw=true) 當我請求時 * Case One ```commandline curl -X 'GET' \ 'http://0.0.0.0:8000/parent?join_foreign_table=child_o2o' \ -H 'accept: application/json' ``` Response data ```json [ { "id_foreign": [ { "id": 1, "parent_id": 1 }, { "id": 2, "parent_id": 1 } ], "id": 1 }, { "id_foreign": [ { "id": 3, "parent_id": 2 }, { "id": 4, "parent_id": 2 } ], "id": 2 } ] ``` Response headers ```text x-total-count: 4 ``` 這有響應四個數據,響應數據將按父行分組,如果子引用相同的父行 * Case Two ```commandline curl -X 'GET' \ 'http://0.0.0.0:8000/child?join_foreign_table=parent_o2o' \ -H 'accept: application/json' ``` Response data ```json [ { "parent_id_foreign": [ { "id": 1 } ], "id": 1, "parent_id": 1 }, { "parent_id_foreign": [ { "id": 1 } ], "id": 2, "parent_id": 1 }, { "parent_id_foreign": [ { "id": 2 } ], "id": 3, "parent_id": 2 }, { "parent_id_foreign": [ { "id": 2 } ], "id": 4, "parent_id": 2 } ] ``` Response Header ```text x-total-count: 4 ``` #### FastAPI_quickcrud Response Status Code standard 當您請求特定資源時,例如一個用戶或帶有查詢參數,而該用戶不存在 ```GET: get one : https://0.0.0.0:8080/api/:userid?xx=xx``` ```UPDATE: update one : https://0.0.0.0:8080/api/:userid?xx=xx``` ```PATCH: patch one : https://0.0.0.0:8080/api/:userid?xx=xx``` ```DELETE: delete one : https://0.0.0.0:8080/api/:userid?xx=xx``` 那麼 fastapi-qucikcrud 應該返回 404。在這種情況下,客戶端請求了一個不存在的資源。 ---- 在另一種情況下,您有一個 api,它使用以下 url 在系統中批量操作數據: ```GET: get many : https://0.0.0.0:8080/api/user?xx=xx``` ```UPDATE: update many : https://0.0.0.0:8080/api/user?xx=xx``` ```DELETE: delete many : https://0.0.0.0:8080/api/user?xx=xx``` ```PATCH: patch many : https://0.0.0.0:8080/api/user?xx=xx``` 如果系統中沒有用戶,那麼在這種情況下,您應該返回 204。 ### TODO - 每個 SQL 的 Upsert 操作 ================================================ FILE: __init__.py ================================================ ================================================ FILE: __main__.py ================================================ ================================================ FILE: setup.py ================================================ import os from setuptools import setup, find_packages VERSION = os.getenv("RELEASE_VERSION", default=None) or os.getenv("env.RELEASE_VERSION", default=None) print( """ - upload - build wheel: python setup.py sdist - upload to server: twine upload dist/* - download - Just pip install """ ) if __name__ == "__main__": setup( name="fastapi_quickcrud", version=VERSION, install_requires=[ "fastapi==0.68.2", "pydantic==1.8.2", "SQLAlchemy==1.4.30", "StrEnum==0.4.7", "starlette==0.14.2", "aiosqlite==0.17.0", ], extras_require={ 'dev': [ "uvicorn==0.17.0", "greenlet==1.1.2", "anyio==3.5.0" ], }, python_requires=">=3.7", description="A comprehensive FastaAPI's CRUD router generator for SQLALchemy.", long_description=open("README.md", "r", encoding="utf-8").read(), long_description_content_type="text/markdown", author="Luis Lui", author_email="luis11235178@gmail.com", url="https://github.com/LuisLuii/FastAPIQuickCRUD", license="MIT License", keywords=[ "fastapi", "crud", "restful", "routing", "SQLAlchemy", "generator", "crudrouter", "postgresql", "builder", ], packages=find_packages("src"), package_dir={"": "src"}, setup_requires=["setuptools>=31.6.0"], classifiers=[ "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python", "Topic :: Internet", "Topic :: Software Development :: Libraries :: Application Frameworks", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Software Development :: Libraries", "Topic :: Software Development :: Code Generators", "Topic :: Software Development", "Typing :: Typed", "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Framework :: AsyncIO", "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Intended Audience :: System Administrators", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Topic :: Internet :: WWW/HTTP :: HTTP Servers", "Topic :: Internet :: WWW/HTTP", ], include_package_data=True, ) ================================================ FILE: src/__init__.py ================================================ ================================================ FILE: src/fastapi_quickcrud/__init__.py ================================================ from .misc.utils import sqlalchemy_to_pydantic from .crud_router import crud_router_builder from .misc.type import CrudMethods ================================================ FILE: src/fastapi_quickcrud/crud_router.py ================================================ import asyncio import inspect from functools import partial from typing import \ Any, \ List, \ TypeVar, Union, Callable, Optional from fastapi import \ Depends, APIRouter from pydantic import \ BaseModel from sqlalchemy.sql.schema import Table from . import sqlalchemy_to_pydantic from .misc.abstract_execute import SQLALchemyExecuteService from .misc.abstract_parser import SQLAlchemyGeneralSQLeResultParse from .misc.abstract_query import SQLAlchemyPGSQLQueryService, \ SQLAlchemySQLITEQueryService, SQLAlchemyNotSupportQueryService from .misc.abstract_route import SQLAlchemySQLLiteRouteSource, SQLAlchemyPGSQLRouteSource, \ SQLAlchemyNotSupportRouteSource from .misc.crud_model import CRUDModel from .misc.memory_sql import async_memory_db, sync_memory_db from .misc.type import CrudMethods, SqlType from .misc.utils import convert_table_to_model, Base CRUDModelType = TypeVar("CRUDModelType", bound=BaseModel) CompulsoryQueryModelType = TypeVar("CompulsoryQueryModelType", bound=BaseModel) OnConflictModelType = TypeVar("OnConflictModelType", bound=BaseModel) def crud_router_builder( *, db_model: Union[Table, 'DeclarativeBaseModel'], db_session: Callable = None, autocommit: bool = True, crud_methods: Optional[List[CrudMethods]] = None, exclude_columns: Optional[List[str]] = None, dependencies: Optional[List[callable]] = None, crud_models: Optional[CRUDModel] = None, async_mode: Optional[bool] = None, foreign_include: Optional[Base] = None, sql_type: Optional[SqlType] = None, **router_kwargs: Any) -> APIRouter: """ @param db_model: The Sqlalchemy Base model/Table you want to use it to build api. @param db_session: The callable variable and return a session generator that will be used to get database connection session for fastapi. @param autocommit: set False if you handle commit in your db_session. @param crud_methods: Fastapi Quick CRUD supports a few of crud methods, and they save into the Enum class, get it by : from fastapi_quickcrud import CrudMethods example: [CrudMethods.GET_MANY,CrudMethods.ONE] note: if there is no primary key in your SQLAlchemy model, it dose not support request with specific resource, such as GET_ONE, UPDATE_ONE, DELETE_ONE, PATCH_ONE AND POST_REDIRECT_GET this is because POST_REDIRECT_GET need to redirect to GET_ONE api @param exclude_columns: Fastapi Quick CRUD will get all the columns in you table to generate a CRUD router, it is allow you exclude some columns you dont want it expose to operated by API note: if the column in exclude list but is it not nullable or no default_value, it may throw error when you do insert @param dependencies: A variable that will be added to the path operation decorators. @param crud_models: You can use the sqlalchemy_to_pydantic() to build your own Pydantic model CRUD set @param async_mode: As your database connection @param foreign_include: BaseModel Used to build foreign tree api @param sql_type: You sql database type @param router_kwargs: other argument for FastApi's views @return: APIRouter for fastapi """ db_model, NO_PRIMARY_KEY = convert_table_to_model(db_model) constraints = db_model.__table__.constraints if db_session is None: if async_mode: db_connection = async_memory_db db_session: Callable = db_connection.async_get_memory_db_session else: db_connection = sync_memory_db db_session: Callable = db_connection.get_memory_db_session db_connection.create_memory_table(db_model) if async_mode is None: async_mode = inspect.isasyncgen(db_session()) if sql_type is None: async def async_runner(f): return [i.bind.name async for i in f()] try: if async_mode: sql_type, = asyncio.get_event_loop().run_until_complete(async_runner(db_session)) else: sql_type, = [i.bind.name for i in db_session()] except Exception: raise RuntimeError("Some unknown problem occurred error, maybe you are uvicorn.run with reload=True. " "Try declaring sql_type for crud_router_builder yourself using from fastapi_quickcrud.misc.type import SqlType") if not crud_methods and NO_PRIMARY_KEY == False: crud_methods = CrudMethods.get_declarative_model_full_crud_method() if not crud_methods and NO_PRIMARY_KEY == True: crud_methods = CrudMethods.get_table_full_crud_method() result_parser_builder = SQLAlchemyGeneralSQLeResultParse if sql_type == SqlType.sqlite: routes_source = SQLAlchemySQLLiteRouteSource query_service = SQLAlchemySQLITEQueryService elif sql_type == SqlType.postgresql: routes_source = SQLAlchemyPGSQLRouteSource query_service = SQLAlchemyPGSQLQueryService else: routes_source = SQLAlchemyNotSupportRouteSource query_service = SQLAlchemyNotSupportQueryService if not crud_models: crud_models_builder: CRUDModel = sqlalchemy_to_pydantic crud_models: CRUDModel = crud_models_builder(db_model=db_model, constraints=constraints, crud_methods=crud_methods, exclude_columns=exclude_columns, sql_type=sql_type, foreign_include=foreign_include, exclude_primary_key=NO_PRIMARY_KEY) foreign_table_mapping = {db_model.__tablename__: db_model} if foreign_include: for i in foreign_include: model , _= convert_table_to_model(i) foreign_table_mapping[model.__tablename__] = i crud_service = query_service(model=db_model, async_mode=async_mode, foreign_table_mapping=foreign_table_mapping) # else: # crud_service = SQLAlchemyPostgreQueryService(model=db_model, async_mode=async_mode) result_parser = result_parser_builder(async_model=async_mode, crud_models=crud_models, autocommit=autocommit) methods_dependencies = crud_models.get_available_request_method() primary_name = crud_models.PRIMARY_KEY_NAME if primary_name: path = '/{' + primary_name + '}' else: path = "" unique_list: List[str] = crud_models.UNIQUE_LIST execute_service = SQLALchemyExecuteService() def find_one_api(request_response_model: dict, dependencies): _request_query_model = request_response_model.get('requestQueryModel', None) _response_model = request_response_model.get('responseModel', None) _request_url_param_model = request_response_model.get('requestUrlParamModel', None) routes_source.find_one(path=path, request_url_param_model=_request_url_param_model, request_query_model=_request_query_model, response_model=_response_model, db_session=db_session, query_service=crud_service, parsing_service=result_parser, execute_service=execute_service, dependencies=dependencies, api=api, async_mode=async_mode) def find_many_api(request_response_model: dict, dependencies): _request_query_model = request_response_model.get('requestQueryModel', None) _response_model = request_response_model.get('responseModel', None) routes_source.find_many(path="", request_query_model=_request_query_model, response_model=_response_model, db_session=db_session, query_service=crud_service, parsing_service=result_parser, execute_service=execute_service, dependencies=dependencies, api=api, async_mode=async_mode) def upsert_one_api(request_response_model: dict, dependencies): _request_body_model = request_response_model.get('requestBodyModel', None) _response_model = request_response_model.get('responseModel', None) routes_source.upsert_one(path="", request_body_model=_request_body_model, response_model=_response_model, db_session=db_session, query_service=crud_service, parsing_service=result_parser, execute_service=execute_service, dependencies=dependencies, api=api, async_mode=async_mode, unique_list=unique_list) def upsert_many_api(request_response_model: dict, dependencies): _request_body_model = request_response_model.get('requestBodyModel', None) _response_model = request_response_model.get('responseModel', None) routes_source.upsert_many(path="", request_body_model=_request_body_model, response_model=_response_model, db_session=db_session, query_service=crud_service, parsing_service=result_parser, execute_service=execute_service, dependencies=dependencies, api=api, unique_list=unique_list, async_mode=async_mode) def create_one_api(request_response_model: dict, dependencies): _request_body_model = request_response_model.get('requestBodyModel', None) _response_model = request_response_model.get('responseModel', None) routes_source.create_one(path="", request_body_model=_request_body_model, response_model=_response_model, db_session=db_session, query_service=crud_service, parsing_service=result_parser, execute_service=execute_service, dependencies=dependencies, api=api, async_mode=async_mode, unique_list=unique_list) def create_many_api(request_response_model: dict, dependencies): _request_body_model = request_response_model.get('requestBodyModel', None) _response_model = request_response_model.get('responseModel', None) routes_source.create_many(path="", request_body_model=_request_body_model, response_model=_response_model, db_session=db_session, query_service=crud_service, parsing_service=result_parser, execute_service=execute_service, dependencies=dependencies, api=api, unique_list=unique_list, async_mode=async_mode) def delete_one_api(request_response_model: dict, dependencies): _request_query_model = request_response_model.get('requestQueryModel', None) _request_url_model = request_response_model.get('requestUrlParamModel', None) _response_model = request_response_model.get('responseModel', None) routes_source.delete_one(path=path, request_query_model=_request_query_model, request_url_model=_request_url_model, response_model=_response_model, db_session=db_session, query_service=crud_service, parsing_service=result_parser, execute_service=execute_service, dependencies=dependencies, api=api, async_mode=async_mode) def delete_many_api(request_response_model: dict, dependencies): _request_query_model = request_response_model.get('requestQueryModel', None) _response_model = request_response_model.get('responseModel', None) routes_source.delete_many(path="", request_query_model=_request_query_model, response_model=_response_model, db_session=db_session, query_service=crud_service, parsing_service=result_parser, execute_service=execute_service, dependencies=dependencies, api=api, async_mode=async_mode) def post_redirect_get_api(request_response_model: dict, dependencies): _request_body_model = request_response_model.get('requestBodyModel', None) _response_model = request_response_model.get('responseModel', None) routes_source.post_redirect_get(api=api, dependencies=dependencies, request_body_model=_request_body_model, db_session=db_session, crud_service=crud_service, result_parser=result_parser, execute_service=execute_service, async_mode=async_mode, response_model=_response_model) def patch_one_api(request_response_model: dict, dependencies): _request_query_model = request_response_model.get('requestQueryModel', None) _response_model = request_response_model.get('responseModel', None) _request_body_model = request_response_model.get('requestBodyModel', None) _request_url_param_model = request_response_model.get('requestUrlParamModel', None) routes_source.patch_one(api=api, path=path, request_url_param_model=_request_url_param_model, request_query_model=_request_query_model, dependencies=dependencies, request_body_model=_request_body_model, db_session=db_session, crud_service=crud_service, result_parser=result_parser, execute_service=execute_service, async_mode=async_mode, response_model=_response_model) def patch_many_api(request_response_model: dict, dependencies): _request_query_model = request_response_model.get('requestQueryModel', None) _response_model = request_response_model.get('responseModel', None) _request_body_model = request_response_model.get('requestBodyModel', None) routes_source.patch_many(api=api, path="", request_query_model=_request_query_model, dependencies=dependencies, request_body_model=_request_body_model, db_session=db_session, crud_service=crud_service, result_parser=result_parser, execute_service=execute_service, async_mode=async_mode, response_model=_response_model) def put_one_api(request_response_model: dict, dependencies): _request_query_model = request_response_model.get('requestQueryModel', None) _response_model = request_response_model.get('responseModel', None) _request_body_model = request_response_model.get('requestBodyModel', None) _request_url_param_model = request_response_model.get('requestUrlParamModel', None) routes_source.put_one(api=api, path=path, request_query_model=_request_query_model, dependencies=dependencies, request_body_model=_request_body_model, db_session=db_session, crud_service=crud_service, result_parser=result_parser, execute_service=execute_service, async_mode=async_mode, response_model=_response_model, request_url_param_model=_request_url_param_model) def put_many_api(request_response_model: dict, dependencies): _request_query_model = request_response_model.get('requestQueryModel', None) _response_model = request_response_model.get('responseModel', None) _request_body_model = request_response_model.get('requestBodyModel', None) routes_source.put_many(api=api, path='', request_query_model=_request_query_model, dependencies=dependencies, request_body_model=_request_body_model, db_session=db_session, crud_service=crud_service, result_parser=result_parser, execute_service=execute_service, async_mode=async_mode, response_model=_response_model) def find_one_foreign_tree_api(request_response_model: dict, dependencies): _foreign_list_model = request_response_model.get('foreignListModel', None) for i in _foreign_list_model: _request_query_model = i["request_query_model"] _response_model = i["response_model"] _path = i["path"] _function_name = i["function_name"] request_url_param_model = i["primary_key_dataclass_model"] routes_source.find_one_foreign_tree(path=_path, request_query_model=_request_query_model, response_model=_response_model, request_url_param_model=request_url_param_model, db_session=db_session, query_service=crud_service, parsing_service=result_parser, execute_service=execute_service, dependencies=dependencies, api=api, function_name=_function_name, async_mode=async_mode) def find_many_foreign_tree_api(request_response_model: dict, dependencies): _foreign_list_model = request_response_model.get('foreignListModel', None) for i in _foreign_list_model: _request_query_model = i["request_query_model"] _response_model = i["response_model"] _path = i["path"] _function_name = i["function_name"] request_url_param_model = i["primary_key_dataclass_model"] routes_source.find_many_foreign_tree(path=_path, request_query_model=_request_query_model, response_model=_response_model, request_url_param_model=request_url_param_model, db_session=db_session, query_service=crud_service, parsing_service=result_parser, execute_service=execute_service, dependencies=dependencies, api=api, async_mode=async_mode, function_name=_function_name) api_register = { CrudMethods.FIND_ONE.value: find_one_api, CrudMethods.FIND_MANY.value: find_many_api, CrudMethods.UPSERT_ONE.value: upsert_one_api, CrudMethods.UPSERT_MANY.value: upsert_many_api, CrudMethods.CREATE_MANY.value: create_many_api, CrudMethods.CREATE_ONE.value: create_one_api, CrudMethods.DELETE_ONE.value: delete_one_api, CrudMethods.DELETE_MANY.value: delete_many_api, CrudMethods.POST_REDIRECT_GET.value: post_redirect_get_api, CrudMethods.PATCH_ONE.value: patch_one_api, CrudMethods.PATCH_MANY.value: patch_many_api, CrudMethods.UPDATE_ONE.value: put_one_api, CrudMethods.UPDATE_MANY.value: put_many_api, CrudMethods.FIND_ONE_WITH_FOREIGN_TREE.value: find_one_foreign_tree_api, CrudMethods.FIND_MANY_WITH_FOREIGN_TREE.value: find_many_foreign_tree_api } api = APIRouter(**router_kwargs) if dependencies is None: dependencies = [] dependencies = [Depends(dep) for dep in dependencies] for request_method in methods_dependencies: value_of_dict_crud_model = crud_models.get_model_by_request_method(request_method) crud_model_of_this_request_methods = value_of_dict_crud_model.keys() for crud_model_of_this_request_method in crud_model_of_this_request_methods: request_response_model_of_this_request_method = value_of_dict_crud_model[crud_model_of_this_request_method] api_register[crud_model_of_this_request_method.value](request_response_model_of_this_request_method, dependencies) return api pgsql_crud_router_builder = partial(crud_router_builder) generic_sql_crud_router_builder = partial(crud_router_builder) ================================================ FILE: src/fastapi_quickcrud/misc/__init__.py ================================================ ================================================ FILE: src/fastapi_quickcrud/misc/abstract_execute.py ================================================ from typing import Any from sqlalchemy.sql.elements import BinaryExpression class SQLALchemyExecuteService(object): def __init__(self): pass # @staticmethod # async def async_execute_and_expire(session, stmt: BinaryExpression) -> Any: # async_execute_and_expire_result = await session.execute(stmt) # session.expire_all() # return async_execute_and_expire_result # # @staticmethod # def execute_and_expire(session, stmt: BinaryExpression) -> Any: # execute_and_expire_result = session.execute(stmt) # session.expire_all() # return execute_and_expire_result @staticmethod def add(session, model) -> Any: session.add(model) @staticmethod def add_all(session, model) -> Any: session.add_all(model) @staticmethod async def async_flush(session) -> Any: await session.flush() @staticmethod def flush(session) -> Any: session.flush() @staticmethod async def async_execute(session, stmt: BinaryExpression) -> Any: return await session.execute(stmt) @staticmethod def execute(session, stmt: BinaryExpression) -> Any: return session.execute(stmt) ================================================ FILE: src/fastapi_quickcrud/misc/abstract_parser.py ================================================ import copy from http import HTTPStatus from urllib.parse import urlencode from pydantic import parse_obj_as from starlette.responses import Response, RedirectResponse from .utils import group_find_many_join from .exceptions import FindOneApiNotRegister class SQLAlchemyGeneralSQLeResultParse(object): def __init__(self, async_model, crud_models, autocommit): """ :param async_model: bool :param crud_models: pre ready :param autocommit: bool """ self.async_mode = async_model self.crud_models = crud_models self.primary_name = crud_models.PRIMARY_KEY_NAME self.autocommit = autocommit async def async_commit(self, session): await session.flush() if self.autocommit: await session.commit() def commit(self, session): session.flush() if self.autocommit: session.commit() async def async_delete(self, session, data): await session.delete(data) def delete(self, session, data): session.delete(data) def update_data_model(self, data, update_args): for update_arg_name, update_arg_value in update_args.items(): setattr(data, update_arg_name, update_arg_value) return data @staticmethod async def async_rollback(session): await session.rollback() @staticmethod def rollback(session): session.rollback() @staticmethod def _response_builder(sql_execute_result, fastapi_response, response_model): result = parse_obj_as(response_model, sql_execute_result) fastapi_response.headers["x-total-count"] = str(len(sql_execute_result) if isinstance(sql_execute_result, list) else '1') return result # async def async_update_many(self, *, response_model, sql_execute_result, fastapi_response, **kwargs): # result = self._response_builder(sql_execute_result, fastapi_response, response_model) # await self.async_commit(kwargs.get('session')) # return result # # async def async_patch_many(self, *, response_model, sql_execute_result, fastapi_response, **kwargs): # result = self._response_builder(sql_execute_result, fastapi_response, response_model) # await self.async_commit(kwargs.get('session')) # return result # # def patch_many(self, *, response_model, sql_execute_result, fastapi_response, **kwargs): # result = self._response_builder(sql_execute_result, fastapi_response, response_model) # self.commit(kwargs.get('session')) # return result def update_func(self, response_model, sql_execute_result, fastapi_response, update_args, update_one): if not isinstance(sql_execute_result, list): sql_execute_result = [sql_execute_result] tmp = [] for i in sql_execute_result: tmp.append(self.update_data_model(i, update_args=update_args)) if not update_one: sql_execute_result = tmp else: sql_execute_result, = tmp return self._response_builder(response_model=response_model, sql_execute_result=sql_execute_result, fastapi_response=fastapi_response) def update(self, *, response_model, sql_execute_result, fastapi_response, update_args, **kwargs): session = kwargs.get('session') update_one = kwargs.get('update_one') result = self.update_func(response_model, sql_execute_result, fastapi_response, update_args, update_one) self.commit(session) return result async def async_update(self, *, response_model, sql_execute_result, fastapi_response, update_args, **kwargs): session = kwargs.get('session') update_one = kwargs.get('update_one') result = self.update_func(response_model, sql_execute_result, fastapi_response, update_args, update_one) await self.async_commit(session) return result @staticmethod def find_one_sub_func(sql_execute_result, response_model, fastapi_response, **kwargs): join = kwargs.get('join_mode', None) one_row_data = sql_execute_result.fetchall() if not one_row_data: return Response('specific data not found', status_code=HTTPStatus.NOT_FOUND) response = [] for i in one_row_data: i = dict(i) result__ = copy.deepcopy(i) tmp = {} for key_, value_ in result__.items(): if '_____' in key_: key, foreign_column = key_.split('_____') if key not in tmp: tmp[key] = {foreign_column: value_} else: tmp[key][foreign_column] = value_ else: tmp[key_] = value_ response.append(tmp) if join: response = group_find_many_join(response) if isinstance(response, list): response = response[0] fastapi_response.headers["x-total-count"] = str(1) return response async def async_find_one(self, *, response_model, sql_execute_result, fastapi_response, **kwargs): result = self.find_one_sub_func(sql_execute_result, response_model, fastapi_response, **kwargs) await self.async_commit(kwargs.get('session')) return result def find_one(self, *, response_model, sql_execute_result, fastapi_response, **kwargs): result = self.find_one_sub_func(sql_execute_result, response_model, fastapi_response, **kwargs) self.commit(kwargs.get('session')) return result @staticmethod def find_many_sub_func(response_model, sql_execute_result, fastapi_response, **kwargs): join = kwargs.get('join_mode', None) result = sql_execute_result.fetchall() if not result: return Response(status_code=HTTPStatus.NO_CONTENT) response = [] for i in result: i = dict(i) result__ = copy.deepcopy(i) tmp = {} for key_, value_ in result__.items(): if '_____' in key_: key, foreign_column = key_.split('_____') if key not in tmp: tmp[key] = {foreign_column: value_} else: tmp[key][foreign_column] = value_ else: tmp[key_] = value_ response.append(tmp) fastapi_response.headers["x-total-count"] = str(len(response)) if join: response = group_find_many_join(response) response = parse_obj_as(response_model, response) return response async def async_find_many(self, *, response_model, sql_execute_result, fastapi_response, **kwargs): result = self.find_many_sub_func(response_model, sql_execute_result, fastapi_response, **kwargs) await self.async_commit(kwargs.get('session')) return result def find_many(self, *, response_model, sql_execute_result, fastapi_response, **kwargs): result = self.find_many_sub_func(response_model, sql_execute_result, fastapi_response, **kwargs) self.commit(kwargs.get('session')) return result # @staticmethod # def update_one_sub_func(response_model, sql_execute_result, fastapi_response): # result = parse_obj_as(response_model, sql_execute_result) # fastapi_response.headers["x-total-count"] = str(1) # return result # # async def async_update_one(self, *, response_model, sql_execute_result, fastapi_response, update_args, **kwargs): # session = kwargs.get('session') # if not sql_execute_result: # return Response(status_code=HTTPStatus.NOT_FOUND) # data = self.update_data_model(sql_execute_result, update_args=update_args) # result = self.update_one_sub_func(response_model, data, fastapi_response) # await self.commit(session) # return result # # def update_one(self, *, response_model, sql_execute_result, fastapi_response, update_args, **kwargs): # session = kwargs.get('session') # if not sql_execute_result: # return Response(status_code=HTTPStatus.NOT_FOUND) # data = self.update_data_model(sql_execute_result, update_args=update_args) # result = self.update_one_sub_func(response_model, data, fastapi_response) # self.commit(session) # return result # async def async_patch_one(self, *, response_model, sql_execute_result, fastapi_response, **kwargs): # result = self.update_one_sub_func(response_model, sql_execute_result, fastapi_response) # await self.async_commit(kwargs.get('session')) # return result # # def patch_one(self, *, response_model, sql_execute_result, fastapi_response, **kwargs): # result = self.update_one_sub_func(response_model, sql_execute_result, fastapi_response) # self.commit(kwargs.get('session')) # return result @staticmethod def create_one_sub_func(response_model, sql_execute_result, fastapi_response): inserted_data, = sql_execute_result result = parse_obj_as(response_model, inserted_data) fastapi_response.headers["x-total-count"] = str(1) return result async def async_create_one(self, *, response_model, sql_execute_result, fastapi_response, **kwargs): result = self.create_one_sub_func(response_model, sql_execute_result, fastapi_response) await self.async_commit(kwargs.get('session')) return result def create_one(self, *, response_model, sql_execute_result, fastapi_response, **kwargs): result = self.create_one_sub_func(response_model, sql_execute_result, fastapi_response) self.commit(kwargs.get('session')) return result @staticmethod def create_many_sub_func(response_model, sql_execute_result, fastapi_response): result = parse_obj_as(response_model, sql_execute_result) fastapi_response.headers["x-total-count"] = str(len(sql_execute_result)) return result async def async_create_many(self, *, response_model, sql_execute_result, fastapi_response, **kwargs): result = self.create_many_sub_func(response_model, sql_execute_result, fastapi_response) await self.async_commit(kwargs.get('session')) return result def create_many(self, *, response_model, sql_execute_result, fastapi_response, **kwargs): result = self.create_many_sub_func(response_model, sql_execute_result, fastapi_response) self.commit(kwargs.get('session')) return result @staticmethod def upsert_one_sub_func(response_model, sql_execute_result, fastapi_response): sql_execute_result = sql_execute_result.fetchone() result = parse_obj_as(response_model, dict(sql_execute_result)) fastapi_response.headers["x-total-count"] = str(1) return result async def async_upsert_one(self, *, response_model, sql_execute_result, fastapi_response, **kwargs): result = self.upsert_one_sub_func(response_model, sql_execute_result, fastapi_response) await self.async_commit(kwargs.get('session')) return result def upsert_one(self, *, response_model, sql_execute_result, fastapi_response, **kwargs): result = self.upsert_one_sub_func(response_model, sql_execute_result, fastapi_response) self.commit(kwargs.get('session')) return result @staticmethod def upsert_many_sub_func(response_model, sql_execute_result, fastapi_response): insert_result_list = sql_execute_result.fetchall() result = parse_obj_as(response_model, insert_result_list) fastapi_response.headers["x-total-count"] = str(len(insert_result_list)) return result async def async_upsert_many(self, *, response_model, sql_execute_result, fastapi_response, **kwargs): result = self.upsert_many_sub_func(response_model, sql_execute_result, fastapi_response) await self.async_commit(kwargs.get('session')) return result def upsert_many(self, *, response_model, sql_execute_result, fastapi_response, **kwargs): result = self.upsert_many_sub_func(response_model, sql_execute_result, fastapi_response) self.commit(kwargs.get('session')) return result def delete_one_sub_func(self, response_model, sql_execute_result, fastapi_response, **kwargs): if not sql_execute_result: return Response(status_code=HTTPStatus.NOT_FOUND) result = parse_obj_as(response_model, sql_execute_result) fastapi_response.headers["x-total-count"] = str(1) return result def delete_one(self, *, response_model, sql_execute_result, fastapi_response, **kwargs): session = kwargs.get('session') if sql_execute_result: self.delete(session, sql_execute_result) result = self.delete_one_sub_func(response_model, sql_execute_result, fastapi_response, **kwargs) self.commit(session) return result async def async_delete_one(self, *, response_model, sql_execute_result, fastapi_response, **kwargs): session = kwargs.get('session') if sql_execute_result: self.delete(session, sql_execute_result) result = self.delete_one_sub_func(response_model, sql_execute_result, fastapi_response, **kwargs) await self.async_commit(session) return result def delete_many_sub_func(self, response_model, sql_execute_result, fastapi_response): if not sql_execute_result: return Response(status_code=HTTPStatus.NO_CONTENT) deleted_rows = sql_execute_result result = parse_obj_as(response_model, deleted_rows) fastapi_response.headers["x-total-count"] = str(len(deleted_rows)) return result def delete_many(self, *, response_model, sql_execute_results, fastapi_response, **kwargs): session = kwargs.get('session') if sql_execute_results: for sql_execute_result in sql_execute_results: self.delete(session, sql_execute_result) result = self.delete_many_sub_func(response_model, sql_execute_results, fastapi_response) self.commit(session) return result async def async_delete_many(self, *, response_model, sql_execute_results, fastapi_response, **kwargs): session = kwargs.get('session') if sql_execute_results: for sql_execute_result in sql_execute_results: await self.async_delete(session, sql_execute_result) result = self.delete_many_sub_func(response_model, sql_execute_results, fastapi_response) await self.async_commit(session) return result def has_end_point(self, fastapi_request) -> bool: redirect_end_point = fastapi_request.url.path + "/{" + self.primary_name + "}" redirect_url_exist = False for route in fastapi_request.app.routes: if route.path == redirect_end_point: route_request_method, = route.methods if route_request_method.upper() == 'GET': redirect_url_exist = True return redirect_url_exist def post_redirect_get_sub_func(self, response_model, sql_execute_result, fastapi_request): result = parse_obj_as(response_model, sql_execute_result) primary_key_field = result.__dict__.pop(self.primary_name, None) assert primary_key_field is not None redirect_url = fastapi_request.url.path + "/" + str(primary_key_field) return redirect_url def get_post_redirect_get_url(self, response_model, sql_execute_result, fastapi_request): redirect_url = self.post_redirect_get_sub_func(response_model, sql_execute_result, fastapi_request) header_dict = {i[0].decode("utf-8"): i[1].decode("utf-8") for i in fastapi_request.headers.__dict__['_list']} redirect_url += f'?{urlencode(header_dict)}' return redirect_url async def async_post_redirect_get(self, *, response_model, sql_execute_result, fastapi_request, **kwargs): session = kwargs['session'] if not self.has_end_point(fastapi_request): await self.async_rollback(session) raise FindOneApiNotRegister(404, f'End Point {fastapi_request.url.path}/{ {self.primary_name} }' f' with GET method not found') redirect_url = self.get_post_redirect_get_url(response_model, sql_execute_result, fastapi_request) await self.async_commit(session) return RedirectResponse(redirect_url, status_code=HTTPStatus.SEE_OTHER ) def post_redirect_get(self, *, response_model, sql_execute_result, fastapi_request, **kwargs): session = kwargs['session'] if not self.has_end_point(fastapi_request): self.rollback(session) raise FindOneApiNotRegister(404, f'End Point {fastapi_request.url.path}/{ {self.primary_name} }' f' with GET method not found') redirect_url = self.get_post_redirect_get_url(response_model, sql_execute_result, fastapi_request) self.commit(session) return RedirectResponse(redirect_url, status_code=HTTPStatus.SEE_OTHER ) ================================================ FILE: src/fastapi_quickcrud/misc/abstract_query.py ================================================ from abc import ABC from typing import List, Union from sqlalchemy import and_, select, text from sqlalchemy.dialects.postgresql import insert from sqlalchemy.sql.elements import BinaryExpression from sqlalchemy.sql.schema import Table from .exceptions import UnknownOrderType, UnknownColumn, UpdateColumnEmptyException from .type import Ordering from .utils import clean_input_fields, path_query_builder from .utils import find_query_builder class SQLAlchemyGeneralSQLQueryService(ABC): def __init__(self, *, model, async_mode, foreign_table_mapping): """ :param model: declarative_base model :param async_mode: bool """ self.model = model self.model_columns = model self.async_mode = async_mode self.foreign_table_mapping = foreign_table_mapping def get_many(self, *, join_mode, query, target_model=None, abstract_param=None ) -> BinaryExpression: filter_args = query limit = filter_args.pop('limit', None) offset = filter_args.pop('offset', None) order_by_columns = filter_args.pop('order_by_columns', None) model = self.model if target_model: model = self.foreign_table_mapping[target_model] filter_list: List[BinaryExpression] = find_query_builder(param=filter_args, model=model) path_filter_list: List[BinaryExpression] = path_query_builder(params=abstract_param, model=self.foreign_table_mapping) join_table_instance_list: list = self.get_join_select_fields(join_mode) if not isinstance(self.model, Table): model = model.__table__ stmt = select(*[model] + join_table_instance_list).filter(and_(*filter_list+path_filter_list)) if order_by_columns: order_by_query_list = [] for order_by_column in order_by_columns: if not order_by_column: continue sort_column, order_by = (order_by_column.replace(' ', '').split(':') + [None])[:2] if not hasattr(self.model_columns, sort_column): raise UnknownColumn(f'column {sort_column} is not exited') if not order_by: order_by_query_list.append(getattr(self.model_columns, sort_column).asc()) elif order_by.upper() == Ordering.DESC.upper(): order_by_query_list.append(getattr(self.model_columns, sort_column).desc()) elif order_by.upper() == Ordering.ASC.upper(): order_by_query_list.append(getattr(self.model_columns, sort_column).asc()) else: raise UnknownOrderType(f"Unknown order type {order_by}, only accept DESC or ASC") if order_by_query_list: stmt = stmt.order_by(*order_by_query_list) stmt = stmt.limit(limit).offset(offset) stmt = self.get_join_by_excpression(stmt, join_mode=join_mode) return stmt def get_one(self, *, extra_args: dict, filter_args: dict, join_mode=None ) -> BinaryExpression: filter_list: List[BinaryExpression] = find_query_builder(param=filter_args, model=self.model_columns) extra_query_expression: List[BinaryExpression] = find_query_builder(param=extra_args, model=self.model) join_table_instance_list: list = self.get_join_select_fields(join_mode) model = self.model if not isinstance(self.model, Table): model = model.__table__ stmt = select(*[model] + join_table_instance_list).where(and_(*filter_list + extra_query_expression)) # stmt = session.query(*[model] + join_table_instance_list).filter(and_(*filter_list + extra_query_expression)) stmt = self.get_join_by_excpression(stmt, join_mode=join_mode) return stmt def create(self, *, insert_arg, create_one=True, ) -> List[BinaryExpression]: insert_arg_dict: Union[list, dict] = insert_arg if not create_one: insert_arg_list: list = insert_arg_dict.pop('insert', None) insert_arg_dict = [] for i in insert_arg_list: insert_arg_dict.append(i.__dict__) if not isinstance(insert_arg_dict, list): insert_arg_dict = [insert_arg_dict] insert_arg_dict: list[dict] = [clean_input_fields(model=self.model_columns, param=insert_arg) for insert_arg in insert_arg_dict] if isinstance(insert_arg_dict, list): new_data = [] for i in insert_arg_dict: new_data.append(self.model(**i)) return new_data def upsert(self, *, insert_arg, unique_fields: List[str], upsert_one=True, ) -> BinaryExpression: raise NotImplementedError def insert_one(self, *, insert_args) -> BinaryExpression: insert_args = insert_args update_columns = clean_input_fields(insert_args, self.model_columns) inserted_instance = self.model(**update_columns) return inserted_instance def get_join_select_fields(self, join_mode=None): join_table_instance_list = [] if not join_mode: return join_table_instance_list for _, table_instance in join_mode.items(): for local_reference in table_instance['local_reference_pairs_set']: if 'exclude' in local_reference and local_reference['exclude']: continue for column in local_reference['reference_table_columns']: foreign_table_name = local_reference['reference']['reference_table'] join_table_instance_list.append( column.label(foreign_table_name + '_foreign_____' + str(column).split('.')[1])) return join_table_instance_list def get_join_by_excpression(self, stmt: BinaryExpression, join_mode=None) -> BinaryExpression: if not join_mode: return stmt for join_table, data in join_mode.items(): for local_reference in data['local_reference_pairs_set']: local = local_reference['local']['local_column'] reference = local_reference['reference']['reference_column'] local_column = getattr(local_reference['local_table_columns'], local) reference_column = getattr(local_reference['reference_table_columns'], reference) table = local_reference['reference_table'] stmt = stmt.join(table, local_column == reference_column) return stmt # def delete(self, # *, # delete_args: dict, # session, # primary_key: dict = None, # ) -> BinaryExpression: # filter_list: List[BinaryExpression] = find_query_builder(param=delete_args, # model=self.model_columns) # if primary_key: # filter_list += find_query_builder(param=primary_key, # model=self.model_columns) # # delete_instance = session.query(self.model).where(and_(*filter_list)) # return delete_instance def model_query(self, *, session, extra_args: dict = None, filter_args: dict = None, ) -> BinaryExpression: ''' used for delette and update ''' filter_list: List[BinaryExpression] = find_query_builder(param=filter_args, model=self.model_columns) if extra_args: filter_list += find_query_builder(param=extra_args, model=self.model_columns) stmt = select(self.model).where(and_(*filter_list)) return stmt def get_one_with_foreign_pk(self, *, join_mode, query, target_model, abstract_param=None ) -> BinaryExpression: model = self.foreign_table_mapping[target_model] filter_list: List[BinaryExpression] = find_query_builder(param=query, model=model) path_filter_list: List[BinaryExpression] = path_query_builder(params=abstract_param, model=self.foreign_table_mapping) join_table_instance_list: list = self.get_join_select_fields(join_mode) if not isinstance(self.model, Table): model = model.__table__ stmt = select(*[model] + join_table_instance_list).filter(and_(*filter_list + path_filter_list)) stmt = self.get_join_by_excpression(stmt, join_mode=join_mode) return stmt # def update(self, *, # update_args, # extra_query, # session, # primary_key=None, # ) -> BinaryExpression: # # # filter_list: List[BinaryExpression] = find_query_builder(param=extra_query, # model=self.model_columns) # if primary_key: # primary_key = primary_key # filter_list += find_query_builder(param=primary_key, model=self.model_columns) # update_stmt = update(self.model).where(and_(*filter_list)).values(update_args) # update_stmt = update_stmt.execution_options(synchronize_session=False) # return update_stmt class SQLAlchemyPGSQLQueryService(SQLAlchemyGeneralSQLQueryService): def __init__(self, *, model, async_mode, foreign_table_mapping): """ :param model: declarative_base model :param async_mode: bool """ super(SQLAlchemyPGSQLQueryService, self).__init__(model=model, async_mode=async_mode, foreign_table_mapping=foreign_table_mapping) self.model = model self.model_columns = model self.async_mode = async_mode def upsert(self, *, insert_arg, unique_fields: List[str], upsert_one=True, ) -> BinaryExpression: insert_arg_dict: Union[list, dict] = insert_arg insert_with_conflict_handle = insert_arg_dict.pop('on_conflict', None) if not upsert_one: insert_arg_list: list = insert_arg_dict.pop('insert', None) insert_arg_dict = [] for i in insert_arg_list: insert_arg_dict.append(i.__dict__) if not isinstance(insert_arg_dict, list): insert_arg_dict: list[dict] = [insert_arg_dict] insert_arg_dict: list[dict] = [clean_input_fields(model=self.model_columns, param=insert_arg) for insert_arg in insert_arg_dict] insert_stmt = insert(self.model).values(insert_arg_dict) if unique_fields and insert_with_conflict_handle: update_columns = clean_input_fields(insert_with_conflict_handle.__dict__.get('update_columns', None), self.model_columns) if not update_columns: raise UpdateColumnEmptyException('update_columns parameter must be a non-empty list ') conflict_update_dict = {} for columns in update_columns: conflict_update_dict[columns] = getattr(insert_stmt.excluded, columns) conflict_list = clean_input_fields(model=self.model_columns, param=unique_fields) conflict_update_dict = clean_input_fields(model=self.model_columns, param=conflict_update_dict) insert_stmt = insert_stmt.on_conflict_do_update(index_elements=conflict_list, set_=conflict_update_dict ) insert_stmt = insert_stmt.returning(text('*')) return insert_stmt class SQLAlchemySQLITEQueryService(SQLAlchemyGeneralSQLQueryService): def __init__(self, *, model, async_mode, foreign_table_mapping): """ :param model: declarative_base model :param async_mode: bool """ super().__init__(model=model, async_mode=async_mode, foreign_table_mapping=foreign_table_mapping) self.model = model self.model_columns = model self.async_mode = async_mode def upsert(self, *, insert_arg, unique_fields: List[str], upsert_one=True, ) -> BinaryExpression: raise NotImplementedError class SQLAlchemyMySQLQueryService(SQLAlchemyGeneralSQLQueryService): def __init__(self, *, model, async_mode, foreign_table_mapping): """ :param model: declarative_base model :param async_mode: bool """ super().__init__(model=model, async_mode=async_mode, foreign_table_mapping=foreign_table_mapping) self.model = model self.model_columns = model self.async_mode = async_mode def upsert(self, *, insert_arg, unique_fields: List[str], upsert_one=True, ) -> BinaryExpression: raise NotImplementedError class SQLAlchemyMariaDBQueryService(SQLAlchemyGeneralSQLQueryService): def __init__(self, *, model, async_mode, foreign_table_mapping): """ :param model: declarative_base model :param async_mode: bool """ super().__init__(model=model, async_mode=async_mode, foreign_table_mapping=foreign_table_mapping) self.model = model self.model_columns = model self.async_mode = async_mode def upsert(self, *, insert_arg, unique_fields: List[str], upsert_one=True, ) -> BinaryExpression: raise NotImplementedError class SQLAlchemyOracleQueryService(SQLAlchemyGeneralSQLQueryService): def __init__(self, *, model, async_mode, foreign_table_mapping): """ :param model: declarative_base model :param async_mode: bool """ super().__init__(model=model, async_mode=async_mode, foreign_table_mapping=foreign_table_mapping) self.model = model self.model_columns = model self.async_mode = async_mode def upsert(self, *, insert_arg, unique_fields: List[str], upsert_one=True, ) -> BinaryExpression: raise NotImplementedError class SQLAlchemyMSSqlQueryService(SQLAlchemyGeneralSQLQueryService): def __init__(self, *, model, async_mode, foreign_table_mapping): """ :param model: declarative_base model :param async_mode: bool """ super().__init__(model=model, async_mode=async_mode, foreign_table_mapping=foreign_table_mapping) self.model = model self.model_columns = model self.async_mode = async_mode def upsert(self, *, insert_arg, unique_fields: List[str], upsert_one=True, ) -> BinaryExpression: raise NotImplementedError class SQLAlchemyNotSupportQueryService(SQLAlchemyGeneralSQLQueryService): def __init__(self, *, model, async_mode, foreign_table_mapping): """ :param model: declarative_base model :param async_mode: bool """ super().__init__(model=model, async_mode=async_mode, foreign_table_mapping=foreign_table_mapping) self.model = model self.model_columns = model self.async_mode = async_mode def upsert(self, *, insert_arg, unique_fields: List[str], upsert_one=True, ) -> BinaryExpression: raise NotImplementedError ================================================ FILE: src/fastapi_quickcrud/misc/abstract_route.py ================================================ from abc import abstractmethod, ABC from http import HTTPStatus from typing import Union from fastapi import \ Depends, \ Response from sqlalchemy.exc import IntegrityError from starlette.requests import Request class SQLAlchemyGeneralSQLBaseRouteSource(ABC): """ This route will support the SQL SQLAlchemy dialects. """ @classmethod def find_one(cls, api, *, path, query_service, parsing_service, execute_service, async_mode, response_model, dependencies, request_url_param_model, request_query_model, db_session): if not async_mode: @api.get(path, status_code=200, response_model=response_model, dependencies=dependencies) def get_one_by_primary_key(response: Response, request: Request, url_param=Depends(request_url_param_model), query=Depends(request_query_model), session=Depends(db_session)): join = query.__dict__.pop('join_foreign_table', None) stmt = query_service.get_one(filter_args=query.__dict__, extra_args=url_param.__dict__, join_mode=join) query_result = execute_service.execute(session, stmt) response_result = parsing_service.find_one(response_model=response_model, sql_execute_result=query_result, fastapi_response=response, session=session, join_mode=join) return response_result else: @api.get(path, status_code=200, response_model=response_model, dependencies=dependencies) async def async_get_one_by_primary_key(response: Response, request: Request, url_param=Depends(request_url_param_model), query=Depends(request_query_model), session=Depends(db_session)): join = query.__dict__.pop('join_foreign_table', None) stmt = query_service.get_one(filter_args=query.__dict__, extra_args=url_param.__dict__, join_mode=join) query_result = await execute_service.async_execute(session, stmt) response_result = await parsing_service.async_find_one(response_model=response_model, sql_execute_result=query_result, fastapi_response=response, session=session, join_mode=join) return response_result @classmethod def find_many(cls, api, *, query_service, parsing_service, execute_service, async_mode, path, response_model, dependencies, request_query_model, db_session): if async_mode: @api.get(path, dependencies=dependencies, response_model=response_model) async def async_get_many(response: Response, request: Request, query=Depends(request_query_model), session=Depends( db_session) ): join = query.__dict__.pop('join_foreign_table', None) stmt = query_service.get_many(query=query.__dict__, join_mode=join) query_result = await execute_service.async_execute(session, stmt) parsed_response = await parsing_service.async_find_many(response_model=response_model, sql_execute_result=query_result, fastapi_response=response, join_mode=join, session=session) return parsed_response else: @api.get(path, dependencies=dependencies, response_model=response_model) def get_many(response: Response, request: Request, query=Depends(request_query_model), session=Depends( db_session) ): join = query.__dict__.pop('join_foreign_table', None) stmt = query_service.get_many(query=query.__dict__, join_mode=join) query_result = execute_service.execute(session, stmt) parsed_response = parsing_service.find_many(response_model=response_model, sql_execute_result=query_result, fastapi_response=response, join_mode=join, session=session) return parsed_response @abstractmethod def upsert_one(cls, api, *, path, query_service, parsing_service, execute_service, async_mode, response_model, request_body_model, dependencies, db_session, unique_list): raise NotImplementedError @abstractmethod def upsert_many(cls, api, *, query_service, parsing_service, async_mode, path, response_model, dependencies, request_body_model, db_session, unique_list, execute_service): raise NotImplementedError @classmethod def create_one(cls, api, *, path, query_service, parsing_service, execute_service, async_mode, response_model, request_body_model, dependencies, db_session, unique_list): if async_mode: @api.post(path, status_code=201, response_model=response_model, dependencies=dependencies) async def async_insert_one( response: Response, request: Request, query: request_body_model = Depends(request_body_model), session=Depends(db_session) ): # stmt = query_service.create(insert_arg=query) new_inserted_data = query_service.create(insert_arg=query.__dict__) execute_service.add_all(session, new_inserted_data) try: await execute_service.async_flush(session) except IntegrityError as e: err_msg, = e.orig.args if 'unique constraint' not in err_msg.lower(): raise e result = Response(status_code=HTTPStatus.CONFLICT) return result return await parsing_service.async_create_one(response_model=response_model, sql_execute_result=new_inserted_data, fastapi_response=response, session=session) else: @api.post(path, status_code=201, response_model=response_model, dependencies=dependencies) def insert_one( response: Response, request: Request, query: request_body_model = Depends(request_body_model), session=Depends(db_session) ): new_inserted_data = query_service.create(insert_arg=query.__dict__) execute_service.add_all(session, new_inserted_data) try: execute_service.flush(session) except IntegrityError as e: err_msg, = e.orig.args if 'unique constraint' not in err_msg.lower(): raise e result = Response(status_code=HTTPStatus.CONFLICT) return result return parsing_service.create_one(response_model=response_model, sql_execute_result=new_inserted_data, fastapi_response=response, session=session) @classmethod def create_many(cls, api, *, query_service, parsing_service, async_mode, path, response_model, dependencies, request_body_model, db_session, unique_list, execute_service): if async_mode: @api.post(path, status_code=201, response_model=response_model, dependencies=dependencies) async def async_insert_many( response: Response, request: Request, query: request_body_model = Depends(request_body_model), session=Depends(db_session) ): inserted_data = query_service.create(insert_arg=query.__dict__, create_one=False) execute_service.add_all(session, inserted_data) try: await execute_service.async_flush(session) except IntegrityError as e: err_msg, = e.orig.args if 'unique constraint' not in err_msg.lower(): raise e result = Response(status_code=HTTPStatus.CONFLICT) return result return await parsing_service.async_create_many(response_model=response_model, sql_execute_result=inserted_data, fastapi_response=response, session=session) else: @api.post(path, status_code=201, response_model=response_model, dependencies=dependencies) def insert_many( response: Response, request: Request, query: request_body_model = Depends(request_body_model), session=Depends(db_session) ): # inserted_data = query.__dict__['insert'] update_list = query.__dict__ inserted_data = query_service.create(insert_arg=update_list, create_one=False) execute_service.add_all(session, inserted_data) try: execute_service.flush(session) except IntegrityError as e: err_msg, = e.orig.args if 'unique constraint' not in err_msg.lower(): raise e result = Response(status_code=HTTPStatus.CONFLICT) return result return parsing_service.create_many(response_model=response_model, sql_execute_result=inserted_data, fastapi_response=response, session=session) @classmethod def delete_one(cls, api, *, query_service, parsing_service, execute_service, async_mode, path, response_model, dependencies, request_query_model, request_url_model, db_session, ): if async_mode: @api.delete(path, status_code=200, response_model=response_model, dependencies=dependencies) async def async_delete_one_by_primary_key(response: Response, request: Request, query=Depends(request_query_model), request_url_param_model=Depends(request_url_model), session=Depends(db_session)): # delete_instance = query_service.model_query( # filter_args=request_url_param_model.__dict__, # extra_args=query.__dict__, # session=session) filter_stmt = query_service.model_query(filter_args=request_url_param_model.__dict__, extra_args=query.__dict__, session=session) tmp = await session.execute(filter_stmt) delete_instance = tmp.scalar() return await parsing_service.async_delete_one(response_model=response_model, sql_execute_result=delete_instance, fastapi_response=response, session=session) else: @api.delete(path, status_code=200, response_model=response_model, dependencies=dependencies) def delete_one_by_primary_key(response: Response, request: Request, query=Depends(request_query_model), request_url_param_model=Depends(request_url_model), session=Depends(db_session)): filter_stmt = query_service.model_query(filter_args=request_url_param_model.__dict__, extra_args=query.__dict__, session=session) delete_instance = session.execute(filter_stmt).scalar() return parsing_service.delete_one(response_model=response_model, sql_execute_result=delete_instance, fastapi_response=response, session=session) @classmethod def delete_many(cls, api, *, query_service, parsing_service, execute_service, async_mode, path, response_model, dependencies, request_query_model, db_session): if async_mode: @api.delete(path, status_code=200, response_model=response_model, dependencies=dependencies) async def async_delete_many_by_query(response: Response, request: Request, query=Depends(request_query_model), session=Depends(db_session)): filter_stmt = query_service.model_query(filter_args=query.__dict__, session=session) tmp = await session.execute(filter_stmt) data_instance = [i for i in tmp.scalars()] return await parsing_service.async_delete_many(response_model=response_model, sql_execute_results=data_instance, fastapi_response=response, session=session) else: @api.delete(path, status_code=200, response_model=response_model, dependencies=dependencies) def delete_many_by_query(response: Response, request: Request, query=Depends(request_query_model), session=Depends(db_session)): filter_stmt = query_service.model_query(filter_args=query.__dict__, session=session) delete_instance = [i for i in session.execute(filter_stmt).scalars()] return parsing_service.delete_many(response_model=response_model, sql_execute_results=delete_instance, fastapi_response=response, session=session) @classmethod def post_redirect_get(cls, api, *, dependencies, request_body_model, db_session, crud_service, result_parser, execute_service, async_mode, response_model): if async_mode: @api.post("", status_code=303, response_class=Response, dependencies=dependencies) async def async_create_one_and_redirect_to_get_one_api_with_primary_key( request: Request, insert_args: request_body_model = Depends(), session=Depends(db_session), ): new_inserted_data = crud_service.insert_one(insert_args=insert_args.__dict__) execute_service.add(session, new_inserted_data) try: await execute_service.async_flush(session) except IntegrityError as e: err_msg, = e.orig.args if 'unique constraint' not in err_msg.lower(): raise e result = Response(status_code=HTTPStatus.CONFLICT) return result return await result_parser.async_post_redirect_get(response_model=response_model, sql_execute_result=new_inserted_data, fastapi_request=request, session=session) else: @api.post("", status_code=303, response_class=Response, dependencies=dependencies) def create_one_and_redirect_to_get_one_api_with_primary_key( request: Request, insert_args: request_body_model = Depends(), session=Depends(db_session), ): new_inserted_data = crud_service.insert_one(insert_args=insert_args.__dict__) execute_service.add(session, new_inserted_data) try: execute_service.flush(session) except IntegrityError as e: err_msg, = e.orig.args if 'unique constraint' not in err_msg.lower(): raise e result = Response(status_code=HTTPStatus.CONFLICT) return result return result_parser.post_redirect_get(response_model=response_model, sql_execute_result=new_inserted_data, fastapi_request=request, session=session) @classmethod def patch_one(cls, api, *, path, response_model, dependencies, request_url_param_model, request_body_model, request_query_model, execute_service, db_session, crud_service, result_parser, async_mode): if async_mode: @api.patch(path, status_code=200, response_model=Union[response_model], dependencies=dependencies) async def async_partial_update_one_by_primary_key( response: Response, primary_key: request_url_param_model = Depends(), patch_data: request_body_model = Depends(), extra_query: request_query_model = Depends(), session=Depends(db_session), ): filter_stmt = crud_service.model_query(filter_args=primary_key.__dict__, extra_args=extra_query.__dict__, session=session) data_instance = await session.execute(filter_stmt) data_instance = data_instance.scalar() try: return await result_parser.async_update(response_model=response_model, sql_execute_result=data_instance, update_args=patch_data.__dict__, fastapi_response=response, session=session, update_one=True) except IntegrityError as e: err_msg, = e.orig.args if 'unique constraint' not in err_msg.lower(): raise e result = Response(status_code=HTTPStatus.CONFLICT) return result else: @api.patch(path, status_code=200, response_model=Union[response_model], dependencies=dependencies) def partial_update_one_by_primary_key( response: Response, primary_key: request_url_param_model = Depends(), patch_data: request_body_model = Depends(), extra_query: request_query_model = Depends(), session=Depends(db_session), ): filter_stmt = crud_service.model_query(filter_args=primary_key.__dict__, extra_args=extra_query.__dict__, session=session) update_instance = session.execute(filter_stmt).scalar() try: return result_parser.update(response_model=response_model, sql_execute_result=update_instance, update_args=patch_data.__dict__, fastapi_response=response, session=session, update_one=True) except IntegrityError as e: err_msg, = e.orig.args if 'unique constraint' not in err_msg.lower(): raise e result = Response(status_code=HTTPStatus.CONFLICT) return result @classmethod def patch_many(cls, api, *, path, response_model, dependencies, request_body_model, request_query_model, db_session, crud_service, result_parser, execute_service, async_mode): if async_mode: @api.patch(path, status_code=200, response_model=response_model, dependencies=dependencies) async def async_partial_update_many_by_query( response: Response, patch_data: request_body_model = Depends(), extra_query: request_query_model = Depends(), session=Depends(db_session) ): filter_stmt = crud_service.model_query(filter_args=extra_query.__dict__, session=session) tmp = await session.execute(filter_stmt) data_instance = [i for i in tmp.scalars()] if not data_instance: return Response(status_code=HTTPStatus.NO_CONTENT) try: return await result_parser.async_update(response_model=response_model, sql_execute_result=data_instance, fastapi_response=response, update_args=patch_data.__dict__, session=session, update_one=False) except IntegrityError as e: err_msg, = e.orig.args if 'unique constraint' not in err_msg.lower(): raise e result = Response(status_code=HTTPStatus.CONFLICT) return result else: @api.patch(path, status_code=200, response_model=response_model, dependencies=dependencies) def partial_update_many_by_query( response: Response, patch_data: request_body_model = Depends(), extra_query: request_query_model = Depends(), session=Depends(db_session) ): filter_stmt = crud_service.model_query(filter_args=extra_query.__dict__, session=session) data_instance = [i for i in session.execute(filter_stmt).scalars()] if not data_instance: return Response(status_code=HTTPStatus.NO_CONTENT) try: return result_parser.update(response_model=response_model, sql_execute_result=data_instance, fastapi_response=response, update_args=patch_data.__dict__, session=session, update_one=False) except IntegrityError as e: err_msg, = e.orig.args if 'unique constraint' not in err_msg.lower(): raise e result = Response(status_code=HTTPStatus.CONFLICT) return result @classmethod def put_one(cls, api, *, path, request_url_param_model, request_body_model, response_model, dependencies, request_query_model, db_session, crud_service, result_parser, execute_service, async_mode): if async_mode: @api.put(path, status_code=200, response_model=response_model, dependencies=dependencies) async def async_entire_update_by_primary_key( response: Response, primary_key: request_url_param_model = Depends(), update_data: request_body_model = Depends(), extra_query: request_query_model = Depends(), session=Depends(db_session), ): filter_stmt = crud_service.model_query(filter_args=primary_key.__dict__, extra_args=extra_query.__dict__, session=session) data_instance = await session.execute(filter_stmt) data_instance = data_instance.scalar() if not data_instance: return Response(status_code=HTTPStatus.NOT_FOUND) try: return await result_parser.async_update(response_model=response_model, sql_execute_result=data_instance, fastapi_response=response, update_args=update_data.__dict__, session=session, update_one=True) except IntegrityError as e: err_msg, = e.orig.args if 'unique constraint' not in err_msg.lower(): raise e result = Response(status_code=HTTPStatus.CONFLICT) return result else: @api.put(path, status_code=200, response_model=response_model, dependencies=dependencies) def entire_update_by_primary_key( response: Response, primary_key: request_url_param_model = Depends(), update_data: request_body_model = Depends(), extra_query: request_query_model = Depends(), session=Depends(db_session), ): filter_stmt = crud_service.model_query(filter_args=primary_key.__dict__, extra_args=extra_query.__dict__, session=session) data_instance = session.execute(filter_stmt).scalar() if not data_instance: return Response(status_code=HTTPStatus.NOT_FOUND) try: return result_parser.update(response_model=response_model, sql_execute_result=data_instance, fastapi_response=response, update_args=update_data.__dict__, session=session, update_one=True) except IntegrityError as e: err_msg, = e.orig.args if 'unique constraint' not in err_msg.lower(): raise e result = Response(status_code=HTTPStatus.CONFLICT) return result @classmethod def put_many(cls, api, *, path, response_model, dependencies, request_query_model, request_body_model, db_session, crud_service, result_parser, execute_service, async_mode): if async_mode: @api.put(path, status_code=200, response_model=response_model, dependencies=dependencies) async def async_entire_update_many_by_query( response: Response, update_data: request_body_model = Depends(), extra_query: request_query_model = Depends(), session=Depends(db_session), ): filter_stmt = crud_service.model_query(filter_args=extra_query.__dict__, session=session) tmp = await session.execute(filter_stmt) data_instance = [i for i in tmp.scalars()] if not data_instance: return Response(status_code=HTTPStatus.NO_CONTENT) try: return await result_parser.async_update(response_model=response_model, sql_execute_result=data_instance, fastapi_response=response, update_args=update_data.__dict__, session=session, update_one=False) except IntegrityError as e: err_msg, = e.orig.args if 'unique constraint' not in err_msg.lower(): raise e result = Response(status_code=HTTPStatus.CONFLICT) return result else: @api.put(path, status_code=200, response_model=response_model, dependencies=dependencies) def entire_update_many_by_query( response: Response, update_data: request_body_model = Depends(), extra_query: request_query_model = Depends(), session=Depends(db_session), ): filter_stmt = crud_service.model_query(filter_args=extra_query.__dict__, session=session) data_instance = [i for i in session.execute(filter_stmt).scalars()] if not data_instance: return Response(status_code=HTTPStatus.NO_CONTENT) try: return result_parser.update(response_model=response_model, sql_execute_result=data_instance, fastapi_response=response, update_args=update_data.__dict__, session=session, update_one=False) except IntegrityError as e: err_msg, = e.orig.args if 'unique constraint' not in err_msg.lower(): raise e result = Response(status_code=HTTPStatus.CONFLICT) return result # return result_parser.update_many(response_model=response_model, # sql_execute_result=query_result, # fastapi_response=response, # session=session) @classmethod def find_one_foreign_tree(cls, api, *, query_service, parsing_service, execute_service, async_mode, path, response_model, dependencies, request_query_model, request_url_param_model, function_name, db_session): if async_mode: @api.get(path, dependencies=dependencies, response_model=response_model, name=function_name) async def async_get_one_with_foreign_tree(response: Response, request: Request, url_param=Depends(request_url_param_model), query=Depends(request_query_model), session=Depends( db_session) ): target_model = request.url.path.split("/")[-2] join = query.__dict__.pop('join_foreign_table', None) stmt = query_service.get_one_with_foreign_pk(query=query.__dict__, join_mode=join, abstract_param=url_param.__dict__, target_model=target_model) query_result = await execute_service.async_execute(session, stmt) parsed_response = await parsing_service.async_find_one(response_model=response_model, sql_execute_result=query_result, fastapi_response=response, join_mode=join, session=session) return parsed_response else: @api.get(path, dependencies=dependencies, response_model=response_model, name=function_name) def get_one_with_foreign_tree(response: Response, request: Request, url_param=Depends(request_url_param_model), query=Depends(request_query_model), session=Depends( db_session) ): target_model = request.url.path.split("/")[-2] join = query.__dict__.pop('join_foreign_table', None) stmt = query_service.get_one_with_foreign_pk(query=query.__dict__, join_mode=join, abstract_param=url_param.__dict__, target_model=target_model) query_result = execute_service.execute(session, stmt) parsed_response = parsing_service.find_one(response_model=response_model, sql_execute_result=query_result, fastapi_response=response, join_mode=join, session=session) return parsed_response @classmethod def find_many_foreign_tree(cls, api, *, query_service, parsing_service, execute_service, async_mode, path, response_model, dependencies, request_query_model, request_url_param_model, function_name, db_session): if async_mode: @api.get(path, dependencies=dependencies, response_model=response_model, name=function_name) async def async_get_many_with_foreign_tree(response: Response, request: Request, url_param=Depends(request_url_param_model), query=Depends(request_query_model), session=Depends( db_session) ): target_model = request.url.path.split("/")[-1] join = query.__dict__.pop('join_foreign_table', None) stmt = query_service.get_many(query=query.__dict__, join_mode=join, abstract_param=url_param.__dict__, target_model=target_model) query_result = await execute_service.async_execute(session, stmt) parsed_response = await parsing_service.async_find_many(response_model=response_model, sql_execute_result=query_result, fastapi_response=response, join_mode=join, session=session) return parsed_response else: @api.get(path, dependencies=dependencies, response_model=response_model, name=function_name) def get_many_with_foreign_tree(response: Response, request: Request, url_param=Depends(request_url_param_model), query=Depends(request_query_model), session=Depends( db_session) ): target_model = request.url.path.split("/")[-1] join = query.__dict__.pop('join_foreign_table', None) stmt = query_service.get_many(query=query.__dict__, join_mode=join, abstract_param=url_param.__dict__, target_model=target_model) query_result = execute_service.execute(session, stmt) parsed_response = parsing_service.find_many(response_model=response_model, sql_execute_result=query_result, fastapi_response=response, join_mode=join, session=session) return parsed_response class SQLAlchemyPGSQLRouteSource(SQLAlchemyGeneralSQLBaseRouteSource): ''' This route will support the SQL SQLAlchemy dialects ''' @classmethod def upsert_one(cls, api, *, path, query_service, parsing_service, execute_service, async_mode, response_model, request_body_model, dependencies, db_session, unique_list): if async_mode: @api.post(path, status_code=201, response_model=response_model, dependencies=dependencies) async def async_insert_one_and_support_upsert( response: Response, request: Request, query: request_body_model = Depends(request_body_model), session=Depends(db_session) ): stmt = query_service.upsert(insert_arg=query.__dict__, unique_fields=unique_list) try: query_result = await execute_service.async_execute(session, stmt) except IntegrityError as e: err_msg, = e.orig.args if 'unique constraint' not in err_msg.lower(): raise e result = Response(status_code=HTTPStatus.CONFLICT, content=err_msg) return result return await parsing_service.async_upsert_one(response_model=response_model, sql_execute_result=query_result, fastapi_response=response, session=session) else: @api.post(path, status_code=201, response_model=response_model, dependencies=dependencies) def insert_one_and_support_upsert( response: Response, request: Request, query: request_body_model = Depends(request_body_model), session=Depends(db_session) ): stmt = query_service.upsert(insert_arg=query.__dict__, unique_fields=unique_list) try: query_result = execute_service.execute(session, stmt) except IntegrityError as e: err_msg, = e.orig.args if 'unique constraint' not in err_msg.lower(): raise e result = Response(status_code=HTTPStatus.CONFLICT, content=err_msg) return result return parsing_service.upsert_one(response_model=response_model, sql_execute_result=query_result, fastapi_response=response, session=session) @classmethod def upsert_many(cls, api, *, query_service, parsing_service, async_mode, path, response_model, dependencies, request_body_model, db_session, unique_list, execute_service): if async_mode: @api.post(path, status_code=201, response_model=response_model, dependencies=dependencies) async def async_insert_many_and_support_upsert( response: Response, request: Request, query: request_body_model = Depends(request_body_model), session=Depends(db_session) ): stmt = query_service.upsert(insert_arg=query.__dict__, unique_fields=unique_list, upsert_one=False) try: query_result = await execute_service.async_execute(session, stmt) except IntegrityError as e: err_msg, = e.orig.args if 'unique constraint' not in err_msg.lower(): raise e result = Response(status_code=HTTPStatus.CONFLICT, content=err_msg) return result return await parsing_service.async_upsert_many(response_model=response_model, sql_execute_result=query_result, fastapi_response=response, session=session) else: @api.post(path, status_code=201, response_model=response_model, dependencies=dependencies) def insert_many_and_support_upsert( response: Response, request: Request, query: request_body_model = Depends(request_body_model), session=Depends(db_session) ): stmt = query_service.upsert(insert_arg=query.__dict__, unique_fields=unique_list, upsert_one=False) try: query_result = execute_service.execute(session, stmt) except IntegrityError as e: err_msg, = e.orig.args if 'unique constraint' not in err_msg.lower(): raise e result = Response(status_code=HTTPStatus.CONFLICT, content=err_msg) return result return parsing_service.upsert_many(response_model=response_model, sql_execute_result=query_result, fastapi_response=response, session=session) class SQLAlchemySQLLiteRouteSource(SQLAlchemyGeneralSQLBaseRouteSource): ''' This route will support the SQL SQLAlchemy dialects ''' @classmethod def upsert_one(cls, api, *, path, query_service, parsing_service, execute_service, async_mode, response_model, request_body_model, dependencies, db_session, unique_list): if async_mode: @api.post(path, status_code=201, response_model=response_model, dependencies=dependencies) async def async_insert_one_and_support_upsert( response: Response, request: Request, query: request_body_model = Depends(request_body_model), session=Depends(db_session) ): stmt = query_service.upsert(insert_arg=query.__dict__, unique_fields=unique_list) try: query_result = await execute_service.async_execute(session, stmt) except IntegrityError as e: err_msg, = e.orig.args if 'unique constraint' not in err_msg.lower(): raise e result = Response(status_code=HTTPStatus.CONFLICT) return result return await parsing_service.async_upsert_one(response_model=response_model, sql_execute_result=query_result, fastapi_response=response, session=session) else: @api.post(path, status_code=201, response_model=response_model, dependencies=dependencies) def insert_one_and_support_upsert( response: Response, request: Request, query: request_body_model = Depends(request_body_model), session=Depends(db_session) ): stmt = query_service.upsert(insert_arg=query.__dict__, unique_fields=unique_list) try: query_result = execute_service.execute(session, stmt) except IntegrityError as e: err_msg, = e.orig.args if 'unique constraint' not in err_msg.lower(): raise e result = Response(status_code=HTTPStatus.CONFLICT) return result return parsing_service.upsert_one(response_model=response_model, sql_execute_result=query_result, fastapi_response=response, session=session) @classmethod def upsert_many(cls, api, *, query_service, parsing_service, async_mode, path, response_model, dependencies, request_body_model, db_session, unique_list, execute_service): if async_mode: @api.post(path, status_code=201, response_model=response_model, dependencies=dependencies) async def async_insert_many_and_support_upsert( response: Response, request: Request, query: request_body_model = Depends(request_body_model), session=Depends(db_session) ): stmt = query_service.upsert(insert_arg=query.__dict__, unique_fields=unique_list, upsert_one=False) try: query_result = await execute_service.async_execute(session, stmt) except IntegrityError as e: err_msg, = e.orig.args if 'unique constraint' not in err_msg.lower(): raise e result = Response(status_code=HTTPStatus.CONFLICT) return result return await parsing_service.async_upsert_many(response_model=response_model, sql_execute_result=query_result, fastapi_response=response, session=session) else: @api.post(path, status_code=201, response_model=response_model, dependencies=dependencies) def insert_many_and_support_upsert( response: Response, request: Request, query: request_body_model = Depends(request_body_model), session=Depends(db_session) ): stmt = query_service.upsert(insert_arg=query.__dict__, unique_fields=unique_list, upsert_one=False) try: query_result = execute_service.execute(session, stmt) except IntegrityError as e: err_msg, = e.orig.args if 'unique constraint' not in err_msg.lower(): raise e result = Response(status_code=HTTPStatus.CONFLICT) return result return parsing_service.upsert_many(response_model=response_model, sql_execute_result=query_result, fastapi_response=response, session=session) class SQLAlchemyMySQLRouteSource(SQLAlchemyGeneralSQLBaseRouteSource): ''' This route will support the SQL SQLAlchemy dialects ''' @classmethod def upsert_one(cls, api, *, path, query_service, parsing_service, execute_service, async_mode, response_model, request_body_model, dependencies, db_session, unique_list): raise NotImplementedError @classmethod def upsert_many(cls, api, *, query_service, parsing_service, async_mode, path, response_model, dependencies, request_body_model, db_session, unique_list, execute_service): raise NotImplementedError class SQLAlchemyMariadbRouteSource(SQLAlchemyGeneralSQLBaseRouteSource): ''' This route will support the SQL SQLAlchemy dialects ''' @classmethod def upsert_one(cls, api, *, path, query_service, parsing_service, execute_service, async_mode, response_model, request_body_model, dependencies, db_session, unique_list): raise NotImplementedError @classmethod def upsert_many(cls, api, *, query_service, parsing_service, async_mode, path, response_model, dependencies, request_body_model, db_session, unique_list, execute_service): raise NotImplementedError class SQLAlchemyOracleRouteSource(SQLAlchemyGeneralSQLBaseRouteSource): ''' This route will support the SQL SQLAlchemy dialects ''' @classmethod def upsert_one(cls, api, *, path, query_service, parsing_service, execute_service, async_mode, response_model, request_body_model, dependencies, db_session, unique_list): raise NotImplementedError @classmethod def upsert_many(cls, api, *, query_service, parsing_service, async_mode, path, response_model, dependencies, request_body_model, db_session, unique_list, execute_service): raise NotImplementedError class SQLAlchemyMSSQLRouteSource(SQLAlchemyGeneralSQLBaseRouteSource): ''' This route will support the SQL SQLAlchemy dialects ''' @classmethod def upsert_one(cls, api, *, path, query_service, parsing_service, execute_service, async_mode, response_model, request_body_model, dependencies, db_session, unique_list): raise NotImplementedError @classmethod def upsert_many(cls, api, *, query_service, parsing_service, async_mode, path, response_model, dependencies, request_body_model, db_session, unique_list, execute_service): raise NotImplementedError class SQLAlchemyNotSupportRouteSource(SQLAlchemyGeneralSQLBaseRouteSource): ''' This route will support the SQL SQLAlchemy dialects ''' @classmethod def upsert_one(cls, api, *, path, query_service, parsing_service, execute_service, async_mode, response_model, request_body_model, dependencies, db_session, unique_list): raise NotImplementedError @classmethod def upsert_many(cls, api, *, query_service, parsing_service, async_mode, path, response_model, dependencies, request_body_model, db_session, unique_list, execute_service): raise NotImplementedError ================================================ FILE: src/fastapi_quickcrud/misc/covert_model.py ================================================ from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.sql.schema import Table def convert_table_to_model(db_model): NO_PRIMARY_KEY = False if not isinstance(db_model, Table): return db_model, NO_PRIMARY_KEY db_name = str(db_model.fullname) table_dict = {'__table__': db_model, '__tablename__': db_name} if not db_model.primary_key: table_dict['__mapper_args__'] = { "primary_key": [i for i in db_model._columns] } NO_PRIMARY_KEY = True for i in db_model.c: col, = i.expression.base_columns table_dict[str(i.key)] = col return type(f'{db_name}DeclarativeBaseClass', (declarative_base(),), table_dict), NO_PRIMARY_KEY ================================================ FILE: src/fastapi_quickcrud/misc/crud_model.py ================================================ from typing import (Optional, Dict, List) from pydantic import BaseModel from pydantic.main import ModelMetaclass from .exceptions import (RequestMissing, InvalidRequestMethod) from .type import CrudMethods class RequestResponseModel(BaseModel): requestUrlParamModel: Optional[ModelMetaclass] requestRelationshipUrlParamField: Optional[List[str]] requestQueryModel: Optional[ModelMetaclass] requestBodyModel: Optional[ModelMetaclass] responseModel: Optional[ModelMetaclass] jsonRequestFieldModel: Optional[ModelMetaclass] jsonbRequestFieldModel: Optional[ModelMetaclass] arrayRequestFieldModel: Optional[ModelMetaclass] foreignListModel: Optional[List[dict]] class CRUDModel(BaseModel): GET: Optional[Dict[CrudMethods, RequestResponseModel]] POST: Optional[Dict[CrudMethods, RequestResponseModel]] PUT: Optional[Dict[CrudMethods, RequestResponseModel]] PATCH: Optional[Dict[CrudMethods, RequestResponseModel]] DELETE: Optional[Dict[CrudMethods, RequestResponseModel]] FIND_MANY_WITH_FOREIGN_TREE: Optional[Dict[CrudMethods, RequestResponseModel]] PRIMARY_KEY_NAME: Optional[str] UNIQUE_LIST: Optional[List[str]] def get_available_request_method(self): return [i for i in self.dict(exclude_unset=True, ).keys() if i in ["GET", "POST", "PUT", "PATCH", "DELETE"]] def get_model_by_request_method(self, request_method): available_methods = self.dict() if request_method not in available_methods.keys(): raise InvalidRequestMethod(f'{request_method} is not an available request method') if not available_methods[request_method]: raise RequestMissing( f'{request_method} is not available, ' f'make sure the CRUDModel contains this request method') _ = available_methods[request_method] return _ ================================================ FILE: src/fastapi_quickcrud/misc/exceptions.py ================================================ from fastapi import HTTPException class FindOneApiNotRegister(HTTPException): pass class CRUDBuilderException(BaseException): pass class RequestMissing(CRUDBuilderException): pass class PrimaryMissing(CRUDBuilderException): pass class UnknownOrderType(CRUDBuilderException): pass class UpdateColumnEmptyException(CRUDBuilderException): pass class UnknownColumn(CRUDBuilderException): pass class QueryOperatorNotFound(CRUDBuilderException): pass class UnknownError(CRUDBuilderException): pass class ConflictColumnsCannotHit(CRUDBuilderException): pass class MultipleSingleUniqueNotSupportedException(CRUDBuilderException): pass class SchemaException(CRUDBuilderException): pass class CompositePrimaryKeyConstraintNotSupportedException(CRUDBuilderException): pass class MultiplePrimaryKeyNotSupportedException(CRUDBuilderException): pass class ColumnTypeNotSupportedException(CRUDBuilderException): pass class InvalidRequestMethod(CRUDBuilderException): pass # # class NotFoundError(MongoQueryError): # def __init__(self, Collection: Type[ModelType], model: BaseModel): # detail = "does not exist" # super().__init__(Collection, model, detail) # # # # class DuplicatedError(MongoQueryError): # def __init__(self, Collection: Type[ModelType], model: BaseModel): # detail = "was already existed" # super().__init__(Collection, model, detail) class FDDRestHTTPException(HTTPException): """Baseclass for all HTTP exceptions in FDD Rest API. This exception can be called as WSGI application to render a default error page or you can catch the subclasses of it independently and render nicer error messages. """ ================================================ FILE: src/fastapi_quickcrud/misc/memory_sql.py ================================================ import asyncio import string import random from typing import Generator from sqlalchemy import create_engine from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession from sqlalchemy.orm import declarative_base, sessionmaker from sqlalchemy.pool import StaticPool class MemorySql(): def __init__(self, async_mode: bool = False): """ @type async_mode: bool used to build sync or async memory sql connection """ self.async_mode = async_mode SQLALCHEMY_DATABASE_URL = f"sqlite{'+aiosqlite' if async_mode else ''}://" if not async_mode: self.engine = create_engine(SQLALCHEMY_DATABASE_URL, future=True, echo=True, pool_pre_ping=True, pool_recycle=7200, connect_args={"check_same_thread": False}, poolclass=StaticPool) self.sync_session = sessionmaker(bind=self.engine, autocommit=False, ) else: self.engine = create_async_engine(SQLALCHEMY_DATABASE_URL, future=True, echo=True, pool_pre_ping=True, pool_recycle=7200, connect_args={"check_same_thread": False}, poolclass=StaticPool) self.sync_session = sessionmaker(autocommit=False, autoflush=False, bind=self.engine, class_=AsyncSession) def create_memory_table(self, Mode: 'declarative_base()'): if not self.async_mode: Mode.__table__.create(self.engine, checkfirst=True) else: async def create_table(engine, model): async with engine.begin() as conn: await conn.run_sync(model._sa_registry.metadata.create_all) loop = asyncio.get_event_loop() loop.run_until_complete(create_table(self.engine, Mode)) def get_memory_db_session(self) -> Generator: try: db = self.sync_session() yield db except Exception as e: db.rollback() raise e finally: db.close() async def async_get_memory_db_session(self): async with self.sync_session() as session: yield session async_memory_db = MemorySql(True) sync_memory_db = MemorySql() ================================================ FILE: src/fastapi_quickcrud/misc/schema_builder.py ================================================ import uuid import warnings from copy import deepcopy from dataclasses import (make_dataclass, field) from enum import auto from typing import (Optional, Any) from typing import (Type, Dict, List, Tuple, TypeVar, NewType, Union) import pydantic from fastapi import (Body, Query) from pydantic import (BaseModel, create_model, BaseConfig) from pydantic.dataclasses import dataclass as pydantic_dataclass from sqlalchemy import UniqueConstraint, Table, Column from sqlalchemy import inspect from sqlalchemy.orm import DeclarativeMeta from sqlalchemy.orm import declarative_base from strenum import StrEnum from .covert_model import convert_table_to_model from .exceptions import (SchemaException, ColumnTypeNotSupportedException) from .type import (MatchingPatternInStringBase, RangeFromComparisonOperators, Ordering, RangeToComparisonOperators, ExtraFieldTypePrefix, ExtraFieldType, ItemComparisonOperators, PGSQLMatchingPatternInString, SqlType, ) FOREIGN_PATH_PARAM_KEYWORD = "__pk__" BaseModelT = TypeVar('BaseModelT', bound=BaseModel) DataClassT = TypeVar('DataClassT', bound=Any) DeclarativeClassT = NewType('DeclarativeClassT', declarative_base) TableNameT = NewType('TableNameT', str) ResponseModelT = NewType('ResponseModelT', BaseModel) ForeignKeyName = NewType('ForeignKeyName', str) TableInstance = NewType('TableInstance', Table) class ExcludeUnsetBaseModel(BaseModel): def dict(self, *args, **kwargs): if kwargs and kwargs.get("exclude_none") is not None: kwargs["exclude_unset"] = True return BaseModel.dict(self, *args, **kwargs) class OrmConfig(BaseConfig): orm_mode = True def _add_orm_model_config_into_pydantic_model(pydantic_model, **kwargs) -> BaseModelT: validators = kwargs.get('validators', None) config = kwargs.get('config', None) field_definitions = { name_: (field_.outer_type_, field_.field_info.default) for name_, field_ in pydantic_model.__fields__.items() } return create_model(f'{pydantic_model.__name__}WithValidators', **field_definitions, __config__=config, __validators__=validators) # def _add_validators(model: Type[BaseModelT], validators, **kwargs) -> Type[BaseModelT]: # """ # Create a new BaseModel with the exact same fields as `model` # but making them all optional and no default # """ # # config = kwargs.get('config', None) # # field_definitions = { # name_: (field_.outer_type_, field_.field_info.default) # for name_, field_ in model.__fields__.items() # } # return create_model(f'{model.__name__}WithValidators', # **field_definitions, # __config__=config, # __validators__={**validators}) def _model_from_dataclass(kls: DataClassT) -> Type[BaseModel]: """ Converts a stdlib dataclass to a pydantic BaseModel. """ return pydantic_dataclass(kls).__pydantic_model__ def _to_require_but_default(model: Type[BaseModelT]) -> Type[BaseModelT]: """ Create a new BaseModel with the exact same fields as `model` but making them all require but there are default value """ config = model.Config field_definitions = {} for name_, field_ in model.__fields__.items(): field_definitions[name_] = (field_.outer_type_, field_.field_info.default) return create_model(f'{model.__name__}RequireButDefault', **field_definitions, __config__=config) # type: ignore[arg-type] def _filter_none(request_or_response_object): received_request = deepcopy(request_or_response_object.__dict__) if 'insert' in received_request: insert_item_without_null = [] for received_insert in received_request['insert']: received_insert_ = deepcopy(received_insert) for received_insert_item, received_insert_value in received_insert_.__dict__.items(): if hasattr(received_insert_value, '__module__'): if received_insert_value.__module__ == 'fastapi.params' or received_insert_value is None: delattr(received_insert, received_insert_item) elif received_insert_value is None: delattr(received_insert, received_insert_item) insert_item_without_null.append(received_insert) setattr(request_or_response_object, 'insert', insert_item_without_null) else: for name, value in received_request.items(): if hasattr(value, '__module__'): if value.__module__ == 'fastapi.params' or value is None: delattr(request_or_response_object, name) elif value is None: delattr(request_or_response_object, name) class ApiParameterSchemaBuilder: unsupported_data_types = ["BLOB"] partial_supported_data_types = ["INTERVAL", "JSON", "JSONB"] def __init__(self, db_model: Type, sql_type, exclude_column=None, constraints=None, exclude_primary_key=False, foreign_include=False): self.constraints = constraints self.exclude_primary_key = exclude_primary_key if exclude_column is None: self._exclude_column = [] else: self._exclude_column = exclude_column self.alias_mapper: Dict[str, str] = {} # Table not support alias if self.exclude_primary_key: self.__db_model: Table = db_model self.__db_model_table: Table = db_model.__table__ self.__columns = db_model.__table__.c self.db_name: str = db_model.__tablename__ else: self.__db_model: DeclarativeClassT = db_model self.__db_model_table: Table = db_model.__table__ self.db_name: str = db_model.__tablename__ self.__columns = db_model.__table__.c model = self.__db_model self.primary_key_str, self._primary_key_dataclass_model, self._primary_key_field_definition \ = self._extract_primary() self.unique_fields: List[str] = self._extract_unique() self.uuid_type_columns = [] self.str_type_columns = [] self.number_type_columns = [] self.datetime_type_columns = [] self.timedelta_type_columns = [] self.bool_type_columns = [] self.json_type_columns = [] self.array_type_columns = [] self.foreign_table_response_model_sets: Dict[TableNameT, ResponseModelT] = {} self.all_field: List[dict] = self._extract_all_field() self.sql_type = sql_type if not foreign_include: foreign_include = [] self.foreign_include = foreign_include self.foreign_mapper = self.__foreign_mapper_builder() self.relation_level = self._extra_relation_level() self.table_of_foreign, self.reference_mapper = self.extra_foreign_table() def __foreign_mapper_builder(self): foreign_mapper = {} if self.exclude_primary_key: return foreign_mapper for db_model in self.foreign_include: db_model, NO_PRIMARY_KEY = convert_table_to_model(db_model) tmp = {} table_name = self.__get_table_name(db_model) tmp["model"] = db_model foreign_mapper[table_name] = db_model tmp["db_model"] = db_model tmp["db_model_table"] = db_model.__table__ tmp["db_name"] = db_model.__tablename__ tmp["columns"] = db_model.__table__.c tmp["all_fields"] = self._extract_all_field(tmp["columns"]) tmp["primary_key"] = self._extract_primary(tmp["db_model_table"]) foreign_mapper[table_name] = tmp return foreign_mapper def __get_table_name_from_table(self, table): return table.name def __get_table_name_from_model(self, table): return table.__tablename__ def __get_table_name(self, table): if isinstance(table, Table): return self.__get_table_name_from_table(table) else: return self.__get_table_name_from_model(table) def extra_foreign_table(self, db_model=None) -> Dict[ForeignKeyName, dict]: if db_model is None: db_model = self.__db_model if self.exclude_primary_key: return self._extra_foreign_table_from_table() else: return self._extra_foreign_table_from_declarative_base(db_model) def _extract_primary(self, db_model_table=None) -> Union[tuple, Tuple[Union[str, Any], DataClassT, Tuple[Union[str, Any], Union[Type[uuid.UUID], Any], Optional[Any]]]]: if db_model_table == None: db_model_table = self.__db_model_table primary_list = db_model_table.primary_key.columns.values() if not primary_list or self.exclude_primary_key: return (None, None, None) if len(primary_list) > 1: raise SchemaException( f'multiple primary key / or composite not supported; {self.db_name} ') primary_key_column, = primary_list column_type = str(primary_key_column.type) try: python_type = primary_key_column.type.python_type if column_type in self.unsupported_data_types: raise ColumnTypeNotSupportedException( f'The type of column {primary_key_column.key} ({column_type}) not supported yet') if column_type in self.partial_supported_data_types: warnings.warn( f'The type of column {primary_key_column.key} ({column_type}) ' f'is not support data query (as a query parameters )') except NotImplementedError: if column_type == "UUID": python_type = uuid.UUID else: raise ColumnTypeNotSupportedException( f'The type of column {primary_key_column.key} ({column_type}) not supported yet') # handle if python type is UUID if python_type.__name__ in ['str', 'int', 'float', 'Decimal', 'UUID', 'bool', 'date', 'time', 'datetime']: column_type = python_type else: raise ColumnTypeNotSupportedException( f'The type of column {primary_key_column.key} ({column_type}) not supported yet') default = self._extra_default_value(primary_key_column) description = self._get_field_description(primary_key_column) if default is ...: warnings.warn( f'The column of {primary_key_column.key} has not default value ' f'and it is not nullable and in exclude_list' f'it may throw error when you insert data ') primary_column_name = str(primary_key_column.key) primary_field_definitions = (primary_column_name, column_type, default) primary_columns_model: DataClassT = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_PrimaryKeyModel', [(primary_field_definitions[0], primary_field_definitions[1], Query(primary_field_definitions[2], description=description))], namespace={ '__post_init__': lambda self_object: self._value_of_list_to_str( self_object, self.uuid_type_columns) }) assert primary_column_name and primary_columns_model and primary_field_definitions return primary_column_name, primary_columns_model, primary_field_definitions def _extract_unique(self) -> List[str]: # get the unique columns with alias name # service change alias to original # handle: # composite unique constraint # single unique # exception: # use composite unique constraint if more than one column using unique # can not use composite unique constraint and single unique at same time # unique_constraint = None if not self.constraints: return [] for constraint in self.constraints: if isinstance(constraint, UniqueConstraint): if unique_constraint: raise SchemaException( "Only support one unique constraint/ Use unique constraint and composite unique constraint " "at same time is not supported / Use composite unique constraint if there are more than one unique constraint") unique_constraint = constraint if unique_constraint: unique_column_name_list = [] for constraint_column in unique_constraint.columns: column_name = str(constraint_column.key) unique_column_name = column_name unique_column_name_list.append(unique_column_name) return unique_column_name_list else: return [] @staticmethod def _get_field_description(column: Column) -> str: if not hasattr(column, 'comment'): return "" return column.comment def _extract_all_field(self, columns=None) -> List[dict]: fields: List[dict] = [] if not columns: columns = self.__columns elif isinstance(columns, DeclarativeMeta): columns = columns.__table__.c elif isinstance(columns, Table): columns = columns.c for column in columns: column_name = str(column.key) column_foreign = [i.target_fullname for i in column.foreign_keys] default = self._extra_default_value(column) if column_name in self._exclude_column: continue column_type = str(column.type) description = self._get_field_description(column) try: python_type = column.type.python_type if column_type in self.unsupported_data_types: raise ColumnTypeNotSupportedException( f'The type of column {column_name} ({column_type}) not supported yet') if column_type in self.partial_supported_data_types: warnings.warn( f'The type of column {column_name} ({column_type}) ' f'is not support data query (as a query parameters )') except NotImplementedError: if column_type == "UUID": python_type = uuid.UUID else: raise ColumnTypeNotSupportedException( f'The type of column {column_name} ({column_type}) not supported yet') # string filter if python_type.__name__ in ['str']: self.str_type_columns.append(column_name) # uuid filter elif python_type.__name__ in ['UUID']: self.uuid_type_columns.append(column_name) # number filter elif python_type.__name__ in ['int', 'float', 'Decimal']: self.number_type_columns.append(column_name) # date filter elif python_type.__name__ in ['date', 'time', 'datetime']: self.datetime_type_columns.append(column_name) # timedelta filter elif python_type.__name__ in ['timedelta']: self.timedelta_type_columns.append(column_name) # bool filter elif python_type.__name__ in ['bool']: self.bool_type_columns.append(column_name) # json filter elif python_type.__name__ in ['dict']: self.json_type_columns.append(column_name) # array filter elif python_type.__name__ in ['list']: self.array_type_columns.append(column_name) base_column_detail, = column.base_columns if hasattr(base_column_detail.type, 'item_type'): item_type = base_column_detail.type.item_type.python_type fields.append({'column_name': column_name, 'column_type': List[item_type], 'column_default': default, 'column_description': description}) continue else: raise ColumnTypeNotSupportedException( f'The type of column {column_name} ({column_type}) not supported yet') if column_type == "JSONB": fields.append({'column_name': column_name, 'column_type': Union[python_type, list], 'column_default': default, 'column_description': description, 'column_foreign': column_foreign}) else: fields.append({'column_name': column_name, 'column_type': python_type, 'column_default': default, 'column_description': description, 'column_foreign': column_foreign}) return fields def _extra_foreign_table_from_table(self) -> Dict[str, Table]: foreign_key_table = {} reference_mapper = {} for column in self.__columns: if column.foreign_keys: foreign_column, = column.foreign_keys foreign_table = foreign_column.column.table all_fields_ = self._extract_all_field(foreign_table.c) foreign_table_name = str(foreign_table.__str__()) local = str(foreign_column.parent).split('.') reference = foreign_column.target_fullname.split('.') class BaseClass(object): def __init__(self): pass TableClass = type(f'{foreign_table_name}', (BaseClass,), {}) # table_class = mapper(TableClass, foreign_table) local_reference_pairs = [{'local': {"local_table": local[0], "local_column": local[1]}, "reference": {"reference_table": reference[0], "reference_column": reference[1]}, 'reference_table': foreign_table, 'reference_table_columns': foreign_table.c, 'local_table': foreign_column.parent.table, 'local_table_columns': foreign_column.parent.table.c}] reference_mapper[local[1]] = {"foreign_table": foreign_table_name, "foreign_table_name": foreign_table_name} # foreign_key_table[foreign_table_name] = foreign_table # all_column = {} column_label = {} for i in foreign_table.c: column_name = str(i).split('.')[1] setattr(TableClass, column_name, i) column_label[column_name] = i foreign_key_table[foreign_table_name] = {'local_reference_pairs_set': local_reference_pairs, 'fields': all_fields_, 'instance': foreign_table, 'db_column': TableClass, 'column_label': column_label} response_fields = [] for i in all_fields_: response_fields.append((i['column_name'], i['column_type'], None)) response_model_dataclass = make_dataclass( f'foreign_{foreign_table_name + str(uuid.uuid4())}_FindManyResponseItemModel', response_fields, ) response_item_model = _model_from_dataclass(response_model_dataclass) response_item_model = _add_orm_model_config_into_pydantic_model(response_item_model, config=OrmConfig) # response_item_model = _add_validators(response_item_model, # config=OrmConfig) response_model = create_model( f'foreign_{foreign_table_name + str(uuid.uuid4())}_UpsertManyResponseListModel', **{'__root__': (List[response_item_model], None)} ) self.foreign_table_response_model_sets[foreign_table_name] = response_model foreign_key_table[foreign_table_name] = {'local_reference_pairs_set': local_reference_pairs, 'fields': all_fields_, 'instance': foreign_table, 'db_column': foreign_table} return foreign_key_table, reference_mapper def _extra_relation_level(self, model=None, processed_table=None) -> Dict[str, Table]: if model is None: model = self.__db_model if not processed_table: processed_table = [] mapper = inspect(model) relation_level = [] for r in mapper.relationships: target_table = r.target target_model, _ = convert_table_to_model(target_table) target_table_name = target_model.__tablename__ if target_table_name and target_table_name not in processed_table and target_table_name in self.foreign_mapper: processed_table.append(str(mapper.local_table)) if self.foreign_mapper[target_table_name]["db_name"] not in relation_level: relation_level.append(self.foreign_mapper[target_table_name]["db_name"]) relation_level += self._extra_relation_level(self.foreign_mapper[target_table_name]["db_model"], processed_table=processed_table ) return relation_level def _extra_foreign_table_from_declarative_base(self, model) -> Dict[str, Table]: mapper = inspect(model) foreign_key_table = {} reference_mapper = {} for r in mapper.relationships: local, = r.local_columns local = mapper.get_property_by_column(local).expression local_table = str(local).split('.')[0] local_column = str(local).split('.')[1] local_table_instance = local.table foreign_table = r.mapper.class_ foreign_table_name = foreign_table.__tablename__ foreign_secondary_table_name = '' if r.secondary_synchronize_pairs: # foreign_table_name = r.secondary.key foreign_secondary_table_name = str(r.secondary.key) local_reference_pairs = [] ''' for i in r.synchronize_pairs: if r.secondary_synchronize_pairs: local = str(i[0]).split('.') reference = str(i[1]).split('.') local_table_instance = i[0].table reference_table_instance = i[1].table else: local = str(r.local).split('.') reference = str(i[0]).split('.') local_table_instance = r.local.table reference_table_instance = i[0].table local_table = local[0] local_column = local[1] reference_table = reference[0] reference_column = reference[1] self.reference_mapper[local_column] = foreign_table_name local_reference_pairs.append({'local': {"local_table": local_table, "local_column": local_column}, "reference": {"reference_table": reference_table, "reference_column": reference_column}, 'local_table': local_table_instance, 'local_table_columns': local_table_instance.c, 'reference_table': reference_table_instance, 'reference_table_columns': reference_table_instance.c}) ''' for i in r.synchronize_pairs: for column in i: table_name_ = str(column).split('.')[0] column_name_ = str(column).split('.')[1] if table_name_ not in [foreign_secondary_table_name, foreign_table_name]: continue reference_table = table_name_ reference_column = column_name_ reference_table_instance = column.table if r.secondary_synchronize_pairs: exclude = True else: reference_mapper[local_column] = {"foreign_table": foreign_table, "foreign_table_name": foreign_table_name} exclude = False local_reference_pairs.append({'local': {"local_table": local_table, "local_column": local_column}, "reference": {"reference_table": reference_table, "reference_column": reference_column}, 'local_table': local_table_instance, 'local_table_columns': local_table_instance.c, 'reference_table': reference_table_instance, 'reference_table_columns': reference_table_instance.c, 'exclude': exclude}) for i in r.secondary_synchronize_pairs: local_table_: str = None local_column_: str = None reference_table_: str = None reference_column_: str = None local_table_instance_: Table = None reference_table_instance_: Table = None for column in i: table_name_ = str(column).split('.')[0] column_name_ = str(column).split('.')[1] if table_name_ == foreign_secondary_table_name: local_table_ = str(column).split('.')[0] local_column_ = str(column).split('.')[1] local_table_instance_ = column.table if table_name_ == foreign_table_name: reference_table_ = str(column).split('.')[0] reference_column_ = str(column).split('.')[1] reference_table_instance_ = column.table reference_mapper[local_column_] = {"foreign_table": foreign_table, "foreign_table_name": foreign_table_name} local_reference_pairs.append({'local': {"local_table": local_table_, "local_column": local_column_}, "reference": {"reference_table": reference_table_, "reference_column": reference_column_}, 'local_table': local_table_instance_, 'local_table_columns': local_table_instance_.c, 'reference_table': reference_table_instance_, 'reference_table_columns': reference_table_instance_.c, 'exclude': False}) all_fields_ = self._extract_all_field(foreign_table.__table__.c) response_fields = [] for i in all_fields_: response_fields.append((i['column_name'], i['column_type'], None)) response_model_dataclass = make_dataclass( f'foreign_{foreign_table_name + str(uuid.uuid4())}_FindManyResponseItemModel', response_fields, ) response_item_model = _model_from_dataclass(response_model_dataclass) response_item_model = _add_orm_model_config_into_pydantic_model(response_item_model, config=OrmConfig) response_model = create_model( f'foreign_{foreign_table_name + str(uuid.uuid4())}_GetManyResponseForeignModel', **{'__root__': (Union[List[response_item_model], None], None)} ) self.foreign_table_response_model_sets[foreign_table] = response_model foreign_key_table[foreign_table_name] = {'local_reference_pairs_set': local_reference_pairs, 'fields': all_fields_, 'instance': foreign_table, 'db_column': foreign_table} return foreign_key_table, reference_mapper @staticmethod def _value_of_list_to_str(request_or_response_object, columns): received_request = deepcopy(request_or_response_object.__dict__) if isinstance(columns, str): columns = [columns] if 'insert' in request_or_response_object.__dict__: insert_str_list = [] for insert_item in request_or_response_object.__dict__['insert']: for column in columns: for insert_item_column, _ in insert_item.__dict__.items(): if column in insert_item_column: value_ = insert_item.__dict__[insert_item_column] if value_ is not None: if isinstance(value_, list): str_value_ = [str(i) for i in value_] else: str_value_ = str(value_) setattr(insert_item, insert_item_column, str_value_) insert_str_list.append(insert_item) setattr(request_or_response_object, 'insert', insert_str_list) else: for column in columns: for received_column_name, _ in received_request.items(): if column in received_column_name: value_ = received_request[received_column_name] if value_ is not None: if isinstance(value_, list): str_value_ = [str(i) for i in value_] else: str_value_ = str(value_) setattr(request_or_response_object, received_column_name, str_value_) @staticmethod def _assign_join_table_instance(request_or_response_object, join_table_mapping): received_request = deepcopy(request_or_response_object.__dict__) join_table_replace = {} if 'join_foreign_table' in received_request: for join_table in received_request['join_foreign_table']: if join_table in join_table_mapping: join_table_replace[str(join_table)] = join_table_mapping[join_table] setattr(request_or_response_object, 'join_foreign_table', join_table_replace) @staticmethod def _get_many_string_matching_patterns_description_builder(): return '''
Composite string field matching pattern

Allow to select more than one pattern for string query
https://www.postgresql.org/docs/9.3/functions-matching.html ''' @staticmethod def _get_many_order_by_columns_description_builder(all_columns, regex_validation, primary_name): return f'''
support column:
{all_columns}

support ordering:
{list(map(str, Ordering))}

example:
  {primary_name}:ASC
  {primary_name}: DESC
  {primary_name} : DESC
  {primary_name} (default sort by ASC)''' @staticmethod def _extra_default_value(column): if not column.nullable: if column.default is not None: default = column.default.arg elif column.server_default is not None: default = None elif column.primary_key and column.autoincrement == True: default = None else: default = ... else: if column.default is not None: default = column.default.arg else: default = None return default def _assign_str_matching_pattern(self, field_of_param: dict, result_: List[dict]) -> List[dict]: if self.sql_type == SqlType.postgresql: operator = List[PGSQLMatchingPatternInString] else: operator = List[MatchingPatternInStringBase] for i in [ {'column_name': field_of_param['column_name'] + ExtraFieldTypePrefix.Str + ExtraFieldType.Matching_pattern, 'column_type': Optional[operator], 'column_default': [MatchingPatternInStringBase.case_sensitive], 'column_description': ""}, {'column_name': field_of_param['column_name'] + ExtraFieldTypePrefix.Str, 'column_type': Optional[List[field_of_param['column_type']]], 'column_default': None, 'column_description': field_of_param['column_description']} ]: result_.append(i) return result_ @staticmethod def _assign_list_comparison(field_of_param, result_: List[dict]) -> List[dict]: for i in [ { 'column_name': field_of_param[ 'column_name'] + f'{ExtraFieldTypePrefix.List}{ExtraFieldType.Comparison_operator}', 'column_type': Optional[ItemComparisonOperators], 'column_default': ItemComparisonOperators.In, 'column_description': ""}, {'column_name': field_of_param['column_name'] + ExtraFieldTypePrefix.List, 'column_type': Optional[List[field_of_param['column_type']]], 'column_default': None, 'column_description': field_of_param['column_description']} ]: result_.append(i) return result_ @staticmethod def _assign_range_comparison(field_of_param, result_: List[dict]) -> List[dict]: for i in [ {'column_name': field_of_param[ 'column_name'] + f'{ExtraFieldTypePrefix.From}{ExtraFieldType.Comparison_operator}', 'column_type': Optional[RangeFromComparisonOperators], 'column_default': RangeFromComparisonOperators.Greater_than_or_equal_to, 'column_description': ""}, {'column_name': field_of_param[ 'column_name'] + f'{ExtraFieldTypePrefix.To}{ExtraFieldType.Comparison_operator}', 'column_type': Optional[RangeToComparisonOperators], 'column_default': RangeToComparisonOperators.Less_than.Less_than_or_equal_to, 'column_description': ""}, ]: result_.append(i) for i in [ {'column_name': field_of_param['column_name'] + ExtraFieldTypePrefix.From, 'column_type': Optional[NewType(ExtraFieldTypePrefix.From, field_of_param['column_type'])], 'column_default': None, 'column_description': field_of_param['column_description']}, {'column_name': field_of_param['column_name'] + ExtraFieldTypePrefix.To, 'column_type': Optional[NewType(ExtraFieldTypePrefix.To, field_of_param['column_type'])], 'column_default': None, 'column_description': field_of_param['column_description']} ]: result_.append(i) return result_ def _assign_foreign_join(self, result_, table_of_foreign=None) -> List[Union[Tuple, Dict]]: if table_of_foreign is None: table_of_foreign = self.table_of_foreign if not self.table_of_foreign: return result_ table_name_enum = StrEnum('TableName' + str(uuid.uuid4()), {table_name: auto() for table_name in table_of_foreign}) result_.append(('join_foreign_table', Optional[List[table_name_enum]], Query(None))) return result_ def _get_fizzy_query_param(self, exclude_column: List[str] = None, fields=None) -> List[dict]: if not fields: fields = self.all_field if not exclude_column: exclude_column = [] fields_: List[dict] = deepcopy(fields) result = [] for field_ in fields_: if field_['column_name'] in exclude_column: continue if "column_foreign" in field_ and field_['column_foreign']: jump = False for foreign in field_['column_foreign']: if foreign in exclude_column: jump = True if jump: continue field_['column_default'] = None if field_['column_name'] in self.str_type_columns: result = self._assign_str_matching_pattern(field_, result) result = self._assign_list_comparison(field_, result) elif field_['column_name'] in self.uuid_type_columns or \ field_['column_name'] in self.bool_type_columns: result = self._assign_list_comparison(field_, result) elif field_['column_name'] in self.number_type_columns or \ field_['column_name'] in self.datetime_type_columns: result = self._assign_range_comparison(field_, result) result = self._assign_list_comparison(field_, result) return result def _assign_pagination_param(self, result_: List[tuple]) -> List[Union[Tuple, Dict]]: all_column_ = [i['column_name'] for i in self.all_field] regex_validation = "(?=(" + '|'.join(all_column_) + r")?\s?:?\s*?(?=(" + '|'.join( list(map(str, Ordering))) + r"))?)" columns_with_ordering = pydantic.constr(regex=regex_validation) for i in [ ('limit', Optional[int], Query(None)), ('offset', Optional[int], Query(None)), ('order_by_columns', Optional[List[columns_with_ordering]], Query( # [f"{self._primary_key}:ASC"], None, description=self._get_many_order_by_columns_description_builder( all_columns=all_column_, regex_validation=regex_validation, primary_name='any name of column'))) ]: result_.append(i) return result_ def upsert_one(self) -> Tuple: request_validation = [lambda self_object: _filter_none(self_object)] request_fields = [] response_fields = [] # Create on_conflict Model all_column_ = [i['column_name'] for i in self.all_field] conflict_columns = ('update_columns', Optional[List[str]], Body(set(all_column_) - set(self.unique_fields), description='update_columns should contain which columns you want to update ' 'when the unique columns got conflict')) conflict_model = make_dataclass( f'{self.db_name + str(uuid.uuid4())}_Upsert_one_request_update_columns_when_conflict_request_body_model', [conflict_columns]) on_conflict_handle = [('on_conflict', Optional[conflict_model], Body(None))] # Create Request and Response Model all_field = deepcopy(self.all_field) for i in all_field: request_fields.append((i['column_name'], i['column_type'], Body(i['column_default'], description=i['column_description']))) response_fields.append((i['column_name'], i['column_type'], Body(i['column_default'], description=i['column_description']))) # Ready the uuid to str validator if self.uuid_type_columns: request_validation.append(lambda self_object: self._value_of_list_to_str(self_object, self.uuid_type_columns)) # request_body_model = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_Upsert_one_request_model', request_fields + on_conflict_handle, namespace={ '__post_init__': lambda self_object: [i(self_object) for i in request_validation] }) response_model_dataclass = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_Upsert_one_response_model', response_fields) response_model_pydantic = _model_from_dataclass(response_model_dataclass) response_model = _to_require_but_default(response_model_pydantic) response_model = _add_orm_model_config_into_pydantic_model(response_model, config=OrmConfig) return None, request_body_model, response_model def upsert_many(self) -> Tuple: insert_fields = [] response_fields = [] # Create on_conflict Model all_column_ = [i['column_name'] for i in self.all_field] conflict_columns = ('update_columns', Optional[List[str]], Body(set(all_column_) - set(self.unique_fields), description='update_columns should contain which columns you want to update ' 'when the unique columns got conflict')) conflict_model = make_dataclass( f'{self.db_name + str(uuid.uuid4())}_Upsert_many_request_update_columns_when_conflict_request_body_model', [conflict_columns]) on_conflict_handle = [('on_conflict', Optional[conflict_model], Body(None))] # Ready the Request and Response Model all_field = deepcopy(self.all_field) for i in all_field: insert_fields.append((i['column_name'], i['column_type'], field(default=Body(i['column_default'], description=i['column_description'])))) response_fields.append((i['column_name'], i['column_type'], Body(i['column_default'], description=i['column_description']))) request_validation = [lambda self_object: _filter_none(self_object)] if self.uuid_type_columns: request_validation.append(lambda self_object: self._value_of_list_to_str(self_object, self.uuid_type_columns)) insert_item_field_model_pydantic = make_dataclass( f'{self.db_name + str(uuid.uuid4())}_UpsertManyInsertItemRequestModel', insert_fields ) # Create List Model with contains item insert_list_field = [('insert', List[insert_item_field_model_pydantic], Body(...))] request_body_model = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_UpsertManyRequestBody', insert_list_field + on_conflict_handle , namespace={ '__post_init__': lambda self_object: [validator_(self_object) for validator_ in request_validation]} ) response_model_dataclass = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_UpsertManyResponseItemModel', response_fields) response_model_pydantic = _model_from_dataclass(response_model_dataclass) response_item_model = _to_require_but_default(response_model_pydantic) response_item_model = _add_orm_model_config_into_pydantic_model(response_item_model, config=OrmConfig) response_model = create_model( f'{self.db_name + str(uuid.uuid4())}_UpsertManyResponseListModel', **{'__root__': (List[response_item_model], None)} ) return None, request_body_model, response_model def create_one(self) -> Tuple: request_validation = [lambda self_object: _filter_none(self_object)] request_fields = [] response_fields = [] # Create Request and Response Model all_field = deepcopy(self.all_field) for i in all_field: request_fields.append((i['column_name'], i['column_type'], Body(i['column_default'], description=i['column_description']))) response_fields.append((i['column_name'], i['column_type'], Body(i['column_default'], description=i['column_description']))) # Ready the uuid to str validator if self.uuid_type_columns: request_validation.append(lambda self_object: self._value_of_list_to_str(self_object, self.uuid_type_columns)) # request_body_model = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_Create_one_request_model', request_fields, namespace={ '__post_init__': lambda self_object: [i(self_object) for i in request_validation] }) response_model_dataclass = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_Create_one_response_model', response_fields) response_model_pydantic = _model_from_dataclass(response_model_dataclass) response_model = _to_require_but_default(response_model_pydantic) response_model = _add_orm_model_config_into_pydantic_model(response_model, config=OrmConfig) return None, request_body_model, response_model def create_many(self) -> Tuple: insert_fields = [] response_fields = [] # Ready the Request and Response Model all_field = deepcopy(self.all_field) for i in all_field: insert_fields.append((i['column_name'], i['column_type'], field(default=Body(i['column_default'], description=i['column_description'])))) response_fields.append((i['column_name'], i['column_type'], Body(i['column_default'], description=i['column_description']))) request_validation = [lambda self_object: _filter_none(self_object)] if self.uuid_type_columns: request_validation.append(lambda self_object: self._value_of_list_to_str(self_object, self.uuid_type_columns)) insert_item_field_model_pydantic = make_dataclass( f'{self.db_name + str(uuid.uuid4())}_CreateManyInsertItemRequestModel', insert_fields ) # Create List Model with contains item insert_list_field = [('insert', List[insert_item_field_model_pydantic], Body(...))] request_body_model = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_CreateManyRequestBody', insert_list_field , namespace={ '__post_init__': lambda self_object: [validator_(self_object) for validator_ in request_validation]} ) response_model_dataclass = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_UpsertManyResponseItemModel', response_fields) response_model_pydantic = _model_from_dataclass(response_model_dataclass) response_item_model = _to_require_but_default(response_model_pydantic) response_item_model = _add_orm_model_config_into_pydantic_model(response_item_model, config=OrmConfig) response_model = create_model( f'{self.db_name + str(uuid.uuid4())}_UpsertManyResponseListModel', **{'__root__': (List[response_item_model], None)} ) return None, request_body_model, response_model def find_many(self) -> Tuple: query_param: List[dict] = self._get_fizzy_query_param() query_param: List[Tuple] = self._assign_pagination_param(query_param) query_param: List[Union[Tuple, Dict]] = self._assign_foreign_join(query_param) response_fields = [] all_field = deepcopy(self.all_field) for local_column, refer_table_info in self.reference_mapper.items(): response_fields.append((f"{refer_table_info['foreign_table_name']}_foreign", self.foreign_table_response_model_sets[refer_table_info['foreign_table']], None)) for i in all_field: response_fields.append((i['column_name'], i['column_type'], None)) # i['column_type'])) request_fields = [] for i in query_param: assert isinstance(i, Tuple) or isinstance(i, dict) if isinstance(i, Tuple): request_fields.append(i) if isinstance(i, dict): request_fields.append((i['column_name'], i['column_type'], Query(i['column_default'], description=i['column_description']))) request_validation = [lambda self_object: _filter_none(self_object)] if self.table_of_foreign: request_validation.append(lambda self_object: self._assign_join_table_instance(self_object, self.table_of_foreign)) if self.uuid_type_columns: request_validation.append(lambda self_object: self._value_of_list_to_str(self_object, self.uuid_type_columns)) request_query_model = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_FindManyRequestBody', request_fields, namespace={ '__post_init__': lambda self_object: [validator_(self_object) for validator_ in request_validation]} ) response_model_dataclass = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_FindManyResponseItemModel', response_fields, ) response_list_item_model = _model_from_dataclass(response_model_dataclass) response_list_item_model = _add_orm_model_config_into_pydantic_model(response_list_item_model, config=OrmConfig) response_model = create_model( f'{self.db_name + str(uuid.uuid4())}_FindManyResponseListModel', **{'__root__': (Union[List[response_list_item_model], Any], None), '__base__': ExcludeUnsetBaseModel} ) return request_query_model, None, response_model def _extra_relation_primary_key(self, relation_dbs): primary_key_columns = [] foreign_table_name = "" primary_column_names = [] for db_model_table in relation_dbs: table_name = db_model_table.key foreign_table_name += table_name + "_" primary_list = db_model_table.primary_key.columns.values() primary_key_column, = primary_list column_type = str(primary_key_column.type) try: python_type = primary_key_column.type.python_type if column_type in self.unsupported_data_types: raise ColumnTypeNotSupportedException( f'The type of column {primary_key_column.key} ({column_type}) not supported yet') if column_type in self.partial_supported_data_types: warnings.warn( f'The type of column {primary_key_column.key} ({column_type}) ' f'is not support data query (as a query parameters )') except NotImplementedError: if column_type == "UUID": python_type = uuid.UUID else: raise ColumnTypeNotSupportedException( f'The type of column {primary_key_column.key} ({column_type}) not supported yet') # handle if python type is UUID if python_type.__name__ in ['str', 'int', 'float', 'Decimal', 'UUID', 'bool', 'date', 'time', 'datetime']: column_type = python_type else: raise ColumnTypeNotSupportedException( f'The type of column {primary_key_column.key} ({column_type}) not supported yet') default = self._extra_default_value(primary_key_column) if default is ...: warnings.warn( f'The column of {primary_key_column.key} has not default value ' f'and it is not nullable and in exclude_list' f'it may throw error when you insert data ') description = self._get_field_description(primary_key_column) primary_column_name = str(primary_key_column.key) alias_primary_column_name = table_name + FOREIGN_PATH_PARAM_KEYWORD + str(primary_key_column.key) primary_column_names.append(alias_primary_column_name) primary_key_columns.append((alias_primary_column_name, column_type, Query(default, description=description))) # TODO test foreign uuid key primary_columns_model: DataClassT = make_dataclass(f'{foreign_table_name + str(uuid.uuid4())}_PrimaryKeyModel', primary_key_columns, namespace={ '__post_init__': lambda self_object: self._value_of_list_to_str( self_object, self.uuid_type_columns) }) assert primary_column_names and primary_columns_model and primary_key_columns return primary_column_names, primary_columns_model, primary_key_columns def find_one(self) -> Tuple: query_param: List[dict] = self._get_fizzy_query_param(self.primary_key_str) query_param: List[Union[Tuple, Dict]] = self._assign_foreign_join(query_param) response_fields = [] all_field = deepcopy(self.all_field) for local_column, refer_table_info in self.reference_mapper.items(): response_fields.append((f"{refer_table_info['foreign_table_name']}_foreign", self.foreign_table_response_model_sets[refer_table_info['foreign_table']], None)) for i in all_field: response_fields.append((i['column_name'], i['column_type'], Body(i['column_default']))) request_fields = [] for i in query_param: assert isinstance(i, dict) or isinstance(i, tuple) if isinstance(i, Tuple): request_fields.append(i) else: request_fields.append((i['column_name'], i['column_type'], Query(i['column_default'], description=i['column_description']))) request_validation = [lambda self_object: _filter_none(self_object)] if self.uuid_type_columns: request_validation.append(lambda self_object: self._value_of_list_to_str(self_object, self.uuid_type_columns)) if self.table_of_foreign: request_validation.append(lambda self_object: self._assign_join_table_instance(self_object, self.table_of_foreign)) request_query_model = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_FindOneRequestBody', request_fields, namespace={ '__post_init__': lambda self_object: [validator_(self_object) for validator_ in request_validation] } ) response_model_dataclass = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_FindOneResponseModel', response_fields, namespace={ '__post_init__': lambda self_object: [validator_(self_object) for validator_ in request_validation]} ) response_model = _model_from_dataclass(response_model_dataclass) response_model = _add_orm_model_config_into_pydantic_model(response_model, config=OrmConfig) response_model = create_model( f'{self.db_name + str(uuid.uuid4())}_FindOneResponseListModel', **{'__root__': (response_model, None), '__base__': ExcludeUnsetBaseModel} ) return self._primary_key_dataclass_model, request_query_model, None, response_model, None def delete_one(self) -> Tuple: query_param: List[dict] = self._get_fizzy_query_param(self.primary_key_str) response_fields = [] all_field = deepcopy(self.all_field) for i in all_field: response_fields.append((i['column_name'], i['column_type'], Body(i['column_default']))) request_fields = [] for i in query_param: assert isinstance(i, dict) request_fields.append((i['column_name'], i['column_type'], Query(i['column_default'], description=i['column_description']))) request_validation = [lambda self_object: _filter_none(self_object)] if self.uuid_type_columns: request_validation.append(lambda self_object: self._value_of_list_to_str(self_object, self.uuid_type_columns)) response_validation = [lambda self_object: self._value_of_list_to_str(self_object, self.uuid_type_columns)] request_query_model = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_DeleteOneRequestBody', request_fields, namespace={ '__post_init__': lambda self_object: [validator_(self_object) for validator_ in request_validation] } ) response_model = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_DeleteOneResponseModel', response_fields, namespace={ '__post_init__': lambda self_object: [validator_(self_object) for validator_ in response_validation]} ) response_model = _model_from_dataclass(response_model) response_model = _add_orm_model_config_into_pydantic_model(response_model, config=OrmConfig) return self._primary_key_dataclass_model, request_query_model, None, response_model def delete_many(self) -> Tuple: query_param: List[dict] = self._get_fizzy_query_param() response_fields = [] all_field = deepcopy(self.all_field) for i in all_field: response_fields.append((i['column_name'], i['column_type'], Body(i['column_default']))) request_fields = [] for i in query_param: assert isinstance(i, dict) request_fields.append((i['column_name'], i['column_type'], Query(i['column_default'], description=i['column_description']))) request_validation = [lambda self_object: _filter_none(self_object)] if self.uuid_type_columns: request_validation.append(lambda self_object: self._value_of_list_to_str(self_object, self.uuid_type_columns)) response_validation = [lambda self_object: self._value_of_list_to_str(self_object, self.uuid_type_columns)] request_query_model = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_DeleteManyRequestBody', request_fields, namespace={ '__post_init__': lambda self_object: [validator_(self_object) for validator_ in request_validation] } ) # response_model = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_DeleteManyResponseModel', # response_fields, # namespace={ # '__post_init__': lambda self_object: [validator_(self_object) # for validator_ in # response_validation]} # ) response_model = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_DeleteManyResponseModel', response_fields, namespace={ '__post_init__': lambda self_object: [validator_(self_object) for validator_ in response_validation]} ) response_model = _model_from_dataclass(response_model) response_model = _add_orm_model_config_into_pydantic_model(response_model, config=OrmConfig) response_model = create_model( f'{self.db_name + str(uuid.uuid4())}_DeleteManyResponseListModel', **{'__root__': (List[response_model], None)} ) return None, request_query_model, None, response_model def patch(self) -> Tuple: query_param: List[dict] = self._get_fizzy_query_param(self.primary_key_str) response_fields = [] all_field = deepcopy(self.all_field) request_body_fields = [] for i in all_field: response_fields.append((i['column_name'], i['column_type'], Body(i['column_default']))) if i['column_name'] != self.primary_key_str: request_body_fields.append((i['column_name'], i['column_type'], Body(None, description=i['column_description']))) request_query_fields = [] for i in query_param: assert isinstance(i, dict) request_query_fields.append((i['column_name'], i['column_type'], Query(i['column_default'], description=i['column_description']))) request_validation = [lambda self_object: _filter_none(self_object)] if self.uuid_type_columns: request_validation.append(lambda self_object: self._value_of_list_to_str(self_object, self.uuid_type_columns)) request_query_model = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_PatchOneRequestQueryBody', request_query_fields, namespace={ '__post_init__': lambda self_object: [validator_(self_object) for validator_ in request_validation] } ) request_body_model = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_PatchOneRequestBodyBody', request_body_fields, namespace={ '__post_init__': lambda self_object: [validator_(self_object) for validator_ in request_validation] } ) response_model_dataclass = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_PatchOneResponseModel', response_fields, namespace={ '__post_init__': lambda self_object: [validator_(self_object) for validator_ in request_validation]} ) response_model = _model_from_dataclass(response_model_dataclass) response_model = _add_orm_model_config_into_pydantic_model(response_model, config=OrmConfig) return self._primary_key_dataclass_model, request_query_model, request_body_model, response_model def update_one(self) -> Tuple: query_param: List[dict] = self._get_fizzy_query_param(self.primary_key_str) response_fields = [] all_field = deepcopy(self.all_field) request_body_fields = [] for i in all_field: response_fields.append((i['column_name'], i['column_type'], Body(i['column_default']))) if i['column_name'] != self.primary_key_str: request_body_fields.append((i['column_name'], i['column_type'], Body(..., description=i['column_description']))) request_query_fields = [] for i in query_param: assert isinstance(i, dict) request_query_fields.append((i['column_name'], i['column_type'], Query(i['column_default'], description=i['column_description']))) request_validation = [lambda self_object: _filter_none(self_object)] if self.uuid_type_columns: request_validation.append(lambda self_object: self._value_of_list_to_str(self_object, self.uuid_type_columns)) request_query_model = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_UpdateOneRequestQueryBody', request_query_fields, namespace={ '__post_init__': lambda self_object: [validator_(self_object) for validator_ in request_validation] } ) request_body_model = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_UpdateOneRequestBodyBody', request_body_fields, namespace={ '__post_init__': lambda self_object: [validator_(self_object) for validator_ in request_validation] } ) response_model_dataclass = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_UpdateOneResponseModel', response_fields, namespace={ '__post_init__': lambda self_object: [validator_(self_object) for validator_ in request_validation]} ) response_model = _model_from_dataclass(response_model_dataclass) response_model = _add_orm_model_config_into_pydantic_model(response_model, config=OrmConfig) return self._primary_key_dataclass_model, request_query_model, request_body_model, response_model def update_many(self) -> Tuple: """ In update many, it allow you update some columns into the same value in limit of a scope, you can get the limit of scope by using request query. And fill out the columns (except the primary key column and unique columns) you want to update and the update value in the request body The response will show you the update result :return: url param dataclass model """ query_param: List[dict] = self._get_fizzy_query_param() response_fields = [] all_field = deepcopy(self.all_field) request_body_fields = [] for i in all_field: response_fields.append((i['column_name'], i['column_type'], Body(i['column_default']))) if i['column_name'] not in [self.primary_key_str]: request_body_fields.append((i['column_name'], i['column_type'], Body(..., description=i['column_description']))) request_query_fields = [] for i in query_param: assert isinstance(i, dict) request_query_fields.append((i['column_name'], i['column_type'], Query(i['column_default'], description=i['column_description']))) request_validation = [lambda self_object: _filter_none(self_object)] if self.uuid_type_columns: request_validation.append(lambda self_object: self._value_of_list_to_str(self_object, self.uuid_type_columns)) request_query_model = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_UpdateManyRequestQueryBody', request_query_fields, namespace={ '__post_init__': lambda self_object: [validator_(self_object) for validator_ in request_validation] } ) request_body_model = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_UpdateManyRequestBodyBody', request_body_fields, namespace={ '__post_init__': lambda self_object: [validator_(self_object) for validator_ in request_validation] } ) response_model_dataclass = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_UpdateManyResponseModel', response_fields, ) response_model_pydantic = _model_from_dataclass(response_model_dataclass) response_model_pydantic = _add_orm_model_config_into_pydantic_model(response_model_pydantic, config=OrmConfig) response_model = create_model( f'{self.db_name + str(uuid.uuid4())}_UpdateManyResponseListModel', **{'__root__': (List[response_model_pydantic], None)} ) response_model = _add_orm_model_config_into_pydantic_model(response_model, config=OrmConfig) return None, request_query_model, request_body_model, response_model def patch_many(self) -> Tuple: """ In update many, it allow you update some columns into the same value in limit of a scope, you can get the limit of scope by using request query. And fill out the columns (except the primary key column and unique columns) you want to update and the update value in the request body The response will show you the update result :return: url param dataclass model """ query_param: List[dict] = self._get_fizzy_query_param() response_fields = [] all_field = deepcopy(self.all_field) request_body_fields = [] for i in all_field: response_fields.append((i['column_name'], i['column_type'], Body(i['column_default']))) if i['column_name'] not in [self.primary_key_str]: request_body_fields.append((i['column_name'], i['column_type'], Body(None, description=i['column_description']))) request_query_fields = [] for i in query_param: assert isinstance(i, dict) request_query_fields.append((i['column_name'], i['column_type'], Query(i['column_default'], description=i['column_description']))) request_validation = [lambda self_object: _filter_none(self_object)] if self.uuid_type_columns: request_validation.append(lambda self_object: self._value_of_list_to_str(self_object, self.uuid_type_columns)) request_query_model = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_PatchManyRequestQueryBody', request_query_fields, namespace={ '__post_init__': lambda self_object: [validator_(self_object) for validator_ in request_validation] } ) request_body_model = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_PatchManyRequestBodyBody', request_body_fields, namespace={ '__post_init__': lambda self_object: [validator_(self_object) for validator_ in request_validation] } ) response_model_dataclass = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_PatchManyResponseModel', response_fields, namespace={ '__post_init__': lambda self_object: [validator_(self_object) for validator_ in request_validation]} ) response_model_pydantic = _model_from_dataclass(response_model_dataclass) response_model_pydantic = _add_orm_model_config_into_pydantic_model(response_model_pydantic, config=OrmConfig) response_model = create_model( f'{self.db_name + str(uuid.uuid4())}_PatchManyResponseListModel', **{'__root__': (List[response_model_pydantic], None)} ) response_model = _add_orm_model_config_into_pydantic_model(response_model, config=OrmConfig) return None, request_query_model, request_body_model, response_model def post_redirect_get(self) -> Tuple: request_validation = [lambda self_object: _filter_none(self_object)] request_body_fields = [] response_body_fields = [] # Create Request and Response Model all_field = deepcopy(self.all_field) for i in all_field: request_body_fields.append((i['column_name'], i['column_type'], Body(i['column_default'], description=i['column_description']))) response_body_fields.append((i['column_name'], i['column_type'], Body(i['column_default'], description=i['column_description']))) # Ready the uuid to str validator if self.uuid_type_columns: request_validation.append(lambda self_object: self._value_of_list_to_str(self_object, self.uuid_type_columns)) # request_body_model = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_PostAndRedirectRequestModel', request_body_fields, namespace={ '__post_init__': lambda self_object: [validator(self_object) for validator in request_validation] }) response_model_dataclass = make_dataclass(f'{self.db_name + str(uuid.uuid4())}_PostAndRedirectResponseModel', response_body_fields) response_model = _model_from_dataclass(response_model_dataclass) response_model = _add_orm_model_config_into_pydantic_model(response_model, config=OrmConfig) return None, request_body_model, response_model def foreign_tree_get_many(self) -> Tuple: _tmp = [] path = "" path += '/{' + self.db_name + FOREIGN_PATH_PARAM_KEYWORD + self.primary_key_str + '}' path_model = [self.__db_model_table] pk_list = [self.db_name + "." + self.primary_key_str] total_table_of_foreign = {} function_name = "get_many_by_pk_from" for idx, relation in enumerate(self.relation_level): table_detail = self.foreign_mapper[relation] _all_fields = table_detail["all_fields"] _primary_key = table_detail["primary_key"] _db_name = table_detail["db_name"] _db_model = table_detail["db_model"] _db_model_table = table_detail["db_model_table"] _primary_key_dataclass_model = self._extra_relation_primary_key(path_model) path_model.append(_db_model_table) _query_param: List[dict] = self._get_fizzy_query_param(pk_list, _all_fields) table_of_foreign, reference_mapper = self.extra_foreign_table(_db_model) total_table_of_foreign.update(table_of_foreign) _query_param: List[Union[Tuple, Dict]] = self._assign_foreign_join(_query_param, table_of_foreign) response_fields = [] all_field = deepcopy(_all_fields) path += '/' + _db_name + '' function_name += "_/_" + _db_name pk_list.append(_db_name + "." + _primary_key[0]) for i in all_field: response_fields.append((i['column_name'], i['column_type'], Body(i['column_default']))) request_fields = [] for i in _query_param: assert isinstance(i, dict) or isinstance(i, tuple) if isinstance(i, Tuple): request_fields.append(i) else: request_fields.append((i['column_name'], i['column_type'], Query(i['column_default'], description=i['column_description']))) request_validation = [lambda self_object: _filter_none(self_object)] if table_of_foreign: request_validation.append(lambda self_object: self._assign_join_table_instance(self_object, total_table_of_foreign)) if self.uuid_type_columns: request_validation.append(lambda self_object: self._value_of_list_to_str(self_object, self.uuid_type_columns)) for local_column, refer_table_info in reference_mapper.items(): response_fields.append((f"{refer_table_info['foreign_table_name']}_foreign", self.foreign_table_response_model_sets[refer_table_info['foreign_table']], None)) request_query_model = make_dataclass( f'{"_".join(pk_list) + str(uuid.uuid4())}_FindOneForeignTreeRequestBody', request_fields, namespace={ '__post_init__': lambda self_object: [validator_(self_object) for validator_ in request_validation]} ) response_model_dataclass = make_dataclass(f'{"_".join(pk_list) + str(uuid.uuid4())}_FindOneResponseModel', response_fields, namespace={ '__post_init__': lambda self_object: [validator_(self_object) for validator_ in request_validation]} ) response_model = _model_from_dataclass(response_model_dataclass) response_model = _add_orm_model_config_into_pydantic_model(response_model, config=OrmConfig) response_model = create_model( f'{"_".join(pk_list) + str(uuid.uuid4())}_FindManyResponseListModel', **{'__root__': (Union[List[response_model], Any], None), '__base__': ExcludeUnsetBaseModel} ) _response_model = {} _response_model["primary_key_dataclass_model"] = _primary_key_dataclass_model[1] _response_model["request_query_model"] = request_query_model _response_model["response_model"] = response_model _response_model["path"] = path _response_model["function_name"] = function_name _tmp.append(_response_model) path += '/{' + _db_name + FOREIGN_PATH_PARAM_KEYWORD + _primary_key[0] + '}' return _tmp def foreign_tree_get_one(self) -> Tuple: _tmp = [] path = "" path += '/{' + self.db_name + FOREIGN_PATH_PARAM_KEYWORD + self.primary_key_str + '}' path_model = [self.__db_model_table] pk_list = [self.db_name + "." + self.primary_key_str] total_table_of_foreign = {} function_name = "get_one_by_pk_from" for relation in self.relation_level: table_detail = self.foreign_mapper[relation] _all_fields = table_detail["all_fields"] _primary_key = table_detail["primary_key"] _db_name = table_detail["db_name"] _db_model = table_detail["db_model"] _db_model_table = table_detail["db_model_table"] path_model.append(_db_model_table) _primary_key_dataclass_model = self._extra_relation_primary_key(path_model) _query_param: List[dict] = self._get_fizzy_query_param([_primary_key[0]] + pk_list, _all_fields) table_of_foreign, reference_mapper = self.extra_foreign_table(_db_model) total_table_of_foreign.update(table_of_foreign) _query_param: List[Union[Tuple, Dict]] = self._assign_foreign_join(_query_param, table_of_foreign) response_fields = [] all_field = deepcopy(_all_fields) path += '/' + _db_name + '' path += '/{' + _db_name + FOREIGN_PATH_PARAM_KEYWORD + _primary_key[0] + '}' function_name += "_/_" + _db_name pk_list.append(_db_name + "." + _primary_key[0]) for i in all_field: response_fields.append((i['column_name'], i['column_type'], Body(i['column_default']))) request_fields = [] for i in _query_param: assert isinstance(i, dict) or isinstance(i, tuple) if isinstance(i, Tuple): request_fields.append(i) else: request_fields.append((i['column_name'], i['column_type'], Query(i['column_default'], description=i['column_description']))) request_validation = [lambda self_object: _filter_none(self_object)] if table_of_foreign: request_validation.append(lambda self_object: self._assign_join_table_instance(self_object, total_table_of_foreign)) if self.uuid_type_columns: request_validation.append(lambda self_object: self._value_of_list_to_str(self_object, self.uuid_type_columns)) for local_column, refer_table_info in reference_mapper.items(): response_fields.append((f"{refer_table_info['foreign_table_name']}_foreign", self.foreign_table_response_model_sets[refer_table_info['foreign_table']], None)) request_query_model = make_dataclass(f'{"_".join(pk_list) + str(uuid.uuid4())}_FindOneRequestBody', request_fields, namespace={ '__post_init__': lambda self_object: [validator_(self_object) for validator_ in request_validation] } ) response_model_dataclass = make_dataclass(f'{"_".join(pk_list) + str(uuid.uuid4())}_FindOneResponseModel', response_fields, namespace={ '__post_init__': lambda self_object: [validator_(self_object) for validator_ in request_validation]} ) response_model = _model_from_dataclass(response_model_dataclass) response_model = _add_orm_model_config_into_pydantic_model(response_model, config=OrmConfig) response_model = create_model( f'{"_".join(pk_list) + str(uuid.uuid4())}_FindOneResponseListModel', **{'__root__': (response_model, None), '__base__': ExcludeUnsetBaseModel} ) _response_model = {} _response_model["primary_key_dataclass_model"] = _primary_key_dataclass_model[1] _response_model["request_query_model"] = request_query_model _response_model["response_model"] = response_model _response_model["path"] = path _response_model["function_name"] = function_name _tmp.append(_response_model) return _tmp ================================================ FILE: src/fastapi_quickcrud/misc/type.py ================================================ from enum import Enum, auto from itertools import chain from strenum import StrEnum from .exceptions import InvalidRequestMethod class SqlType(StrEnum): postgresql = auto() mysql = auto() mariadb = auto() sqlite = auto() oracle = auto() mssql = auto() class Ordering(StrEnum): DESC = auto() ASC = auto() class CrudMethods(Enum): FIND_ONE = "FIND_ONE" FIND_MANY = "FIND_MANY" UPDATE_ONE = "UPDATE_ONE" UPDATE_MANY = "UPDATE_MANY" PATCH_ONE = "PATCH_ONE" PATCH_MANY = "PATCH_MANY" UPSERT_ONE = "UPSERT_ONE" UPSERT_MANY = "UPSERT_MANY" CREATE_ONE = "CREATE_ONE" CREATE_MANY = "CREATE_MANY" DELETE_ONE = "DELETE_ONE" DELETE_MANY = "DELETE_MANY" POST_REDIRECT_GET = "POST_REDIRECT_GET" FIND_ONE_WITH_FOREIGN_TREE = "FIND_ONE_WITH_FOREIGN_TREE" FIND_MANY_WITH_FOREIGN_TREE = "FIND_MANY_WITH_FOREIGN_TREE" @staticmethod def get_table_full_crud_method(): return [CrudMethods.FIND_MANY, CrudMethods.CREATE_MANY, CrudMethods.UPDATE_MANY, CrudMethods.PATCH_MANY, CrudMethods.DELETE_MANY] @staticmethod def get_declarative_model_full_crud_method(): return [CrudMethods.FIND_MANY, CrudMethods.FIND_ONE, CrudMethods.UPDATE_MANY, CrudMethods.UPDATE_ONE, CrudMethods.PATCH_MANY, CrudMethods.PATCH_ONE, CrudMethods.CREATE_MANY, CrudMethods.DELETE_MANY, CrudMethods.DELETE_ONE, CrudMethods.FIND_ONE_WITH_FOREIGN_TREE, CrudMethods.FIND_MANY_WITH_FOREIGN_TREE] class RequestMethods(Enum): GET = "GET" POST = "POST" PUT = "PUT" PATCH = "PATCH" DELETE = "DELETE" class CRUDRequestMapping(Enum): FIND_ONE = RequestMethods.GET FIND_ONE_WITH_FOREIGN_TREE = RequestMethods.GET FIND_MANY = RequestMethods.GET FIND_MANY_WITH_FOREIGN_TREE = RequestMethods.GET UPDATE_ONE = RequestMethods.PUT UPDATE_MANY = RequestMethods.PUT PATCH_ONE = RequestMethods.PATCH PATCH_MANY = RequestMethods.PATCH CREATE_ONE = RequestMethods.POST CREATE_MANY = RequestMethods.POST UPSERT_ONE = RequestMethods.POST UPSERT_MANY = RequestMethods.POST DELETE_ONE = RequestMethods.DELETE DELETE_MANY = RequestMethods.DELETE GET_VIEW = RequestMethods.GET POST_REDIRECT_GET = RequestMethods.POST @classmethod def get_request_method_by_crud_method(cls, value): crud_methods = cls.__dict__ if value not in crud_methods: raise InvalidRequestMethod( f'{value} is not an available request method, Please use CrudMethods to select available crud method') return crud_methods[value].value class ExtraFieldType(StrEnum): Comparison_operator = '_____comparison_operator' Matching_pattern = '_____matching_pattern' class ExtraFieldTypePrefix(StrEnum): List = '____list' From = '____from' To = '____to' Str = '____str' class RangeFromComparisonOperators(StrEnum): Greater_than = auto() Greater_than_or_equal_to = auto() class RangeToComparisonOperators(StrEnum): Less_than = auto() Less_than_or_equal_to = auto() class ItemComparisonOperators(StrEnum): Equal = auto() Not_equal = auto() In = auto() Not_in = auto() class MatchingPatternInStringBase(StrEnum): case_insensitive = auto() case_sensitive = auto() not_case_insensitive = auto() not_case_sensitive = auto() contains = auto() class PGSQLMatchingPattern(StrEnum): match_regex_with_case_sensitive = auto() match_regex_with_case_insensitive = auto() does_not_match_regex_with_case_sensitive = auto() does_not_match_regex_with_case_insensitive = auto() similar_to = auto() not_similar_to = auto() PGSQLMatchingPatternInString = StrEnum('PGSQLMatchingPatternInString', {Pattern: auto() for Pattern in chain(MatchingPatternInStringBase, PGSQLMatchingPattern)}) class JSONMatchingMode(str, Enum): match_the_key_value = 'match_the_key_value' match_the_value_if_not_null_by_key = 'match_the_value_if_not_null_by_key' custom_query = 'custom_query' class JSONBMatchingMode(str, Enum): match_the_key_value = 'match_the_key_value' match_the_value_if_not_null_by_key = 'match_the_value_if_not_null_by_key' custom_query = 'custom_query' class SessionObject(StrEnum): sqlalchemy = auto() databases = auto() FOREIGN_PATH_PARAM_KEYWORD = "__pk__" ================================================ FILE: src/fastapi_quickcrud/misc/utils.py ================================================ from itertools import groupby from typing import Type, List, Union, TypeVar, Optional from pydantic import BaseModel, BaseConfig from sqlalchemy import Column, Integer from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.sql.elements import \ or_, \ BinaryExpression from sqlalchemy.sql.schema import Table from .covert_model import convert_table_to_model from .crud_model import RequestResponseModel, CRUDModel from .exceptions import QueryOperatorNotFound, PrimaryMissing, UnknownColumn from .schema_builder import ApiParameterSchemaBuilder from .type import \ CrudMethods, \ CRUDRequestMapping, \ MatchingPatternInStringBase, \ ExtraFieldType, \ RangeFromComparisonOperators, \ ExtraFieldTypePrefix, \ RangeToComparisonOperators, \ ItemComparisonOperators, PGSQLMatchingPatternInString, SqlType, FOREIGN_PATH_PARAM_KEYWORD Base = TypeVar("Base", bound=declarative_base) BaseModelT = TypeVar('BaseModelT', bound=BaseModel) __all__ = [ 'sqlalchemy_to_pydantic', # 'sqlalchemy_table_to_pydantic', 'find_query_builder', 'Base', 'clean_input_fields', 'group_find_many_join', 'convert_table_to_model'] unsupported_data_types = ["BLOB"] partial_supported_data_types = ["INTERVAL", "JSON", "JSONB"] def clean_input_fields(param: Union[dict, list], model: Base): assert isinstance(param, dict) or isinstance(param, list) or isinstance(param, set) if isinstance(param, dict): stmt = {} for column_name, value in param.items(): if column_name == '__initialised__': continue column = getattr(model, column_name) actual_column_name = column.expression.key stmt[actual_column_name] = value return stmt if isinstance(param, list) or isinstance(param, set): stmt = [] for column_name in param: if not hasattr(model, column_name): raise UnknownColumn(f'column {column_name} is not exited') column = getattr(model, column_name) actual_column_name = column.expression.key stmt.append(actual_column_name) return stmt def find_query_builder(param: dict, model: Base) -> List[Union[BinaryExpression]]: query = [] for column_name, value in param.items(): if ExtraFieldType.Comparison_operator in column_name or ExtraFieldType.Matching_pattern in column_name: continue if ExtraFieldTypePrefix.List in column_name: type_ = ExtraFieldTypePrefix.List elif ExtraFieldTypePrefix.From in column_name: type_ = ExtraFieldTypePrefix.From elif ExtraFieldTypePrefix.To in column_name: type_ = ExtraFieldTypePrefix.To elif ExtraFieldTypePrefix.Str in column_name: type_ = ExtraFieldTypePrefix.Str else: query.append((getattr(model, column_name) == value)) # raise Exception('known error') continue sub_query = [] table_column_name = column_name.replace(type_, "") operator_column_name = column_name + process_type_map[type_] operators = param.get(operator_column_name, None) if not operators: raise QueryOperatorNotFound(f'The query operator of {column_name} not found!') if not isinstance(operators, list): operators = [operators] for operator in operators: sub_query.append(process_map[operator](getattr(model, table_column_name), value)) query.append((or_(*sub_query))) return query class OrmConfig(BaseConfig): orm_mode = True def sqlalchemy_to_pydantic( db_model: Type, *, crud_methods: List[CrudMethods], sql_type: str = SqlType.postgresql, exclude_columns: List[str] = None, constraints=None, foreign_include: Optional[any] = None, exclude_primary_key=False) -> CRUDModel: db_model, _ = convert_table_to_model(db_model) if exclude_columns is None: exclude_columns = [] if foreign_include is None: foreign_include = {} request_response_mode_set = {} model_builder = ApiParameterSchemaBuilder(db_model, constraints=constraints, exclude_column=exclude_columns, sql_type=sql_type, foreign_include=foreign_include, exclude_primary_key=exclude_primary_key) REQUIRE_PRIMARY_KEY_CRUD_METHOD = [CrudMethods.DELETE_ONE.value, CrudMethods.FIND_ONE.value, CrudMethods.PATCH_ONE.value, CrudMethods.POST_REDIRECT_GET.value, CrudMethods.UPDATE_ONE.value] for crud_method in crud_methods: request_url_param_model = None request_body_model = None response_model = None request_query_model = None foreignListModel = None if crud_method.value in REQUIRE_PRIMARY_KEY_CRUD_METHOD and not model_builder.primary_key_str: raise PrimaryMissing(f"The generation of this API [{crud_method.value}] requires a primary key") if crud_method.value == CrudMethods.UPSERT_ONE.value: request_query_model, \ request_body_model, \ response_model = model_builder.upsert_one() elif crud_method.value == CrudMethods.UPSERT_MANY.value: request_query_model, \ request_body_model, \ response_model = model_builder.upsert_many() elif crud_method.value == CrudMethods.CREATE_ONE.value: request_query_model, \ request_body_model, \ response_model = model_builder.create_one() elif crud_method.value == CrudMethods.CREATE_MANY.value: request_query_model, \ request_body_model, \ response_model = model_builder.create_many() elif crud_method.value == CrudMethods.DELETE_ONE.value: request_url_param_model, \ request_query_model, \ request_body_model, \ response_model = model_builder.delete_one() elif crud_method.value == CrudMethods.DELETE_MANY.value: request_url_param_model, \ request_query_model, \ request_body_model, \ response_model = model_builder.delete_many() elif crud_method.value == CrudMethods.FIND_ONE.value: request_url_param_model, \ request_query_model, \ request_body_model, \ response_model, \ relationship_list = model_builder.find_one() elif crud_method.value == CrudMethods.FIND_MANY.value: request_query_model, \ request_body_model, \ response_model = model_builder.find_many() elif crud_method.value == CrudMethods.POST_REDIRECT_GET.value: request_query_model, \ request_body_model, \ response_model = model_builder.post_redirect_get() elif crud_method.value == CrudMethods.PATCH_ONE.value: request_url_param_model, \ request_query_model, \ request_body_model, \ response_model = model_builder.patch() elif crud_method.value == CrudMethods.UPDATE_ONE.value: request_url_param_model, \ request_query_model, \ request_body_model, \ response_model = model_builder.update_one() elif crud_method.value == CrudMethods.UPDATE_MANY.value: request_url_param_model, \ request_query_model, \ request_body_model, \ response_model = model_builder.update_many() elif crud_method.value == CrudMethods.PATCH_MANY.value: request_url_param_model, \ request_query_model, \ request_body_model, \ response_model = model_builder.patch_many() elif crud_method.value == CrudMethods.FIND_ONE_WITH_FOREIGN_TREE.value: foreignListModel = model_builder.foreign_tree_get_one() elif crud_method.value == CrudMethods.FIND_MANY_WITH_FOREIGN_TREE.value: foreignListModel = model_builder.foreign_tree_get_many() request_response_models = {'requestBodyModel': request_body_model, 'responseModel': response_model, 'requestQueryModel': request_query_model, 'requestUrlParamModel': request_url_param_model, 'foreignListModel': foreignListModel} request_response_model = RequestResponseModel(**request_response_models) request_method = CRUDRequestMapping.get_request_method_by_crud_method(crud_method.value).value if request_method not in request_response_mode_set: request_response_mode_set[request_method] = {} request_response_mode_set[request_method][crud_method.value] = request_response_model return CRUDModel( **{**request_response_mode_set, **{"PRIMARY_KEY_NAME": model_builder.primary_key_str, "UNIQUE_LIST": model_builder.unique_fields}}) # def get_many_string_matching_patterns_description_builder() -> str: # return '''
Composite string field matching pattern
#
Allow to select more than one pattern for string query''' # def get_many_order_by_columns_description_builder(*, all_columns, regex_validation, primary_name) -> str: # return f'''
support column: #
{all_columns}

support ordering: #
{list(map(str, Ordering))} #
#
field input validation regex #
{regex_validation} #
#
example: #
  {primary_name}:ASC #
  {primary_name}: DESC #
  {primary_name} : DESC #
  {primary_name} (default sort by ASC)''' process_type_map = { ExtraFieldTypePrefix.List: ExtraFieldType.Comparison_operator, ExtraFieldTypePrefix.From: ExtraFieldType.Comparison_operator, ExtraFieldTypePrefix.To: ExtraFieldType.Comparison_operator, ExtraFieldTypePrefix.Str: ExtraFieldType.Matching_pattern, } process_map = { RangeFromComparisonOperators.Greater_than: lambda field, value: field > value, RangeFromComparisonOperators.Greater_than_or_equal_to: lambda field, value: field >= value, RangeToComparisonOperators.Less_than: lambda field, value: field < value, RangeToComparisonOperators.Less_than_or_equal_to: lambda field, value: field <= value, ItemComparisonOperators.Equal: lambda field, values: or_(field == value for value in values), ItemComparisonOperators.Not_equal: lambda field, values: or_(field != value for value in values), ItemComparisonOperators.In: lambda field, values: or_(field.in_(values)), ItemComparisonOperators.Not_in: lambda field, values: or_(field.notin_(values)), MatchingPatternInStringBase.case_insensitive: lambda field, values: or_(field.ilike(value) for value in values), MatchingPatternInStringBase.case_sensitive: lambda field, values: or_(field.like(value) for value in values), MatchingPatternInStringBase.not_case_insensitive: lambda field, values: or_(field.not_ilike(value) for value in values), MatchingPatternInStringBase.not_case_sensitive: lambda field, values: or_(field.not_like(value) for value in values), MatchingPatternInStringBase.contains: lambda field, values: or_(field.contains(value) for value in values), PGSQLMatchingPatternInString.similar_to: lambda field, values: or_(field.op("SIMILAR TO")(value) for value in values), PGSQLMatchingPatternInString.not_similar_to: lambda field, values: or_(field.op("NOT SIMILAR TO")(value) for value in values), PGSQLMatchingPatternInString.match_regex_with_case_sensitive: lambda field, values: or_(field.op("~")(value) for value in values), PGSQLMatchingPatternInString.match_regex_with_case_insensitive: lambda field, values: or_(field.op("~*")(value) for value in values), PGSQLMatchingPatternInString.does_not_match_regex_with_case_sensitive: lambda field, values: or_(field.op("!~")(value) for value in values), PGSQLMatchingPatternInString.does_not_match_regex_with_case_insensitive: lambda field, values: or_(field.op("!~*")(value) for value in values) } def table_to_declarative_base(db_model): db_name = str(db_model.fullname) Base = declarative_base() if not db_model.primary_key: db_model.append_column(Column('__id', Integer, primary_key=True, autoincrement=True)) table_dict = {'__tablename__': db_name} for i in db_model.c: _, = i.expression.base_columns _.table = None table_dict[str(i.key)] = _ tmp = type(f'{db_name}', (Base,), table_dict) tmp.__table__ = db_model return tmp def group_find_many_join(list_of_dict: List[dict]) -> List[dict]: def group_by_foreign_key(item): tmp = {} for k, v in item.items(): if '_foreign' not in k: tmp[k] = v return tmp response_list = [] for key, group in groupby(list_of_dict, group_by_foreign_key): response = {} for i in group: for k, v in i.items(): if '_foreign' in k: if k not in response: response[k] = [v] else: response[k].append(v) for response_ in response: i.pop(response_, None) result = {**i, **response} response_list.append(result) return response_list def path_query_builder(params, model) -> List[Union[BinaryExpression]]: query = [] if not params: return query for param_name, param_value in params.items(): table_with_column = param_name.split(FOREIGN_PATH_PARAM_KEYWORD) assert len(table_with_column) == 2 table_name, column_name = table_with_column table_model = model[table_name] query.append((getattr(table_model, column_name) == param_value)) return query ================================================ FILE: tests/__init__.py ================================================ ================================================ FILE: tests/conf/__init__.py ================================================ ================================================ FILE: tests/conf/config.py ================================================ import os import pathlib ENV_FILE_PATH = pathlib.Path(__file__).parent / "dev.env" assert ENV_FILE_PATH.exists() class BaseConfig: POSTGRES_HOST = "" POSTGRES_USER = "" POSTGRES_PASSWORD = "" POSTGRES_DB = "" POSTGRES_PORT = "" def __init__(self): self._apply_dot_env() self._apply_env_vars() self.POSTGRES_URI = f"postgresql://{self.POSTGRES_USER}:{self.POSTGRES_PASSWORD}@{self.POSTGRES_HOST}:{self.POSTGRES_PORT}/{self.POSTGRES_DB}" print(self.POSTGRES_URI) def _apply_dot_env(self): with open(ENV_FILE_PATH) as fp: for line in fp.readlines(): line = line.strip(" \n") if not line.startswith("#"): k, v = line.split("=", 1) if hasattr(self, k) and not getattr(self, k): setattr(self, k, v) def _apply_env_vars(self): for k, v in os.environ.items(): if hasattr(self, k): setattr(self, k, v) ================================================ FILE: tests/conf/dev.docker-compose.yml ================================================ version: "3.9" services: db: image: postgres restart: always env_file: - dev.env ports: - 5432:5432 ================================================ FILE: tests/conf/dev.env ================================================ POSTGRES_HOST=localhost POSTGRES_DB=test POSTGRES_USER=postgres POSTGRES_PASSWORD=password POSTGRES_PORT=5432 ================================================ FILE: tests/test_implementations/__init__.py ================================================ ================================================ FILE: tests/test_implementations/other/__init__.py ================================================ ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/__init__.py ================================================ ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_async_test/__init__.py ================================================ import os from fastapi import FastAPI from sqlalchemy import BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy.orm import declarative_base TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata class UntitledTable256(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_build_myself_memory' __table_args__ = ( UniqueConstraint('primary_key', 'int4_value', 'float4_value'), ) primary_key = Column(Integer, primary_key=True, autoincrement=True) bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) # interval_value = Column(INTERVAL) # json_value = Column(JSON) # jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) # uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) # xml_value = Column(NullType) # array_value = Column(ARRAY(Integer())) # array_str__value = Column(ARRAY(String())) # box_valaue = Column(NullType) ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_async_test/foreign_tree/__init__.py ================================================ ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_async_test/foreign_tree/test_relationship_m2m.py ================================================ import asyncio from fastapi import FastAPI from sqlalchemy import Column, Integer, \ ForeignKey, Table, CHAR from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession from sqlalchemy.orm import declarative_base, sessionmaker, relationship from src.fastapi_quickcrud.misc.type import SqlType from src.fastapi_quickcrud.crud_router import crud_router_builder app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy.pool import StaticPool engine = create_async_engine('sqlite+aiosqlite://', future=True, echo=True, pool_pre_ping=True, pool_recycle=7200, connect_args={"check_same_thread": False}, poolclass=StaticPool) session = sessionmaker(autocommit=False, autoflush=False, bind=engine, class_=AsyncSession) async def get_transaction_session(): async with session() as s: yield s association_table = Table('test_association', Base.metadata, Column('left_id', ForeignKey('test_left.id')), Column('right_id', ForeignKey('test_right.id')) ) association_table_second = Table('test_association_second', Base.metadata, Column('left_id_second', ForeignKey('test_left.id')), Column('right_id_second', ForeignKey('test_right_second.id')) ) class Child(Base): __tablename__ = 'test_right' id = Column(Integer, primary_key=True) child = Column(CHAR(10)) parent = relationship("Parent", secondary=association_table) class Parent(Base): __tablename__ = 'test_left' id = Column(Integer, primary_key=True) parent = Column(CHAR(10)) children = relationship("Child", secondary=association_table) children_second = relationship("ChildSecond", secondary=association_table_second) class ChildSecond(Base): __tablename__ = 'test_right_second' id = Column(Integer, primary_key=True) child_second = Column(CHAR(10)) children_second = relationship("Parent", secondary=association_table_second) crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child", tags=["child"], sql_type=SqlType.sqlite, foreign_include=[Parent], async_mode=True ) crud_route_association_table_second = crud_router_builder(db_session=get_transaction_session, db_model=association_table_second, prefix="/association_table_second", tags=["association_table_second"], sql_type=SqlType.sqlite, async_mode=True ) crud_route_association_table_second = crud_router_builder(db_session=get_transaction_session, db_model=association_table_second, prefix="/association_table_second", tags=["association_table_second"], sql_type=SqlType.sqlite, async_mode=True ) crud_route_child_second = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child_second", tags=["child_second"], sql_type=SqlType.sqlite, async_mode=True ) crud_route_parent = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"], foreign_include=[Child], sql_type=SqlType.sqlite, async_mode=True ) crud_route_parent2 = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"], foreign_include=[ChildSecond], sql_type=SqlType.sqlite, async_mode=True ) crud_route_association = crud_router_builder(db_session=get_transaction_session, db_model=association_table, prefix="/association", tags=["association"], sql_type=SqlType.sqlite, async_mode=True ) from starlette.testclient import TestClient [app.include_router(i) for i in [crud_route_association_table_second, crud_route_child_second, crud_route_parent, crud_route_child, crud_route_parent2, crud_route_association]] client = TestClient(app) def test_get_one_1(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } test_api_1 = "/parent/0/test_right/0?child____str_____matching_pattern=case_sensitive&child____list_____comparison_operator=In" test_api_2 = "/parent/1/test_right/1?child____str_____matching_pattern=case_sensitive&child____list_____comparison_operator=In" test_api_3 = "/parent/1/test_right/1?child____str_____matching_pattern=case_sensitive&child____list_____comparison_operator=In&join_foreign_table=test_left" test_api_4 = "/parent/1/test_right/1?child____str_____matching_pattern=case_sensitive&child____str=child1&child____list_____comparison_operator=In&child____list=child1" test_api_5 = "/parent/1/test_right/1?child____str_____matching_pattern=case_sensitive&child____str=%25child%25&child____list_____comparison_operator=In" test_api_6 = "/parent/1/test_right/1?child____str_____matching_pattern=case_sensitive&child____str=%25child%25&child____list_____comparison_operator=Equal&child____list=child1" test_api_7 = "/parent/1/test_right/1?child____str_____matching_pattern=case_sensitive&child____str=%25child%25&child____list_____comparison_operator=In&child____list=child1" test_api_8 = "/parent/1/test_right/1?child____str_____matching_pattern=case_sensitive&child____str=%25child%25&child____list_____comparison_operator=In&child____list=child1&join_foreign_table=test_left" test_api_9 = "/parent/1/test_right/1?child____str_____matching_pattern=case_sensitive&child____str=%25child%25&child____list_____comparison_operator=Not_in&child____list=child1" test_api_10 = "/parent/1/test_right/1?child____str_____matching_pattern=case_sensitive&child____str=%25child%25&child____list_____comparison_operator=Not_equal&child____list=child1" test_api_11 = "/parent/1/test_right/1?child____str_____matching_pattern=not_case_insensitive&child____str=child1&child____list_____comparison_operator=In" response = client.get(test_api_1, headers=headers) assert response.status_code == 404 response = client.get(test_api_2, headers=headers) assert response.status_code == 200 assert response.json() == {'child': 'child1', 'id': 1} response = client.get(test_api_3, headers=headers) assert response.status_code == 200 assert response.json() == {'child': 'child1', 'id': 1, 'test_left_foreign': [{'id': 1, 'parent': 'parent1'}]} response = client.get(test_api_4, headers=headers) assert response.status_code == 200 assert response.json() == {'child': 'child1', 'id': 1} response = client.get(test_api_5, headers=headers) assert response.status_code == 200 assert response.json() == {'child': 'child1', 'id': 1} response = client.get(test_api_6, headers=headers) assert response.status_code == 200 assert response.json() == {'child': 'child1', 'id': 1} response = client.get(test_api_7, headers=headers) assert response.status_code == 200 assert response.json() == {'child': 'child1', 'id': 1} response = client.get(test_api_8, headers=headers) assert response.status_code == 200 assert response.json() == {'child': 'child1', 'id': 1, 'test_left_foreign': [{'id': 1, 'parent': 'parent1'}]} response = client.get(test_api_9, headers=headers) assert response.status_code == 404 response = client.get(test_api_10, headers=headers) assert response.status_code == 404 response = client.get(test_api_11, headers=headers) assert response.status_code == 404 def test_get_one_2(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } test_api_1 = "/parent/0/test_right_second/0?child_second____str_____matching_pattern=case_sensitive&child_second____list_____comparison_operator=In" test_api_2 = "/parent/1/test_right_second/1" test_api_3 = "/parent/1/test_right_second/1?child_second____str_____matching_pattern=case_sensitive&child_second____list_____comparison_operator=In&join_foreign_table=test_left" test_api_4 = "/parent/1/test_right_second/1?child_second____str_____matching_pattern=case_sensitive&child_second____str=child_second1&child_second____list_____comparison_operator=In&child_second____list=child_second1" test_api_5 = "/parent/1/test_right_second/1?child_second____str_____matching_pattern=case_sensitive&child_second____str=%25child_second%25&child_second____list_____comparison_operator=In" test_api_6 = "/parent/1/test_right_second/1?child_second____str_____matching_pattern=case_sensitive&child_second____str=%25child_second%25&child_second____list_____comparison_operator=Equal&child_second____list=child_second1" test_api_7 = "/parent/1/test_right_second/1?child_second____str_____matching_pattern=case_sensitive&child_second____str=%25child_second%25&child_second____list_____comparison_operator=In&child_second____list=child_second1" test_api_8 = "/parent/1/test_right_second/1?child_second____str_____matching_pattern=case_sensitive&child_second____str=%25child_second%25&child_second____list_____comparison_operator=In&child_second____list=child_second1&join_foreign_table=test_left" test_api_9 = "/parent/1/test_right_second/1?child_second____str_____matching_pattern=case_sensitive&child_second____str=%25child_second%25&child_second____list_____comparison_operator=Not_in&child_second____list=child_second1" test_api_10 = "/parent/1/test_right_second/1?child_second____str_____matching_pattern=case_sensitive&child_second____str=%25child_second%25&child_second____list_____comparison_operator=Not_equal&child_second____list=child_second1" test_api_11 = "/parent/1/test_right_second/1?child_second____str_____matching_pattern=not_case_insensitive&child_second____str=child_second1&child_second____list_____comparison_operator=In" response = client.get(test_api_1, headers=headers) assert response.status_code == 404 response = client.get(test_api_2, headers=headers) assert response.status_code == 200 assert response.json() == {'child_second': 'child_second1', 'id': 1} response = client.get(test_api_3, headers=headers) assert response.status_code == 200 assert response.json() == {'child_second': 'child_second1', 'id': 1, 'test_left_foreign': [{'id': 1, 'parent': 'parent1'}]} response = client.get(test_api_4, headers=headers) assert response.status_code == 200 assert response.json() == {'child_second': 'child_second1', 'id': 1} response = client.get(test_api_5, headers=headers) assert response.status_code == 200 assert response.json() == {'child_second': 'child_second1', 'id': 1} response = client.get(test_api_6, headers=headers) assert response.status_code == 200 assert response.json() == {'child_second': 'child_second1', 'id': 1} response = client.get(test_api_7, headers=headers) assert response.status_code == 200 assert response.json() == {'child_second': 'child_second1', 'id': 1} response = client.get(test_api_8, headers=headers) assert response.status_code == 200 assert response.json() == {'child_second': 'child_second1', 'id': 1, 'test_left_foreign': [{'id': 1, 'parent': 'parent1'}]} response = client.get(test_api_9, headers=headers) assert response.status_code == 404 response = client.get(test_api_10, headers=headers) assert response.status_code == 404 response = client.get(test_api_11, headers=headers) assert response.status_code == 404 def test_get_many_1(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } test_api_1 = "/parent/0/test_right?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&child____str_____matching_pattern=case_sensitive&child____list_____comparison_operator=In" test_api_2 = "/parent/1/test_right?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&child____str_____matching_pattern=case_sensitive&child____list_____comparison_operator=In" test_api_3 = "/parent/1/test_right?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____from=1&id____to=2&id____list_____comparison_operator=In&child____str_____matching_pattern=case_sensitive&child____list_____comparison_operator=In" test_api_4 = "/parent/1/test_right?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____from=8&id____to=9&id____list_____comparison_operator=In&child____str_____matching_pattern=case_sensitive&child____list_____comparison_operator=In" test_api_5 = "/parent/1/test_right?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&id____list=0&id____list=1&id____list=2&child____str_____matching_pattern=case_sensitive&child____list_____comparison_operator=In" test_api_6 = "/parent/1/test_right?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&child____str_____matching_pattern=case_sensitive&child____str=child1&child____list_____comparison_operator=In" test_api_7 = "/parent/1/test_right?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&child____str_____matching_pattern=case_sensitive&child____str=child%25&child____list_____comparison_operator=In" test_api_8 = "/parent/1/test_right?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&child____str_____matching_pattern=case_sensitive&child____list_____comparison_operator=In&child____list=child2" test_api_9 = "/parent/1/test_right?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&child____str_____matching_pattern=case_sensitive&child____list_____comparison_operator=In&join_foreign_table=test_left" response = client.get(test_api_1, headers=headers) assert response.status_code == 204 response = client.get(test_api_2, headers=headers) assert response.status_code == 200 assert response.json() == [{'child': 'child1', 'id': 1}, {'child': 'child2', 'id': 2}, {'child': 'child3', 'id': 3}, {'child': 'child4', 'id': 4}] response = client.get(test_api_3, headers=headers) assert response.status_code == 200 assert response.json() == [{'child': 'child1', 'id': 1}, {'child': 'child2', 'id': 2}] response = client.get(test_api_4, headers=headers) assert response.status_code == 204 response = client.get(test_api_5, headers=headers) assert response.status_code == 200 assert response.json() == [{'child': 'child1', 'id': 1}, {'child': 'child2', 'id': 2}] response = client.get(test_api_6, headers=headers) assert response.status_code == 200 assert response.json() == [{'child': 'child1', 'id': 1}] response = client.get(test_api_7, headers=headers) assert response.status_code == 200 assert response.json() == [{'child': 'child1', 'id': 1}, {'child': 'child2', 'id': 2}, {'child': 'child3', 'id': 3}, {'child': 'child4', 'id': 4}] response = client.get(test_api_8, headers=headers) assert response.status_code == 200 assert response.json() == [{'child': 'child2', 'id': 2}] response = client.get(test_api_9, headers=headers) assert response.status_code == 200 assert response.json() == [{'child': 'child1', 'id': 1, 'test_left_foreign': [{'id': 1, 'parent': 'parent1'}]}] def test_get_many_2(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } test_api_1 = "/parent/0/test_right_second?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&child_second____str_____matching_pattern=case_sensitive&child_second____list_____comparison_operator=In" test_api_2 = "/parent/1/test_right_second?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&child_second____str_____matching_pattern=case_sensitive&child_second____list_____comparison_operator=In" test_api_3 = "/parent/1/test_right_second?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____from=1&id____to=2&id____list_____comparison_operator=In&child_second____str_____matching_pattern=case_sensitive&child_second____list_____comparison_operator=In" test_api_4 = "/parent/1/test_right_second?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____from=8&id____to=9&id____list_____comparison_operator=In&child_second____str_____matching_pattern=case_sensitive&child_second____list_____comparison_operator=In" test_api_5 = "/parent/1/test_right_second?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&id____list=0&id____list=1&id____list=2&child_second____str_____matching_pattern=case_sensitive&child_second____list_____comparison_operator=In" test_api_6 = "/parent/1/test_right_second?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&child_second____str_____matching_pattern=case_sensitive&child_second____str=child_second1&child_second____list_____comparison_operator=In" test_api_7 = "/parent/1/test_right_second?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&child_second____str_____matching_pattern=case_sensitive&child_second____str=child_second%25&child_second____list_____comparison_operator=In" test_api_8 = "/parent/1/test_right_second?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&child_second____str_____matching_pattern=case_sensitive&child_second____list_____comparison_operator=In&child_second____list=child_second2" test_api_9 = "/parent/1/test_right_second?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&child_second____str_____matching_pattern=case_sensitive&child_second____list_____comparison_operator=In&join_foreign_table=test_left" response = client.get(test_api_1, headers=headers) assert response.status_code == 204 response = client.get(test_api_2, headers=headers) assert response.status_code == 200 assert response.json() == [{'child_second': 'child_second1', 'id': 1}, {'child_second': 'child_second2', 'id': 2}, {'child_second': 'child_second3', 'id': 3}, {'child_second': 'child_second4', 'id': 4}] response = client.get(test_api_3, headers=headers) assert response.status_code == 200 assert response.json() == [{'child_second': 'child_second1', 'id': 1}, {'child_second': 'child_second2', 'id': 2}] response = client.get(test_api_4, headers=headers) assert response.status_code == 204 response = client.get(test_api_5, headers=headers) assert response.status_code == 200 assert response.json() == [{'child_second': 'child_second1', 'id': 1}, {'child_second': 'child_second2', 'id': 2}] response = client.get(test_api_6, headers=headers) assert response.status_code == 200 assert response.json() == [{'child_second': 'child_second1', 'id': 1}] response = client.get(test_api_7, headers=headers) assert response.status_code == 200 assert response.json() == [{'child_second': 'child_second1', 'id': 1}, {'child_second': 'child_second2', 'id': 2}, {'child_second': 'child_second3', 'id': 3}, {'child_second': 'child_second4', 'id': 4}] response = client.get(test_api_8, headers=headers) assert response.status_code == 200 assert response.json() == [{'child_second': 'child_second2', 'id': 2}] response = client.get(test_api_9, headers=headers) assert response.status_code == 200 assert response.json() == [{'child_second': 'child_second1', 'id': 1, 'test_left_foreign': [{'id': 1, 'parent': 'parent1'}]}] def setup_module(module): async def create_table(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) db = module.session() db.add(Child(id=1, child="child1")) db.add(Child(id=2, child="child2")) db.add(Child(id=3, child="child3")) db.add(Child(id=4, child="child4")) await db.flush() db.add(Parent(id=1, parent="parent1")) db.add(Parent(id=2, parent="parent2")) db.add(Parent(id=3, parent="parent3")) db.add(Parent(id=4, parent="parent4")) await db.flush() await db.execute(association_table.insert().values(left_id=1, right_id=1)) await db.execute(association_table.insert().values(left_id=2, right_id=2)) await db.execute(association_table.insert().values(left_id=3, right_id=3)) await db.execute(association_table.insert().values(left_id=4, right_id=4)) db.add(ChildSecond(id=1, child_second="child_second1")) db.add(ChildSecond(id=2, child_second="child_second2")) db.add(ChildSecond(id=3, child_second="child_second3")) db.add(ChildSecond(id=4, child_second="child_second4")) await db.flush() await db.execute(association_table_second.insert().values(left_id_second=1, right_id_second=1)) await db.execute(association_table_second.insert().values(left_id_second=2, right_id_second=2)) await db.execute(association_table_second.insert().values(left_id_second=3, right_id_second=3)) await db.execute(association_table_second.insert().values(left_id_second=4, right_id_second=4)) await db.commit() loop = asyncio.get_event_loop() loop.run_until_complete(create_table()) ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_async_test/test_create_many_api.py ================================================ import json from starlette.testclient import TestClient from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud.misc.exceptions import ConflictColumnsCannotHit from tests.test_implementations.test_memory_sqlalchemy.api_test import UntitledTable256, app # Create Many API Test test_create_many = crud_router_builder(crud_methods=[CrudMethods.CREATE_MANY], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], db_model=UntitledTable256, prefix="/test_creation_many", tags=["test"], autocommit=True, async_mode=True ) [app.include_router(i) for i in [test_create_many]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def create_example_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '[ { "bool_value": true, "char_value": "string", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963Z", "timestamptz_value": "2021-07-23T02:38:24.963Z", "varchar_value": "string"}, { "bool_value": true, "char_value": "string", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963Z", "timestamptz_value": "2021-07-23T02:38:24.963Z", "varchar_value": "string"}, { "bool_value": true, "char_value": "string", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963Z", "timestamptz_value": "2021-07-23T02:38:24.963Z", "varchar_value": "string"} ]' response = client.post('/test_creation_many', headers=headers, data=data) assert response.status_code == 201 return response.json() def test_try_only_input_required_fields(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '[ { "float4_value": 1, "int2_value": 1, "int4_value": 1 },{ "float4_value": 2, "int2_value": 2, "int4_value": 2 },{ "float4_value": 3, "int2_value": 3, "int4_value": 3 } ] ' data_ = json.loads(data) response = client.post('/test_creation_many', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_try_input_with_conflict_but_conflict_columns_not_hit(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } insert_data = [] for i in sample_data: _ = {} for k, v in {"float4_value": 99, "int2_value": 99, "int4_value": 99}.items(): _[k] = v insert_data.append(_) data = insert_data try: _ = json.dumps(data) response = client.post('/test_creation_many', headers=headers, data=json.dumps(sample_data)) except ConflictColumnsCannotHit as e: pass assert response.status_code == 409 def test_try_input_without_conflict(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {} insert_data = [] for i in sample_data: _ = {} for k, v in i.items(): _[k] = v for k, v in {"float4_value": 99, "int2_value": 99, "int4_value": 99}.items(): _[k] = v insert_data.append(_) data['insert'] = insert_data response = client.post('/test_creation_many', headers=headers, data=json.dumps(insert_data)) assert response.status_code == 409 ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_async_test/test_create_one_api.py ================================================ import json from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.exceptions import ConflictColumnsCannotHit from src.fastapi_quickcrud.misc.type import CrudMethods from tests.test_implementations.test_memory_sqlalchemy.api_test import app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_one = crud_router_builder( db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_one", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_many = crud_router_builder( db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_post_and_redirect_get = crud_router_builder( db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_get_data = crud_router_builder( db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", tags=["test"], async_mode=True ) [app.include_router(i) for i in [test_post_and_redirect_get, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields # Create One API Test def create_example_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_creation_one', headers=headers, data=data) assert response.status_code == 201 return response.json() def test_try_only_input_required_fields(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"float4_value": 0.0, "int2_value": 0, "int4_value": 0} response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) assert response.status_code == 201 response_result = response.json() for k, v in data.items(): assert response_result[k] == v def test_try_input_with_conflict_but_conflict_columns_not_hit(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"on_conflict": {"update_columns": ["bool_value", "float8_value", "varchar_value", "interval_value", "time_value", "int8_value", "jsonb_value", "timetz_value", "array_str__value", "text_value", "char_value", "uuid_value", "array_value", "numeric_value", "timestamp_value", "int2_value", "date_value", "json_value", "timestamptz_value"]}} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 99, "int2_value": 99, "int4_value": 99}.items(): data[k] = v # for k, v in {"float4_value": 99.9, "int2_value": 99, "int4_value": 99}.items(): # data[k] = v try: _ = json.dumps(data) response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) except ConflictColumnsCannotHit as e: pass assert response.status_code == 409 def test_try_input_with_conflict(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"on_conflict": {"update_columns": ["bool_value", "float8_value", "varchar_value", "interval_value", "time_value", "int8_value", "jsonb_value", "timetz_value", "array_str__value", "text_value", "char_value", "uuid_value", "array_value", "numeric_value", "timestamp_value", "int2_value", "date_value", "json_value", "timestamptz_value"]}} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 0.0, "int2_value": 99, "int4_value": 0}.items(): data[k] = v response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) assert response.status_code == 409 def test_try_input_without_conflict(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 0.0, "int2_value": 99, "int4_value": 0}.items(): data[k] = v # data['on_conflict'] = {'update_columns': []} response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) assert response.status_code == 409 ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_async_test/test_delete_many_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods from tests.test_implementations.test_memory_sqlalchemy.api_test import app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_one = crud_router_builder( db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_one", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_many = crud_router_builder( db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_post_and_redirect_get = crud_router_builder( db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_get_data = crud_router_builder( db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.DELETE_MANY ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_delete_data = crud_router_builder( db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_delete_many", tags=["test"], async_mode=True ) [app.include_router(i) for i in [test_post_and_redirect_get, test_delete_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def test_create_many_and_delete_many(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ { "bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18" , "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list":True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) response = client.delete(f'/test_delete_many?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_create_many_and_delete_many_but_not_found(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ { "bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18" , "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list":True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '10:18:18', "time_value____to": '12:18:18', "time_value____list": '12:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "timez_value____from": '18:18:18+00:00', "timez_value____to": '18:18:18+00:00', "timez_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) response = client.delete(f'/test_delete_many?{query_string}') assert response.status_code == 204 ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_async_test/test_delete_one_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_memory_sqlalchemy.api_test import app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_one = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_one", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_many = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_post_and_redirect_get = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_get_data = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.DELETE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_delete_data = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_delete_one", tags=["test"], async_mode=True ) [app.include_router(i) for i in [test_post_and_redirect_get, test_delete_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def test_create_one_and_delete_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key ,= [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False} response = client.delete(f'/test_delete_one/{primary_key}?{query_string}') response_data = response.json() assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_create_one_and_delete_one_but_not_found(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key ,= [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '10:18:18', "time_value____to": '12:18:18', "time_value____list": '10:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "timez_value____from": '18:18:18+00:00', "timez_value____to": '18:18:18+00:00', "timez_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False} response = client.delete(f'/test_delete_one/{primary_key}?{query_string}') assert response.status_code == 404 ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_async_test/test_get_many_api.py ================================================ import json from collections import OrderedDict from urllib.parse import urlencode from starlette.testclient import TestClient from src.fastapi_quickcrud.misc.exceptions import UnknownColumn, UnknownOrderType from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods from src.fastapi_quickcrud.misc.utils import sqlalchemy_to_pydantic from tests.test_implementations.test_memory_sqlalchemy.api_test import app, UntitledTable256 test_create_many = crud_router_builder(db_model=UntitledTable256, prefix="/test_creation_many", tags=["test"], exclude_columns=['bytea_value'], async_mode=True ) test_find_many = crud_router_builder(db_model=UntitledTable256, prefix="/test_get_many", tags=["test"], exclude_columns=['bytea_value'], async_mode=True ) [app.include_router(i) for i in [test_create_many, test_find_many]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields # test create many def create_example_data(num=1, **kwargs): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } insert_sample_item = {"bool_value": kwargs.get('bool_value', True), "char_value": kwargs.get('char_value', 'string'), "date_value": kwargs.get('date_value', "2021-07-23"), "float4_value": kwargs.get('float4_value', 0.6), "float8_value": kwargs.get('float8_value', 0.8), "int2_value": kwargs.get('int2_value', 11), "int4_value": kwargs.get('int4_value', 1), "int8_value": kwargs.get('int8_value', 3), "numeric_value": kwargs.get('numeric_value', 110), "text_value": kwargs.get('text_value', 'string'), "timestamp_value": kwargs.get('timestamp_value', "2021-07-23T02:38:24.963Z"), "timestamptz_value": kwargs.get('timestamptz_value', "2021-07-23T02:38:24.963Z"), "varchar_value": kwargs.get('varchar_value', 'string')} data = [insert_sample_item for i in range(num)] response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 response_result = response.json() for i in response_result: assert primary_key_name in i assert i[primary_key_name] return response_result # test pagination by offset and limit and ordering def test_pagination_and_ording(): sample_data = create_example_data(5 * 10) assert len(sample_data) == 5 * 10 limit = 5 seem = [] for num in range(0, 5 * 10, 5): response = client.get( f'/test_get_many?limit={limit}&offset={num}&order_by_columns=primary_key%20%3A%20DESC%20') response.headers['x-total-count'] == limit assert response.status_code == 200 _ = response.json() # test create a new data and get by primary key def test_create_new_data_and_get_by_primary_key(): sample_data = create_example_data(10) primary_key_list = [i[primary_key_name] for i in sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key} from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in response_data: assert i['primary_key'] in primary_key_list params = {"primary_key____from": min_key, "primary_key____to": max_key, "primary_key____from_____comparison_operator": 'Greater_than', "primary_key____to_____comparison_operator": 'Less_than'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 8 for i in response_data: assert i['primary_key'] in primary_key_list # test create a more than one data which value is TRUE of boolean type, and get many def test_create_a_more_than_one_data_which_value_is_TRUE_of_boolean_type_and_get_many(): bool_false_sample_data = create_example_data(5, bool_value=False) bool_true_sample_data = create_example_data(5, bool_value=True) primary_key_list = [i[primary_key_name] for i in bool_false_sample_data] + \ [i[primary_key_name] for i in bool_true_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "In", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) + f"&bool_value____list=False" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "In", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "In", "bool_value____list": False} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Equal", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) + f"&bool_value____list=False" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Equal", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Equal", "bool_value____list": False} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_in", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) + f"&bool_value____list=False" response = client.get(f'/test_get_many?{query_string}') assert response.status_code == 204 params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_in", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_in", "bool_value____list": False} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_equal", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) + f"&bool_value____list=False" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_equal", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_equal", "bool_value____list": False} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # test create a more than one data of char/text/varchar type, and get many def test_create_a_more_than_one_data_and_get_many_1(): char_str_sample_data = create_example_data(5, char_value='string') char_test_sample_data = create_example_data(5, char_value='test') primary_key_list = [i[primary_key_name] for i in char_str_sample_data] + \ [i[primary_key_name] for i in char_test_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) # match_regex_with_case_sensitive/ dose not match_regex_with_case_sensitive # def match_regex_with_case_sensitive(): # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'match_regex_with_case_sensitive', # "char_value____str": 'str.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # _ = response.json() # assert i in _ # for i in char_test_sample_data: # assert i not in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'match_regex_with_case_sensitive', # "char_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # # not_match_regex_with_case_sensitive # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', # "char_value____str": 'str.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', # "char_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i not in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'match_regex_with_case_sensitive', # "char_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'match_regex_with_case_insensitive', # "char_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', # "char_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', # "char_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # # def match_regex_with_case_insensitive(): # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'match_regex_with_case_insensitive', # "char_value____str": 'STR.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i not in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'match_regex_with_case_insensitive', # "char_value____str": 'TES.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # # does_not_match_regex_with_case_insensitive # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', # "char_value____str": 'STR.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', # "char_value____str": 'TES.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i not in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', # "char_value____str": 'TES.*'} # query_string = urlencode(OrderedDict(**params)) + "&char_value____str=STR.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', # "char_value____str": 'TES.*'} # query_string = urlencode(OrderedDict(**params)) + "&char_value____str=STR.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() def case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'case_sensitive', "char_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response_data # for i in char_test_sample_data: # assert i not in response_data params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'case_sensitive', "char_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # not_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_sensitive', "char_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_sensitive', "char_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_sensitive', "char_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=string" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_insensitive', "char_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=string" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() def case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'case_insensitive', "char_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'case_insensitive', "char_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_insensitive', "char_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_insensitive', "char_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_insensitive', "char_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_sensitive', "char_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # def similar_to(): # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'similar_to', # "char_value____str": 'string%'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i not in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'similar_to', # "char_value____str": 'test%'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # # not_case_insensitive # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'not_similar_to', # "char_value____str": 'string%'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'not_similar_to', # "char_value____str": 'test%'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i not in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'similar_to'} # query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str%&char_value____str=_es%" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'similar_to'} # query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str%&char_value____str=_es%" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # match_regex_with_case_sensitive() # match_regex_with_case_insensitive() case_sensitive() case_insensitive() # similar_to() # Varchar char_str_sample_data = create_example_data(5, varchar_value='string') char_test_sample_data = create_example_data(5, varchar_value='test') primary_key_list = [i[primary_key_name] for i in char_str_sample_data] + \ [i[primary_key_name] for i in char_test_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) # match_regex_with_case_sensitive/ dose not match_regex_with_case_sensitive # def match_regex_with_case_sensitive(): # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'match_regex_with_case_sensitive', # "varchar_value____str": 'str.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i not in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'match_regex_with_case_sensitive', # "varchar_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # for i in char_str_sample_data: # # assert i not in response.json() # # for i in char_test_sample_data: # # assert i in response.json() # # # not_match_regex_with_case_sensitive # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', # "varchar_value____str": 'str.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # for i in char_str_sample_data: # # assert i not in response.json() # # for i in char_test_sample_data: # # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', # "varchar_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i not in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'match_regex_with_case_sensitive', # "varchar_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'match_regex_with_case_insensitive', # "varchar_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i in response.json() # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', # "varchar_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', # "varchar_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i in response.json() # # def match_regex_with_case_insensitive(): # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'match_regex_with_case_insensitive', # "varchar_value____str": 'STR.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i not in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'match_regex_with_case_insensitive', # "varchar_value____str": 'TES.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # for i in char_str_sample_data: # # assert i not in response.json() # # for i in char_test_sample_data: # # assert i in response.json() # # # does_not_match_regex_with_case_insensitive # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', # "varchar_value____str": 'STR.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # for i in char_str_sample_data: # # assert i not in response.json() # # for i in char_test_sample_data: # # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', # "varchar_value____str": 'TES.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i not in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', # "varchar_value____str": 'TES.*'} # query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=STR.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', # "varchar_value____str": 'TES.*'} # query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=STR.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i in response.json() def case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # not_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_sensitive', "varchar_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_sensitive', "varchar_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_sensitive', "varchar_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=strinG" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_insensitive', "varchar_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=string" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() def case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'case_insensitive', "varchar_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'case_insensitive', "varchar_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_insensitive', "varchar_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_insensitive', "varchar_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_insensitive', "varchar_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_sensitive', "varchar_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # def similar_to(): # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'similar_to', # "varchar_value____str": 'string%'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i not in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'similar_to', # "varchar_value____str": 'test%'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # for i in char_str_sample_data: # # assert i not in response.json() # # for i in char_test_sample_data: # # assert i in response.json() # # # not_case_insensitive # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'not_similar_to', # "varchar_value____str": 'string%'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # for i in char_str_sample_data: # # assert i not in response.json() # # for i in char_test_sample_data: # # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'not_similar_to', # "varchar_value____str": 'test%'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i not in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'similar_to'} # query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str%&varchar_value____str=_es%" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'similar_to'} # query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str%&varchar_value____str=_es%" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # match_regex_with_case_sensitive() # match_regex_with_case_insensitive() case_sensitive() case_insensitive() # similar_to() # Text char_str_sample_data = create_example_data(5, text_value='string') char_test_sample_data = create_example_data(5, text_value='test') primary_key_list = [i[primary_key_name] for i in char_str_sample_data] + \ [i[primary_key_name] for i in char_test_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) # match_regex_with_case_sensitive/ dose not match_regex_with_case_sensitive # def match_regex_with_case_sensitive(): # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'match_regex_with_case_sensitive', # "text_value____str": 'str.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'match_regex_with_case_sensitive', # "text_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # # not_match_regex_with_case_sensitive # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', # "text_value____str": 'str.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', # "text_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'match_regex_with_case_sensitive', # "text_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'match_regex_with_case_insensitive', # "text_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', # "text_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', # "text_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # def match_regex_with_case_insensitive(): # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'match_regex_with_case_insensitive', # "text_value____str": 'STR.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'match_regex_with_case_insensitive', # "text_value____str": 'TES.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # # does_not_match_regex_with_case_insensitive # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', # "text_value____str": 'STR.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', # "text_value____str": 'TES.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', # "text_value____str": 'TES.*'} # query_string = urlencode(OrderedDict(**params)) + "&text_value____str=STR.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', # "text_value____str": 'TES.*'} # query_string = urlencode(OrderedDict(**params)) + "&text_value____str=STR.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() def case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'case_sensitive', "text_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'case_sensitive', "text_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # not_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_sensitive', "text_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_sensitive', "text_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_sensitive', "text_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=string" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_insensitive', "text_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=string" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 def case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'case_insensitive', "text_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'case_insensitive', "text_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_insensitive', "text_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_insensitive', "text_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_insensitive', "text_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_sensitive', "text_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 # def similar_to(): # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'similar_to', # "text_value____str": 'string%'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'similar_to', # "text_value____str": 'test%'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # # not_case_insensitive # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'not_similar_to', # "text_value____str": 'string%'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'not_similar_to', # "text_value____str": 'test%'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'similar_to'} # query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str%&text_value____str=_es%" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'similar_to'} # query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str%&text_value____str=_es%" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # match_regex_with_case_sensitive() # match_regex_with_case_insensitive() case_sensitive() case_insensitive() # similar_to() # test create a more than one data of float4/text/varchar type, and get many def test_create_a_more_than_one_data_and_get_many_2(): float_one = 5.5 float_two = 10.7 # float 4 <= will round down to the odd floating even # data = 0.4 # <= 0.4 # result = [] # data = 0.4 # <= 0.5 # result = [0.4] num_one_sample_data = create_example_data(5, float4_value=float_one) num_two_sample_data = create_example_data(5, float4_value=float_two) primary_key_list = [i[primary_key_name] for i in num_one_sample_data] + \ [i[primary_key_name] for i in num_two_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) def greater_than_or_equal_to_Less_than_or_equal_to(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "float4_value____from_____comparison_operator": 'Greater_than_or_equal_to', "float4_value____to_____comparison_operator": 'Less_than_or_equal_to', "float4_value____from": float_one, "float4_value____to": float_two} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 # data = 10.7 # < 10.7 # still got 10.7 but if data is 10.6 def less_than_or_equal_to_less_than(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "float4_value____from_____comparison_operator": 'Greater_than', "float4_value____to_____comparison_operator": 'Less_than', "float4_value____from": float_one, "float4_value____to": float_two+0.1} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 greater_than_or_equal_to_Less_than_or_equal_to() less_than_or_equal_to_less_than() # float 4 < will round down to the odd floating odd # data = 0.3 # <= 0.4 # result = [] # data = 0.4 # <= 0.5 # result = [0.4] float_one = 5.5 float_two = 10.6 num_one_sample_data = create_example_data(5, float8_value=float_one) num_two_sample_data = create_example_data(5, float8_value=float_two) primary_key_list = [i[primary_key_name] for i in num_one_sample_data] + \ [i[primary_key_name] for i in num_two_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) def greater_than_or_equal_to_Less_than_or_equal_to(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "float8_value____from_____comparison_operator": 'Greater_than_or_equal_to', "float8_value____to_____comparison_operator": 'Less_than_or_equal_to', "float8_value____from": float_one, "float8_value____to": float_two} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 def less_than_or_equal_to_less_than(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "float8_value____from_____comparison_operator": 'Greater_than', "float8_value____to_____comparison_operator": 'Less_than', "float8_value____from": float_one, "float8_value____to": float_two+0.1} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 greater_than_or_equal_to_Less_than_or_equal_to() less_than_or_equal_to_less_than() def test_get_many_with_ordering_unknown_column(): try: response = client.get(f'/test_get_many?order_by_columns=testestset') except UnknownColumn as e: assert str(e) == "column testestset is not exited" return assert False def test_get_many_with_ordering_with_default_order(): response = client.get(f'/test_get_many?order_by_columns=primary_key&limit=10&offset=0') a = response.json() init = 1 for i in a: assert i['primary_key'] == init init += 1 def test_get_many_with_ordering_with_ASC(): response = client.get(f'/test_get_many?order_by_columns=primary_key:ASC&limit=10&offset=0') a = response.json() init = 1 for i in a: assert i['primary_key'] == init init += 1 def test_get_many_with_ordering_with_DESC(): response = client.get(f'/test_get_many?order_by_columns=primary_key:DESC&limit=10&offset=10') a = response.json() init = a[0]['primary_key'] for i in a: assert i['primary_key'] == init init -= 1 def test_get_many_with_unknown_order_tyoe(): try: response = client.get(f'/test_get_many?order_by_columns=primary_key:DESCSS&limit=10&offset=0') except UnknownOrderType as e: assert str(e) == 'Unknown order type DESCSS, only accept DESC or ASC' return assert False def test_get_many_with_ordering_with_empty_input_list(): try: response = client.get(f'/test_get_many?order_by_columns=') except Exception as e: assert False assert True ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_async_test/test_get_one_api.py ================================================ import json from starlette.testclient import TestClient from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_memory_sqlalchemy.api_test import app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_one = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_get_data = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", tags=["test"], async_mode=True ) [app.include_router(i) for i in [test_get_data, test_create_one]] client = TestClient(app) # create a sample data headers = { 'accept': '*/*', 'Content-Type': 'application/json', } data = '{ "bool_value": true, "char_value": "string", "date_value": "2021-07-26", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-26T02:17:46.846Z", "timestamptz_value": "2021-07-26T02:17:46.846Z", "timetz_value": "18:18:18+00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }' response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_data = response.json() dict_data = json.loads(data) sample_primary_key = response_data['primary_key'] ''' { "primary_key": 1013, "interval_value": 0, <- querying not supported "json_value": {},<- querying not supported "jsonb_value": {},<- querying not supported "array_value": [ 0 ], "array_str__value": [ "string" ] } ''' # try find the data by primary key def test_get_by_primary_key_without_any_query_param(): response = client.get(f'/test/{sample_primary_key}', headers=headers) assert response.status_code == 200 assert response.json()['primary_key'] == sample_primary_key # "bool_value": true # try find the data by primary key but false by bool def test_get_by_primary_key_with_false_bool_query_param(): response = client.get(f'/test/{sample_primary_key}?bool_value____list=false', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?bool_value____list=true', headers=headers) assert response.status_code == 200 # "char_value": "string ", # try find the data by primary key but false by char def test_get_by_primary_key_with_false_char_query_param(): response = client.get(f'/test/{sample_primary_key}?char_value____list=string1&char_value____list=string2', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?char_value____list=string&char_value____list=string1&', headers=headers) assert response.status_code == 200 # Like operator response = client.get( f'/test/{sample_primary_key}?char_value____str=string1&char_value____str=%tri%&char_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=string1&char_value____str=%tsri%&char_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 404 # Ilike operator response = client.get( f'/test/{sample_primary_key}?char_value____str=string1&char_value____str=%tRi%&char_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=string1&char_value____str=%tsri%&char_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 404 # not like operator response = client.get( f'/test/{sample_primary_key}?char_value____str=string2&char_value____str=%strg%&char_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=string%&char_value____str=%strin%&char_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 404 # not ilike operator response = client.get( f'/test/{sample_primary_key}?char_value____str=String2&char_value____str=%Strg%&char_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=STRING%&char_value____str=%TRI%&char_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 404 # match regex with case sensitive operator # response = client.get( # f'/test/{sample_primary_key}?char_value____str=stri.*&varchar_value____stg=str&char_value____str_____matching_pattern=match_regex_with_case_sensitive', # headers=headers) # assert response.status_code == 200 # response = client.get( # f'/test/{sample_primary_key}?char_value____str=stg.*&char_value____str=stg&char_value____str_____matching_pattern=match_regex_with_case_sensitive', # headers=headers) # assert response.status_code == 404 # match regex with case insensitive operator # response = client.get( # f'/test/{sample_primary_key}?char_value____str=strI.*&char_value____str=STG&char_value____str_____matching_pattern=match_regex_with_case_insensitive', # headers=headers) # assert response.status_code == 200 # response = client.get( # f'/test/{sample_primary_key}?char_value____str=stG.*&char_value____str=STG&char_value____str_____matching_pattern=match_regex_with_case_insensitive', # headers=headers) # assert response.status_code == 404 # does_not_match_regex_with_case_insensitive # response = client.get( # f'/test/{sample_primary_key}?char_value____str=strI.*&char_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', # headers=headers) # assert response.status_code == 404 # response = client.get( # f'/test/{sample_primary_key}?char_value____str=stG.*&char_value____str=STG&char_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', # headers=headers) # assert response.status_code == 200 # dose not match regex with case sensitive operator # response = client.get( # f'/test/{sample_primary_key}?char_value____str=stri.*&varchar_value____stg=str&char_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', # headers=headers) # assert response.status_code == 404 # response = client.get( # f'/test/{sample_primary_key}?char_value____str=stg.*&char_value____str=stg&char_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', # headers=headers) # assert response.status_code == 200 # similar_to # response = client.get( # f'/test/{sample_primary_key}?char_value____str=string&char_value____str=%(r|z)%&char_value____str_____matching_pattern=similar_to', # headers=headers) # assert response.status_code == 200 # response = client.get( # f'/test/{sample_primary_key}?char_value____str=str&char_value____str=(r|z)%&char_value____str_____matching_pattern=similar_to', # headers=headers) # assert response.status_code == 404 # not_similar_to # response = client.get( # f'/test/{sample_primary_key}?char_value____str=string%&char_value____str=%(r|z)%&char_value____str_____matching_pattern=not_similar_to', # headers=headers) # assert response.status_code == 404 # response = client.get( # f'/test/{sample_primary_key}?char_value____str=str&char_value____str=(r|z)%&char_value____str_____matching_pattern=not_similar_to', # headers=headers) # assert response.status_code == 200 # "float4_value": 0, # try find the data by primary key but false by float4 def test_get_by_primary_key_with_false_float4_query_param(): # from response = client.get(f'/test/{sample_primary_key}?float4_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?float4_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??float4_value____from=-2&float4_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?float4_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?float4_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?float4_value____from=0&float4_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?float4_value____from=0&float4_value____to=0&float4_value____from_____comparison_operator=Greater_than_or_equal_to&float4_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?float4_value____from=-1&float4_value____to=2&float4_value____from_____comparison_operator=Greater_than&float4_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?float4_value____from=1&float4_value____to=2&float4_value____from_____comparison_operator=Greater_than&float4_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?float4_value____from=1&float4_value____to=2&float4_value____from_____comparison_operator=Greater_than_or_equal_to&float4_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # "float8_value": 0, # try find the data by primary key but false by float8 def test_get_by_primary_key_with_false_float8_query_param(): # from response = client.get(f'/test/{sample_primary_key}?float8_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?float8_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??float8_value____from=-2&float8_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?float8_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?float8_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?float8_value____from=0&float8_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?float8_value____from=0&float8_value____to=0&float8_value____from_____comparison_operator=Greater_than_or_equal_to&float8_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?float8_value____from=-1&float8_value____to=2&float8_value____from_____comparison_operator=Greater_than&float8_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?float8_value____from=1&float8_value____to=2&float8_value____from_____comparison_operator=Greater_than&float8_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?float8_value____from=1&float8_value____to=2&float8_value____from_____comparison_operator=Greater_than_or_equal_to&float8_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by int2 # int2 0 def test_get_by_primary_key_with_false_int2_query_param(): # from response = client.get(f'/test/{sample_primary_key}?int2_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?int2_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??int2_value____from=-2&int2_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?int2_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?int2_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?int2_value____from=0&int2_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int2_value____from=0&int2_value____to=0&int2_value____from_____comparison_operator=Greater_than_or_equal_to&int2_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int2_value____from=-1&int2_value____to=2&int2_value____from_____comparison_operator=Greater_than&int2_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int2_value____from=1&int2_value____to=2&int2_value____from_____comparison_operator=Greater_than&int2_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int2_value____from=1&int2_value____to=2&int2_value____from_____comparison_operator=Greater_than_or_equal_to&int2_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by int4 # int 4 0 def test_get_by_primary_key_with_false_int4_query_param(): # from response = client.get(f'/test/{sample_primary_key}?int4_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?int4_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??int4_value____from=-2&int4_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?int4_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?int4_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?int4_value____from=0&int4_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int4_value____from=0&int4_value____to=0&int4_value____from_____comparison_operator=Greater_than_or_equal_to&int4_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int4_value____from=-1&int4_value____to=2&int4_value____from_____comparison_operator=Greater_than&int4_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int4_value____from=1&int4_value____to=2&int4_value____from_____comparison_operator=Greater_than&int4_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int4_value____from=1&int4_value____to=2&int4_value____from_____comparison_operator=Greater_than_or_equal_to&int4_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by int8 # int 8 0 def test_get_by_primary_key_with_false_int8_query_param(): # from response = client.get(f'/test/{sample_primary_key}?int8_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?int8_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??int8_value____from=-2&int8_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?int8_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?int8_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?int8_value____from=0&int8_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int8_value____from=0&int8_value____to=0&int8_value____from_____comparison_operator=Greater_than_or_equal_to&int8_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int8_value____from=-1&int8_value____to=2&int8_value____from_____comparison_operator=Greater_than&int8_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int8_value____from=1&int8_value____to=2&int8_value____from_____comparison_operator=Greater_than&int8_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int8_value____from=1&int8_value____to=2&int8_value____from_____comparison_operator=Greater_than_or_equal_to&int8_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by numeric # numeric 0 def test_get_by_primary_key_with_false_numeric_query_param(): # from response = client.get(f'/test/{sample_primary_key}?numeric_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?numeric_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??numeric_value____from=-2&numeric_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?numeric_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?numeric_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?numeric_value____from=0&numeric_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?numeric_value____from=0&numeric_value____to=0&numeric_value____from_____comparison_operator=Greater_than_or_equal_to&numeric_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?numeric_value____from=-1&numeric_value____to=2&numeric_value____from_____comparison_operator=Greater_than&numeric_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?numeric_value____from=1&numeric_value____to=2&numeric_value____from_____comparison_operator=Greater_than&numeric_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?numeric_value____from=1&numeric_value____to=2&numeric_value____from_____comparison_operator=Greater_than_or_equal_to&numeric_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by text # "text_value": "string", def test_get_by_primary_key_with_false_text_query_param(): response = client.get(f'/test/{sample_primary_key}?text_value____list=string1&text_value____list=string2', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?text_value____list=string&text_value____list=string1&', headers=headers) assert response.status_code == 200 # Like operator response = client.get(f'/test/{sample_primary_key}?text_value____str=string1&text_value____str=%tri%&text_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?text_value____str=string1&text_value____str=%tsri%&text_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 404 # Ilike operator response = client.get(f'/test/{sample_primary_key}?text_value____str=string1&text_value____str=%tRi%&text_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?text_value____str=string1&text_value____str=%tsri%&text_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 404 # not like operator response = client.get(f'/test/{sample_primary_key}?text_value____str=string2&text_value____str=%strg%&text_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?text_value____str=string&text_value____str=%strin%&text_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 404 # not ilike operator response = client.get(f'/test/{sample_primary_key}?text_value____str=String2&text_value____str=%Strg%&text_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?text_value____str=STRING&text_value____str=%TRI%&text_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 404 # match regex with case sensitive operator # response = client.get(f'/test/{sample_primary_key}?text_value____str=stri.*&varchar_value____stg=str&text_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) # assert response.status_code == 200 # response = client.get(f'/test/{sample_primary_key}?text_value____str=stg.*&text_value____str=stg&text_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) # assert response.status_code == 404 # match regex with case insensitive operator # response = client.get(f'/test/{sample_primary_key}?text_value____str=strI.*&text_value____str=STG&text_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) # assert response.status_code == 200 # response = client.get(f'/test/{sample_primary_key}?text_value____str=stG.*&text_value____str=STG&text_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) # assert response.status_code == 404 # does_not_match_regex_with_case_insensitive # response = client.get(f'/test/{sample_primary_key}?text_value____str=strI.*&text_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) # assert response.status_code == 404 # response = client.get(f'/test/{sample_primary_key}?text_value____str=stG.*&text_value____str=STG&text_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) # assert response.status_code == 200 # dose not match regex with case sensitive operator # response = client.get(f'/test/{sample_primary_key}?text_value____str=stri.*&varchar_value____stg=str&text_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) # assert response.status_code == 404 # response = client.get(f'/test/{sample_primary_key}?text_value____str=stg.*&text_value____str=stg&text_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) # assert response.status_code == 200 # similar_to # response = client.get(f'/test/{sample_primary_key}?text_value____str=string&text_value____str=%(r|z)%&text_value____str_____matching_pattern=similar_to', headers=headers) # assert response.status_code == 200 # response = client.get(f'/test/{sample_primary_key}?text_value____str=str&text_value____str=(r|z)%&text_value____str_____matching_pattern=similar_to', headers=headers) # assert response.status_code == 404 # not_similar_to # response = client.get(f'/test/{sample_primary_key}?text_value____str=string&text_value____str=%(r|z)%&text_value____str_____matching_pattern=not_similar_to', headers=headers) # assert response.status_code == 404 # response = client.get(f'/test/{sample_primary_key}?text_value____str=str&text_value____str=(r|z)%&text_value____str_____matching_pattern=not_similar_to', headers=headers) # assert response.status_code == 200 # try find the data by primary key but false by uuid # def test_get_by_primary_key_with_false_uuid_query_param(): # # In operator # response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa6&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9', headers=headers) # assert response.status_code == 200 # response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afb6', headers=headers) # assert response.status_code == 404 # # not In operator # response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa6&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list_____comparison_operator=Not_in', headers=headers) # assert response.status_code == 404 # response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afb6&uuid_value____list_____comparison_operator=Not_in', headers=headers) # assert response.status_code == 200 # # Equal operator # response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa6&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list_____comparison_operator=Equal', headers=headers) # assert response.status_code == 200 # response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afb6&uuid_value____list_____comparison_operator=Equal', headers=headers) # assert response.status_code == 404 # # not Equal operator # response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa6&uuid_value____list_____comparison_operator=Not_equal', headers=headers) # assert response.status_code == 404 # response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afb6&uuid_value____list_____comparison_operator=Not_equal', headers=headers) # assert response.status_code == 200 # try find the data by primary key but false by varchar def test_get_by_primary_key_with_false_varchar_query_param(): response = client.get(f'/test/{sample_primary_key}?varchar_value____list=string1&varchar_value____list=string2', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?varchar_value____list=string&varchar_value____list=string1&', headers=headers) assert response.status_code == 200 # Like operator response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string1&varchar_value____str=%tri%&varchar_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string1&varchar_value____str=%tsri%&varchar_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 404 # Ilike operator response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string1&varchar_value____str=%tRi%&varchar_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string1&varchar_value____str=%tsri%&varchar_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 404 # not like operator response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string2&varchar_value____str=%strg%&varchar_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string&varchar_value____str=%strin%&varchar_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 404 # not ilike operator response = client.get(f'/test/{sample_primary_key}?varchar_value____str=String2&varchar_value____str=%Strg%&varchar_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=STRING&varchar_value____str=%TRI%&varchar_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 404 # match regex with case sensitive operator # response = client.get(f'/test/{sample_primary_key}?varchar_value____str=stri.*&varchar_value____stg=str&varchar_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) # assert response.status_code == 200 # response = client.get(f'/test/{sample_primary_key}?varchar_value____str=stg.*&varchar_value____str=stg&varchar_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) # assert response.status_code == 404 # match regex with case insensitive operator # response = client.get(f'/test/{sample_primary_key}?varchar_value____str=strI.*&varchar_value____str=STG&varchar_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) # assert response.status_code == 200 # response = client.get(f'/test/{sample_primary_key}?varchar_value____str=stG.*&varchar_value____str=STG&varchar_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) # assert response.status_code == 404 # does_not_match_regex_with_case_insensitive # response = client.get(f'/test/{sample_primary_key}?varchar_value____str=strI.*&varchar_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) # assert response.status_code == 404 # response = client.get(f'/test/{sample_primary_key}?varchar_value____str=stG.*&varchar_value____str=STG&varchar_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) # assert response.status_code == 200 # dose not match regex with case sensitive operator # response = client.get(f'/test/{sample_primary_key}?varchar_value____str=stri.*&varchar_value____stg=str&varchar_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) # assert response.status_code == 404 # response = client.get(f'/test/{sample_primary_key}?varchar_value____str=stg.*&varchar_value____str=stg&varchar_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) # assert response.status_code == 200 # similar_to # response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string&varchar_value____str=%(r|z)%&varchar_value____str_____matching_pattern=similar_to', headers=headers) # assert response.status_code == 200 # response = client.get(f'/test/{sample_primary_key}?varchar_value____str=str&varchar_value____str=(r|z)%&varchar_value____str_____matching_pattern=similar_to', headers=headers) # assert response.status_code == 404 # not_similar_to # response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string&varchar_value____str=%(r|z)%&varchar_value____str_____matching_pattern=not_similar_to', headers=headers) # assert response.status_code == 404 # response = client.get(f'/test/{sample_primary_key}?varchar_value____str=str&varchar_value____str=(r|z)%&varchar_value____str_____matching_pattern=not_similar_to', headers=headers) # assert response.status_code == 200 # query by range of date field def test_get_by_primary_key_with_false_date_range_query_param(): # from response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-27', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?date_value____to=2021-07-24', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??date_value____from=2021-07-21&date_value____to=2021-07-24', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-24', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?date_value____to=2021-07-27', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-24&date_value____to=2021-07-27', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-26&date_value____to=2021-07-26&date_value____from_____comparison_operator=Greater_than_or_equal_to&date_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-25&date_value____to=2021-07-27&date_value____from_____comparison_operator=Greater_than&date_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-26&date_value____to=2021-07-26&date_value____from_____comparison_operator=Greater_than&date_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-27&date_value____to=2021-07-29&date_value____from_____comparison_operator=Greater_than_or_equal_to&date_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 def test_get_by_primary_key_with_false_time_range_query_param(): # from response = client.get(f'/test/{sample_primary_key}?time_value____from=19:18:18', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?time_value____to=17:18:18', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}?time_value____from=10:18:18&time_value____to=17:18:18', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?time_value____from=10:18:18', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?time_value____to=19:18:18', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?time_value____from=10:18:18&time_value____to=19:18:18', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?time_value____from=18:18:18&time_value____to=18:18:18&time_value____from_____comparison_operator=Greater_than_or_equal_to&time_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?time_value____from=18:18:17&time_value____to=18:18:19&time_value____from_____comparison_operator=Greater_than&time_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?time_value____from=18:18:18&time_value____to=18:18:18&time_value____from_____comparison_operator=Greater_than&time_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?time_value____from=19:18:18&time_value____to=19:19:18&time_value____from_____comparison_operator=Greater_than_or_equal_to&time_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 def test_get_by_primary_key_with_false_timestamp_range_query_param(): # "timestamp_value": "2021-07-26T02:17:46.846000", # from response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-27T02:17:46.846000', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?timestamp_value____to=2021-07-25T02:17:46.846000', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-20T02:17:46.846000×tamp_value____to=2021-07-25T02:17:46.846000', headers=headers) assert response.status_code == 404 # success from a = sample_primary_key response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-24T02:17:46.846000', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?timestamp_value____to=2021-07-28T02:17:46.846000', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-24T02:17:46.846000×tamp_value____to=2021-07-28T02:17:46.846000', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-26T02:17:46.846×tamp_value____to=2021-07-26T02:17:46.846Z×tampt_value____from_____comparison_operator=Greater_than_or_equal_to×tampt_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-26T02:17:46.746Z×tamp_value____to=2021-07-26T02:17:46.946Z×tampt_value____from_____comparison_operator=Greater_than×tampt_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-26T02:17:46.846Z×tamp_value____to=2021-07-26T02:17:46.946Z×tamp_value____from_____comparison_operator=Greater_than×tamp_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-26T02:17:46.856Z×tamp_value____to=2021-07-26T02:17:46.986Z×tamp_value____from_____comparison_operator=Greater_than_or_equal_to×tamp_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 def test_get_by_primary_key_with_false_timetz_range_query_param(): # from response = client.get(f'/test/{sample_primary_key}?timetz_value____from=19%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?timetz_value____to=17%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}?timetz_value____from=16%3A18%3A18%2B00%3A00&timetz_value____to=17%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?timetz_value____from=17%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?timetz_value____to=19%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?timetz_value____from=16%3A18%3A18%2B00%3A00&timetz_value____to=19%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timetz_value____from_____comparison_operator=Greater_than&timetz_value____to_____comparison_operator=Less_than&timetz_value____from=17%3A18%3A18%2B00&timetz_value____to=19%3A18%3A18%2B00', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timetz_value____from_____comparison_operator=Greater_than_or_equal_to&timetz_value____to_____comparison_operator=Less_than_or_equal_to&timetz_value____from=18%3A18%3A18%2B00&timetz_value____to=18%3A19%3A18%2B00', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timetz_value____from_____comparison_operator=Greater_than&timetz_value____to_____comparison_operator=Less_than&timetz_value____from=16%3A18%3A18%2B00&timetz_value____to=18%3A18%3A18%2B00', headers=headers) assert response.status_code == 404 # failure from - to with special operator response = client.get(f'/test/{sample_primary_key}?timetz_value____from_____comparison_operator=Greater_than_or_equal_to&timetz_value____to_____comparison_operator=Less_than_or_equal_to&timetz_value____from=16%3A18%3A18%2B00&timetz_value____to=17%3A19%3A18%2B00', headers=headers) assert response.status_code == 404 def test_get_by_primary_key_with_false_timestamptz_range_query_param(): # "timestamp_value": "2021-07-26T02:17:46.846000", # from response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-27T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?timestamptz_value____to=2021-07-25T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-27T02%3A17%3A46.846000%2B00%3A00×tamptz_value____to=2021-07-28T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-20T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?timestamptz_value____to=2021-07-29T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-20T02%3A17%3A46.846000%2B00%3A00×tamptz_value____to=2021-07-27T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-26T02%3A17%3A46.846Z×tamptz_value____to=2021-07-26T02%3A17%3A46.846Z×tamptz_value____from_____comparison_operator=Greater_than_or_equal_to×tamptz_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-26T02%3A17%3A46.800Z×tamptz_value____to=2021-07-26T02%3A17%3A46.946Z×tamptz_value____from_____comparison_operator=Greater_than×tamptz_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-26T02%3A17%3A46.846Z×tamptz_value____to=2021-07-26T02%3A17%3A46.900Z×tamptz_value____from_____comparison_operator=Greater_than×tamptz_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-26T02%3A17%3A46.847Z×tamptz_value____to=2021-07-26T02%3A17%3A46.946Z×tamptz_value____from_____comparison_operator=Greater_than_or_equal_to×tamptz_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_async_test/test_other_default_value.py ================================================ import json import os from copy import deepcopy from datetime import datetime, timezone, date, timedelta from http import HTTPStatus from urllib.parse import urlencode from fastapi import FastAPI from sqlalchemy import BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint from sqlalchemy.orm import declarative_base from starlette.testclient import TestClient from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata class UUIDTable(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_default_value_sync' __table_args__ = ( UniqueConstraint('primary_key', 'int4_value', 'float4_value'), ) primary_key = Column(Integer, primary_key=True, autoincrement=True) bool_value = Column(Boolean, nullable=False, default=False) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, default=datetime.now()) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, default=10) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, default=99) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) varchar_value = Column(String) route_1 = crud_router_builder(db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.FIND_MANY, CrudMethods.CREATE_MANY, CrudMethods.UPDATE_ONE, CrudMethods.UPDATE_MANY, CrudMethods.PATCH_MANY, CrudMethods.PATCH_ONE, CrudMethods.DELETE_MANY, CrudMethods.DELETE_ONE, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"], async_mode=True ) route_2 = crud_router_builder(db_model=UUIDTable, crud_methods=[ CrudMethods.CREATE_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_2", tags=["test"], async_mode=True ) route_3 = crud_router_builder(db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_3", tags=["test"], async_mode=True ) [app.include_router(i) for i in [route_1, route_2, route_3]] client = TestClient(app) def test_get_one_data_and_create_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() find_target = create_response['primary_key'] response = client.get(f'/test/{find_target}', headers=headers, data=data) assert response.status_code == 200 assert response.json() == create_response create_response.pop('primary_key') query_param = urlencode(create_response) response = client.get(f'/test/{find_target}?{query_param}', headers=headers, data=data) assert response.status_code == 200 def test_get_many_data_and_create_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = ''' [ { "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00","varchar_value": "string"}, { "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string"},{ "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string"} ] ''' data_dict = json.loads(data) response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_dict): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_update_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() created_primary_key = create_response['primary_key'] update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} query_param = urlencode(update_data) response = client.put(f'/test/{created_primary_key}?{query_param}', data=json.dumps(update_data)) update_data["bool_value"] = False response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_create_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [{"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test?{query_string}', data=json.dumps(update_data)) update_data["bool_value"] = False response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: assert k[i] == update_data[i] def test_patch_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) update_data = {"bool_value": False} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(params) update_data = {"char_value": "string_u "} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(params) update_data = {"date_value": "2022-07-24"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(params) update_data = {"char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) update_data['bool_value'] = False response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_patch_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [{"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value": True, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test?{query_string}', data=json.dumps(update_data)) update_data['bool_value'] = True response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_delete_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) response = client.delete(f'/test/{primary_key}?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_delete_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [{"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' response = client.delete(f'/test?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_post_redirect_get_data(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19.0 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_3', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() response_data['bool_value'] = False assert 'primary_key' in response_data # for k, v in response_data.items(): # if k in change: # if isinstance(v, str): # v = v.strip() # response_ = json.dumps(v).strip() # request_ = json.dumps(change[k]).strip() # assert request_ == response_ return response_data def test_create_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 10 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k, v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_async_test/test_other_set_description.py ================================================ import json import os from datetime import datetime, timezone, date, timedelta from http import HTTPStatus from urllib.parse import urlencode from fastapi import FastAPI from sqlalchemy import BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text, func from sqlalchemy.orm import declarative_base from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata class UUIDTable(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_default_value_sync' __table_args__ = ( UniqueConstraint('primary_key', 'int4_value', 'float4_value'), ) primary_key = Column(Integer, primary_key=True, autoincrement=True) bool_value = Column(Boolean, nullable=False, default=False) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, default=datetime.now()) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, default=10.10) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, default=99) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) varchar_value = Column(String) model_1 = sqlalchemy_to_pydantic(UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.FIND_MANY, CrudMethods.CREATE_MANY, CrudMethods.UPDATE_ONE, CrudMethods.UPDATE_MANY, CrudMethods.PATCH_MANY, CrudMethods.PATCH_ONE, CrudMethods.DELETE_MANY, CrudMethods.DELETE_ONE, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) route_1 = crud_router_builder(db_model=UUIDTable, crud_models=model_1, prefix="/test", tags=["test"], async_mode=True ) model_2 = sqlalchemy_to_pydantic(UUIDTable, crud_methods=[ CrudMethods.CREATE_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) route_2 = crud_router_builder(db_model=UUIDTable, crud_models=model_2, prefix="/test_2", tags=["test"], async_mode=True ) model_3 = sqlalchemy_to_pydantic(UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) route_3 = crud_router_builder(db_model=UUIDTable, crud_models=model_3, prefix="/test_3", tags=["test"], async_mode=True ) [app.include_router(i) for i in [route_1, route_2, route_3]] client = TestClient(app) def test_get_one_data_and_create_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() find_target = create_response['primary_key'] response = client.get(f'/test/{find_target}', headers=headers, data=data) assert response.status_code == 200 assert response.json() == create_response create_response.pop('primary_key') query_param = urlencode(create_response) response = client.get(f'/test/{find_target}?{query_param}', headers=headers, data=data) assert response.status_code == 200 def test_get_many_data_and_create_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '''[ { "char_value":"string ", "date_value":"2021-07-23", "float4_value":0, "float8_value":0, "int2_value":0, "int4_value":0, "int8_value":0, "numeric_value":0, "text_value":"string", "timestamp_value":"2021-07-23T02:38:24.963000", "timestamptz_value":"2021-07-23T02:38:24.963000+00:00", "varchar_value":"string" }, { "char_value":"string ", "date_value":"2021-07-23", "float4_value":0, "float8_value":0, "int2_value":0, "int4_value":0, "int8_value":0, "numeric_value":0, "text_value":"string", "timestamp_value":"2021-07-23T02:38:24.963000", "timestamptz_value":"2021-07-23T02:38:24.963000+00:00", "varchar_value":"string" }, { "char_value":"string ", "date_value":"2021-07-23", "float4_value":0, "float8_value":0, "int2_value":0, "int4_value":0, "int8_value":0, "numeric_value":0, "text_value":"string", "timestamp_value":"2021-07-23T02:38:24.963000", "timestamptz_value":"2021-07-23T02:38:24.963000+00:00", "varchar_value":"string" } ] ''' data_dict = json.loads(data) response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_dict): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_update_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() created_primary_key = create_response['primary_key'] update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} query_param = urlencode(update_data) response = client.put(f'/test/{created_primary_key}?{query_param}', data=json.dumps(update_data)) update_data["bool_value"] = False response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_update_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [{"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test?{query_string}', data=json.dumps(update_data)) update_data["bool_value"] = False response_data = response.json() assert len(response_data) == 3 def test_patch_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) update_data = {"bool_value": False} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(params) update_data = {"char_value": "string_u "} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(params) update_data = {"date_value": "2022-07-24"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(params) update_data = {"char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) update_data['bool_value'] = False response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_patch_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [{"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value": True, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test?{query_string}', data=json.dumps(update_data)) update_data['bool_value'] = True response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_delete_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) response = client.delete(f'/test/{primary_key}?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_delete_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [{"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' response = client.delete(f'/test?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_post_redirect_get_data(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19.0 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_3', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() response_data['bool_value'] = False assert 'primary_key' in response_data return response_data def test_upsert_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 10 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k, v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_async_test/test_other_single_unique.py ================================================ import json import os import uuid from copy import deepcopy from datetime import datetime, timezone, date, timedelta from http import HTTPStatus from urllib.parse import urlencode from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text, func from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine class UUIDTable(Base): __tablename__ = 'test_single_unique_table_model' id = Column(Integer, primary_key=True, autoincrement=True) bool_value = Column(Boolean, nullable=False,default = False) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, default=datetime.now()) float4_value = Column(Float, nullable=False,unique=True) float8_value = Column(Float(53), nullable=False, default=10.10) int2_value = Column(SmallInteger, nullable=True) int4_value = Column(Integer, nullable=True) int8_value = Column(BigInteger, default=99) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) varchar_value = Column(String) model_1 = sqlalchemy_to_pydantic(UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.FIND_MANY, CrudMethods.CREATE_MANY, CrudMethods.UPDATE_ONE, CrudMethods.UPDATE_MANY, CrudMethods.PATCH_MANY, CrudMethods.PATCH_ONE, CrudMethods.DELETE_MANY, CrudMethods.DELETE_ONE, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) route_1 = crud_router_builder(db_model=UUIDTable, crud_models=model_1, prefix="/test", tags=["test"], async_mode=True ) model_2 = sqlalchemy_to_pydantic(UUIDTable, crud_methods=[ CrudMethods.CREATE_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) route_2 = crud_router_builder(db_model=UUIDTable, crud_models=model_2, prefix="/test_2", tags=["test"], async_mode=True ) model_3 = sqlalchemy_to_pydantic(UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) route_3 = crud_router_builder(db_model=UUIDTable, crud_models=model_3, prefix="/test_3", tags=["test"], async_mode=True ) [app.include_router(i) for i in [route_1, route_2, route_3]] client = TestClient(app) def test_get_one_data_and_create_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0.443}' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() find_target = create_response['id'] response = client.get(f'/test/{find_target}', headers=headers, data=data) assert response.status_code == 200 assert response.json() == create_response create_response.pop('id') query_param = urlencode(create_response) response = client.get(f'/test/{find_target}?{query_param}', headers=headers, data=data) assert response.status_code == 200 def test_get_many_data_and_create_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '''[ { "bool_value":true, "char_value":"string ", "date_value":"2021-07-23", "float4_value":0.12, "float8_value":0, "int2_value":0, "int4_value":0, "int8_value":0, "numeric_value":0, "text_value":"string", "timestamp_value":"2021-07-23T02:38:24.963000", "timestamptz_value":"2021-07-23T02:38:24.963000+00:00", "varchar_value":"string" }, { "bool_value":true, "char_value":"string ", "date_value":"2021-07-23", "float4_value":1.2, "float8_value":0, "int2_value":0, "int4_value":0, "int8_value":0, "numeric_value":0, "text_value":"string", "timestamp_value":"2021-07-23T02:38:24.963000", "timestamptz_value":"2021-07-23T02:38:24.963000+00:00", "varchar_value":"string" }, { "bool_value":true, "char_value":"string ", "date_value":"2021-07-23", "float4_value":9.3, "float8_value":0, "int2_value":0, "int4_value":0, "int8_value":0, "numeric_value":0, "text_value":"string", "timestamp_value":"2021-07-23T02:38:24.963000", "timestamptz_value":"2021-07-23T02:38:24.963000+00:00", "varchar_value":"string" } ] ''' data_dict = json.loads(data) response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_dict): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_update_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0.98}' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() created_primary_key = create_response['id'] update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 12.7, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} query_param = urlencode(update_data) response = client.put(f'/test/{created_primary_key}?{query_param}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_update_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 3.5, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 3.6, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 3.7, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['id'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 200, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params)+f'&id____list={primary_key_list[0]}&id____list={primary_key_list[1]}&id____list={primary_key_list[2]}&float4_value____list=3.5&float4_value____list=3.6&float4_value____list=3.7' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.58, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test?{query_string}', data=json.dumps(update_data)) # FIXME: update the unique column will conflict, it may not a issue, because it should input all columns, you can use the patch assert response.status_code == 409 # response_data = response.json() # assert len(response_data) == 3 # for k in response_data: # for i in update_data: # assert k[i] == update_data[i] def test_patch_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 5.78, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['id'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 500, "float4_value____list": 5.78, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) update_data = {"bool_value": False} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(params) update_data = {"char_value": "string_u "} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(params) update_data = {"date_value": "2022-07-24"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(params) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 1.70, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_patch_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.91, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.92, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.93, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['id'] for i in insert_response_data] params = { "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 500, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&id____list={primary_key_list[0]}&id____list={primary_key_list[1]}&id____list={primary_key_list[2]}&float4_value____list=0.91&float4_value____list=0.92&float4_value____list=0.93' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00","varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_delete_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 2.54, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['id'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 500, "float4_value____list": 2.54, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) response = client.delete(f'/test/{primary_key}?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_delete_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.875, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.876, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.877, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['id'] for i in insert_response_data] params = { "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 500, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&id____list={primary_key_list[0]}&id____list={primary_key_list[1]}&id____list={primary_key_list[2]}&float4_value____list=0.875&float4_value____list=0.876&&float4_value____list=0.877' response = client.delete(f'/test?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_post_redirect_get_data(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} bool_value_change = False char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19.0 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 55.7 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_3', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() assert 'id' in response_data return response_data def test_upsert_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 12.784}' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k,v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_async_test/test_patch_many_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_memory_sqlalchemy.api_test import app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_one = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_one", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_many = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_post_and_redirect_get = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_get_data = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.PATCH_MANY ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_patch_data = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_patch_many", tags=["test"], async_mode=True ) [app.include_router(i) for i in [test_post_and_redirect_get, test_patch_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def test_create_many_and_patch_many(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ { "bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18" , "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list":True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = { "bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [ 1,2,3,4,5 ], "time_value": "18:19:18" , "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test_patch_many?{query_string}', data= json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_async_test/test_patch_one_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_memory_sqlalchemy.api_test import app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_one = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_one", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_many = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_post_and_redirect_get = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_get_data = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.PATCH_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_update_data = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_patch_one", tags=["test"], async_mode=True ) [app.include_router(i) for i in [test_post_and_redirect_get, test_update_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def test_create_one_and_patch_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key ,= [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False} response = client.patch(f'/test_patch_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(OrderedDict(**params)) update_data = { "char_value": "string_u "} response = client.patch(f'/test_patch_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(OrderedDict(**params)) update_data = {"date_value": "2022-07-24"} # update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, # "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, # "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, # "text_value": "string_update", # "timestamp_value": "2022-07-24T02:54:53.285000", # "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", # "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", # "array_value": [1, 2, 3, 4, 5], # "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test_patch_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test_patch_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_async_test/test_post_redirect_get_api.py ================================================ import json import uuid from datetime import date, timedelta, datetime, timezone from http import HTTPStatus from starlette.testclient import TestClient from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_memory_sqlalchemy.api_test import app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_post_and_redirect_get = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_get_data = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_post_and_redirect_get_without_get = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get_without_get", tags=["test"], async_mode=True ) [app.include_router(i) for i in [test_post_and_redirect_get, test_get_data, test_post_and_redirect_get_without_get]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields # Post Redirect Get API Test def test_create_one_but_no_follow_redirect(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } data = '{ "bool_value": true, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }' response = client.post('/test_post_direct_get', headers=headers, data=data, allow_redirects=False) assert response.status_code == HTTPStatus.SEE_OTHER def test_create_one_with_redirect(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} bool_value_change = False char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19.0 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' uuid_value_change = str(uuid.uuid4()) varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['uuid_value'] = uuid_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_post_direct_get', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() assert primary_key_name in response_data return response_data def test_create_but_conflict(): data = test_create_one_with_redirect() headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.post('/test_post_direct_get', headers=headers, data=json.dumps(data), allow_redirects=True) assert response.status_code == HTTPStatus.CONFLICT def test_create_but_not_found_get_api(): change = {} bool_value_change = False char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' uuid_value_change = str(uuid.uuid4()) varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['uuid_value'] = uuid_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data = json.dumps(change) headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.post('/test_post_direct_get_without_get', headers=headers, data=data, allow_redirects=True) assert response.status_code == HTTPStatus.NOT_FOUND ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_async_test/test_put_many_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_memory_sqlalchemy.api_test import app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_one = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_one", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_many = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_post_and_redirect_get = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_get_data = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPDATE_MANY ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_update_data = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_update_many", tags=["test"], async_mode=True ) [app.include_router(i) for i in [test_post_and_redirect_get, test_update_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def test_create_many_and_update_many(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ { "bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18" , "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list":True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = { "bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18" , "timetz_value": "18:19:18+00:00"} response = client.put(f'/test_update_many?{query_string}', data= json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_create_many_and_update_many_but_not_found(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ { "bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18" , "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list":True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '10:18:18', "time_value____to": '12:18:18', "time_value____list": '10:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "timez_value____from": '18:18:18+00:00', "timez_value____to": '18:18:18+00:00', "timez_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = { "bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18" , "timetz_value": "18:19:18+00:00"} response = client.put(f'/test_update_many?{query_string}', data= json.dumps(update_data)) # response_data = response.json() # assert len(response_data) == 3 # for k in response_data: # for i in update_data: # print(i) # print(k[i]) # assert k[i] == update_data[i] assert response.status_code == 204 ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_async_test/test_put_one_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_memory_sqlalchemy.api_test import app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_one = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_one", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_many = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_post_and_redirect_get = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_get_data = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", tags=["test"], async_mode=True ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPDATE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_update_data = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_update_one", tags=["test"], async_mode=True ) [app.include_router(i) for i in [test_post_and_redirect_get, test_update_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def test_create_one_and_update_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key ,= [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test_update_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_create_one_and_update_one_but_not_found(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data =[ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key ,= [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '10:18:18', "time_value____to": '12:18:18', "time_value____list": '10:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_valuez____from": '18:18:18+00:00', "time_valuez____to": '18:18:18+00:00', "time_valuez____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test_update_one/{primary_key}?{query_string}', data=json.dumps(update_data)) # response_data = response.json() response.status_code = 404 # assert response_data # for i in update_data: # assert response_data[i] == update_data[i] ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/__init__.py ================================================ import os from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata class UntitledTable256(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_build_myself_memory' __table_args__ = ( UniqueConstraint('primary_key', 'int4_value', 'float4_value'), ) primary_key = Column(Integer, primary_key=True, autoincrement=True) bool_value = Column(Boolean, nullable=False, default=False) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10,collation='NOCASE')) date_value = Column(Date) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, default=10.10) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, default=99) # interval_value = Column(INTERVAL) # json_value = Column(JSON) # jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) # uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) # xml_value = Column(NullType) # array_value = Column(ARRAY(Integer())) # array_str__value = Column(ARRAY(String())) # box_valaue = Column(NullType) ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/foreign_tree/__init__.py ================================================ ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/foreign_tree/test_relationship_m2m.py ================================================ from fastapi import FastAPI from sqlalchemy import Column, Integer, \ ForeignKey, Table, CHAR from sqlalchemy.orm import declarative_base, sessionmaker, relationship from src.fastapi_quickcrud.misc.type import SqlType from src.fastapi_quickcrud.crud_router import crud_router_builder app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine from sqlalchemy.pool import StaticPool engine = create_engine('sqlite://', echo=True, connect_args={"check_same_thread": False}, pool_recycle=7200, poolclass=StaticPool) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() association_table = Table('test_association', Base.metadata, Column('left_id', ForeignKey('test_left.id')), Column('right_id', ForeignKey('test_right.id')) ) association_table_second = Table('test_association_second', Base.metadata, Column('left_id_second', ForeignKey('test_left.id')), Column('right_id_second', ForeignKey('test_right_second.id')) ) class Child(Base): __tablename__ = 'test_right' id = Column(Integer, primary_key=True) child = Column(CHAR(10)) parent = relationship("Parent", secondary=association_table) class Parent(Base): __tablename__ = 'test_left' id = Column(Integer, primary_key=True) parent = Column(CHAR(10)) children = relationship("Child", secondary=association_table) children_second = relationship("ChildSecond", secondary=association_table_second) class ChildSecond(Base): __tablename__ = 'test_right_second' id = Column(Integer, primary_key=True) child_second = Column(CHAR(10)) children_second = relationship("Parent", secondary=association_table_second) crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child", tags=["child"], sql_type=SqlType.sqlite, foreign_include=[Parent], ) crud_route_association_table_second = crud_router_builder(db_session=get_transaction_session, db_model=association_table_second, prefix="/association_table_second", tags=["association_table_second"], sql_type=SqlType.sqlite, ) crud_route_association_table_second = crud_router_builder(db_session=get_transaction_session, db_model=association_table_second, prefix="/association_table_second", tags=["association_table_second"], sql_type=SqlType.sqlite, ) crud_route_child_second = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child_second", tags=["child_second"], sql_type=SqlType.sqlite, ) crud_route_parent = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"], foreign_include=[Child, ], sql_type=SqlType.sqlite, ) crud_route_parent2 = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"], foreign_include=[ChildSecond], sql_type=SqlType.sqlite, ) crud_route_association = crud_router_builder(db_session=get_transaction_session, db_model=association_table, prefix="/association", tags=["association"], sql_type=SqlType.sqlite, ) from starlette.testclient import TestClient [app.include_router(i) for i in [crud_route_association_table_second, crud_route_child_second, crud_route_parent, crud_route_child, crud_route_parent2, crud_route_association]] client = TestClient(app) def test_get_one_1(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } test_api_1 = "/parent/0/test_right/0?child____str_____matching_pattern=case_sensitive&child____list_____comparison_operator=In" test_api_2 = "/parent/1/test_right/1?child____str_____matching_pattern=case_sensitive&child____list_____comparison_operator=In" test_api_3 = "/parent/1/test_right/1?child____str_____matching_pattern=case_sensitive&child____list_____comparison_operator=In&join_foreign_table=test_left" test_api_4 = "parent/1/test_right/1?child____str_____matching_pattern=case_sensitive&child____str=child1&child____list_____comparison_operator=In&child____list=child1" test_api_5 = "/parent/1/test_right/1?child____str_____matching_pattern=case_sensitive&child____str=%25child%25&child____list_____comparison_operator=In" test_api_6 = "/parent/1/test_right/1?child____str_____matching_pattern=case_sensitive&child____str=%25child%25&child____list_____comparison_operator=Equal&child____list=child1" test_api_7 = "/parent/1/test_right/1?child____str_____matching_pattern=case_sensitive&child____str=%25child%25&child____list_____comparison_operator=In&child____list=child1" test_api_8 = "/parent/1/test_right/1?child____str_____matching_pattern=case_sensitive&child____str=%25child%25&child____list_____comparison_operator=In&child____list=child1&join_foreign_table=test_left" test_api_9 = "parent/1/test_right/1?child____str_____matching_pattern=case_sensitive&child____str=%25child%25&child____list_____comparison_operator=Not_in&child____list=child1" test_api_10 = "/parent/1/test_right/1?child____str_____matching_pattern=case_sensitive&child____str=%25child%25&child____list_____comparison_operator=Not_equal&child____list=child1" test_api_11 = "/parent/1/test_right/1?child____str_____matching_pattern=not_case_insensitive&child____str=child1&child____list_____comparison_operator=In" response = client.get(test_api_1, headers=headers) assert response.status_code == 404 response = client.get(test_api_2, headers=headers) assert response.status_code == 200 assert response.json() == {'child': 'child1', 'id': 1} response = client.get(test_api_3, headers=headers) assert response.status_code == 200 assert response.json() == {'child': 'child1', 'id': 1, 'test_left_foreign': [{'id': 1, 'parent': 'parent1'}]} response = client.get(test_api_4, headers=headers) assert response.status_code == 200 assert response.json() == {'child': 'child1', 'id': 1} response = client.get(test_api_5, headers=headers) assert response.status_code == 200 assert response.json() == {'child': 'child1', 'id': 1} response = client.get(test_api_6, headers=headers) assert response.status_code == 200 assert response.json() == {'child': 'child1', 'id': 1} response = client.get(test_api_7, headers=headers) assert response.status_code == 200 assert response.json() == {'child': 'child1', 'id': 1} response = client.get(test_api_8, headers=headers) assert response.status_code == 200 assert response.json() == {'child': 'child1', 'id': 1, 'test_left_foreign': [{'id': 1, 'parent': 'parent1'}]} response = client.get(test_api_9, headers=headers) assert response.status_code == 404 response = client.get(test_api_10, headers=headers) assert response.status_code == 404 response = client.get(test_api_11, headers=headers) assert response.status_code == 404 def test_get_one_2(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } test_api_1 = "/parent/0/test_right_second/0?child_second____str_____matching_pattern=case_sensitive&child_second____list_____comparison_operator=In" test_api_2 = "/parent/1/test_right_second/1" test_api_3 = "/parent/1/test_right_second/1?child_second____str_____matching_pattern=case_sensitive&child_second____list_____comparison_operator=In&join_foreign_table=test_left" test_api_4 = "parent/1/test_right_second/1?child_second____str_____matching_pattern=case_sensitive&child_second____str=child_second1&child_second____list_____comparison_operator=In&child_second____list=child_second1" test_api_5 = "/parent/1/test_right_second/1?child_second____str_____matching_pattern=case_sensitive&child_second____str=%25child_second%25&child_second____list_____comparison_operator=In" test_api_6 = "/parent/1/test_right_second/1?child_second____str_____matching_pattern=case_sensitive&child_second____str=%25child_second%25&child_second____list_____comparison_operator=Equal&child_second____list=child_second1" test_api_7 = "/parent/1/test_right_second/1?child_second____str_____matching_pattern=case_sensitive&child_second____str=%25child_second%25&child_second____list_____comparison_operator=In&child_second____list=child_second1" test_api_8 = "/parent/1/test_right_second/1?child_second____str_____matching_pattern=case_sensitive&child_second____str=%25child_second%25&child_second____list_____comparison_operator=In&child_second____list=child_second1&join_foreign_table=test_left" test_api_9 = "parent/1/test_right_second/1?child_second____str_____matching_pattern=case_sensitive&child_second____str=%25child_second%25&child_second____list_____comparison_operator=Not_in&child_second____list=child_second1" test_api_10 = "/parent/1/test_right_second/1?child_second____str_____matching_pattern=case_sensitive&child_second____str=%25child_second%25&child_second____list_____comparison_operator=Not_equal&child_second____list=child_second1" test_api_11 = "/parent/1/test_right_second/1?child_second____str_____matching_pattern=not_case_insensitive&child_second____str=child_second1&child_second____list_____comparison_operator=In" response = client.get(test_api_1, headers=headers) assert response.status_code == 404 response = client.get(test_api_2, headers=headers) assert response.status_code == 200 assert response.json() == {'child_second': 'child_second1', 'id': 1} response = client.get(test_api_3, headers=headers) assert response.status_code == 200 assert response.json() == {'child_second': 'child_second1', 'id': 1, 'test_left_foreign': [{'id': 1, 'parent': 'parent1'}]} response = client.get(test_api_4, headers=headers) assert response.status_code == 200 assert response.json() == {'child_second': 'child_second1', 'id': 1} response = client.get(test_api_5, headers=headers) assert response.status_code == 200 assert response.json() == {'child_second': 'child_second1', 'id': 1} response = client.get(test_api_6, headers=headers) assert response.status_code == 200 assert response.json() == {'child_second': 'child_second1', 'id': 1} response = client.get(test_api_7, headers=headers) assert response.status_code == 200 assert response.json() == {'child_second': 'child_second1', 'id': 1} response = client.get(test_api_8, headers=headers) assert response.status_code == 200 assert response.json() == {'child_second': 'child_second1', 'id': 1, 'test_left_foreign': [{'id': 1, 'parent': 'parent1'}]} response = client.get(test_api_9, headers=headers) assert response.status_code == 404 response = client.get(test_api_10, headers=headers) assert response.status_code == 404 response = client.get(test_api_11, headers=headers) assert response.status_code == 404 def test_get_many_1(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } test_api_1 = "/parent/0/test_right?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&child____str_____matching_pattern=case_sensitive&child____list_____comparison_operator=In" test_api_2 = "/parent/1/test_right?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&child____str_____matching_pattern=case_sensitive&child____list_____comparison_operator=In" test_api_3 = "/parent/1/test_right?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____from=1&id____to=2&id____list_____comparison_operator=In&child____str_____matching_pattern=case_sensitive&child____list_____comparison_operator=In" test_api_4 = "/parent/1/test_right?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____from=8&id____to=9&id____list_____comparison_operator=In&child____str_____matching_pattern=case_sensitive&child____list_____comparison_operator=In" test_api_5 = "/parent/1/test_right?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&id____list=0&id____list=1&id____list=2&child____str_____matching_pattern=case_sensitive&child____list_____comparison_operator=In" test_api_6 = "/parent/1/test_right?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&child____str_____matching_pattern=case_sensitive&child____str=child1&child____list_____comparison_operator=In" test_api_7 = "/parent/1/test_right?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&child____str_____matching_pattern=case_sensitive&child____str=child%25&child____list_____comparison_operator=In" test_api_8 = "/parent/1/test_right?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&child____str_____matching_pattern=case_sensitive&child____list_____comparison_operator=In&child____list=child2" test_api_9 = "/parent/1/test_right?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&child____str_____matching_pattern=case_sensitive&child____list_____comparison_operator=In&join_foreign_table=test_left" response = client.get(test_api_1, headers=headers) assert response.status_code == 204 response = client.get(test_api_2, headers=headers) assert response.status_code == 200 assert response.json() == [{'child': 'child1', 'id': 1}, {'child': 'child2', 'id': 2}, {'child': 'child3', 'id': 3}, {'child': 'child4', 'id': 4}] response = client.get(test_api_3, headers=headers) assert response.status_code == 200 assert response.json() == [{'child': 'child1', 'id': 1}, {'child': 'child2', 'id': 2}] response = client.get(test_api_4, headers=headers) assert response.status_code == 204 response = client.get(test_api_5, headers=headers) assert response.status_code == 200 assert response.json() == [{'child': 'child1', 'id': 1}, {'child': 'child2', 'id': 2}] response = client.get(test_api_6, headers=headers) assert response.status_code == 200 assert response.json() == [{'child': 'child1', 'id': 1}] response = client.get(test_api_7, headers=headers) assert response.status_code == 200 assert response.json() == [{'child': 'child1', 'id': 1}, {'child': 'child2', 'id': 2}, {'child': 'child3', 'id': 3}, {'child': 'child4', 'id': 4}] response = client.get(test_api_8, headers=headers) assert response.status_code == 200 assert response.json() == [{'child': 'child2', 'id': 2}] response = client.get(test_api_9, headers=headers) assert response.status_code == 200 assert response.json() == [{'child': 'child1', 'id': 1, 'test_left_foreign': [{'id': 1, 'parent': 'parent1'}]}] def test_get_many_2(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } test_api_1 = "/parent/0/test_right_second?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&child_second____str_____matching_pattern=case_sensitive&child_second____list_____comparison_operator=In" test_api_2 = "/parent/1/test_right_second?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&child_second____str_____matching_pattern=case_sensitive&child_second____list_____comparison_operator=In" test_api_3 = "/parent/1/test_right_second?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____from=1&id____to=2&id____list_____comparison_operator=In&child_second____str_____matching_pattern=case_sensitive&child_second____list_____comparison_operator=In" test_api_4 = "/parent/1/test_right_second?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____from=8&id____to=9&id____list_____comparison_operator=In&child_second____str_____matching_pattern=case_sensitive&child_second____list_____comparison_operator=In" test_api_5 = "/parent/1/test_right_second?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&id____list=0&id____list=1&id____list=2&child_second____str_____matching_pattern=case_sensitive&child_second____list_____comparison_operator=In" test_api_6 = "/parent/1/test_right_second?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&child_second____str_____matching_pattern=case_sensitive&child_second____str=child_second1&child_second____list_____comparison_operator=In" test_api_7 = "/parent/1/test_right_second?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&child_second____str_____matching_pattern=case_sensitive&child_second____str=child_second%25&child_second____list_____comparison_operator=In" test_api_8 = "/parent/1/test_right_second?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&child_second____str_____matching_pattern=case_sensitive&child_second____list_____comparison_operator=In&child_second____list=child_second2" test_api_9 = "/parent/1/test_right_second?id____from_____comparison_operator=Greater_than_or_equal_to&id____to_____comparison_operator=Less_than_or_equal_to&id____list_____comparison_operator=In&child_second____str_____matching_pattern=case_sensitive&child_second____list_____comparison_operator=In&join_foreign_table=test_left" response = client.get(test_api_1, headers=headers) assert response.status_code == 204 response = client.get(test_api_2, headers=headers) assert response.status_code == 200 assert response.json() == [{'child_second': 'child_second1', 'id': 1}, {'child_second': 'child_second2', 'id': 2}, {'child_second': 'child_second3', 'id': 3}, {'child_second': 'child_second4', 'id': 4}] response = client.get(test_api_3, headers=headers) assert response.status_code == 200 assert response.json() == [{'child_second': 'child_second1', 'id': 1}, {'child_second': 'child_second2', 'id': 2}] response = client.get(test_api_4, headers=headers) assert response.status_code == 204 response = client.get(test_api_5, headers=headers) assert response.status_code == 200 assert response.json() == [{'child_second': 'child_second1', 'id': 1}, {'child_second': 'child_second2', 'id': 2}] response = client.get(test_api_6, headers=headers) assert response.status_code == 200 assert response.json() == [{'child_second': 'child_second1', 'id': 1}] response = client.get(test_api_7, headers=headers) assert response.status_code == 200 assert response.json() == [{'child_second': 'child_second1', 'id': 1}, {'child_second': 'child_second2', 'id': 2}, {'child_second': 'child_second3', 'id': 3}, {'child_second': 'child_second4', 'id': 4}] response = client.get(test_api_8, headers=headers) assert response.status_code == 200 assert response.json() == [{'child_second': 'child_second2', 'id': 2}] response = client.get(test_api_9, headers=headers) assert response.status_code == 200 assert response.json() == [{'child_second': 'child_second1', 'id': 1, 'test_left_foreign': [{'id': 1, 'parent': 'parent1'}]}] def setup_module(module): Child.__table__.create(module.engine, checkfirst=True) ChildSecond.__table__.create(module.engine, checkfirst=True) Parent.__table__.create(module.engine, checkfirst=True) association_table.create(module.engine, checkfirst=True) association_table_second.create(module.engine, checkfirst=True) db = module.session() db.add(Child(id=1, child="child1")) db.add(Child(id=2, child="child2")) db.add(Child(id=3, child="child3")) db.add(Child(id=4, child="child4")) db.flush() db.add(Parent(id=1, parent="parent1")) db.add(Parent(id=2, parent="parent2")) db.add(Parent(id=3, parent="parent3")) db.add(Parent(id=4, parent="parent4")) db.flush() db.execute(association_table.insert().values(left_id=1, right_id=1)) db.execute(association_table.insert().values(left_id=2, right_id=2)) db.execute(association_table.insert().values(left_id=3, right_id=3)) db.execute(association_table.insert().values(left_id=4, right_id=4)) db.add(ChildSecond(id=1, child_second="child_second1")) db.add(ChildSecond(id=2, child_second="child_second2")) db.add(ChildSecond(id=3, child_second="child_second3")) db.add(ChildSecond(id=4, child_second="child_second4")) db.flush() db.execute(association_table_second.insert().values(left_id_second=1, right_id_second=1)) db.execute(association_table_second.insert().values(left_id_second=2, right_id_second=2)) db.execute(association_table_second.insert().values(left_id_second=3, right_id_second=3)) db.execute(association_table_second.insert().values(left_id_second=4, right_id_second=4)) q = db.execute(''' SELECT name FROM sqlite_master ''') available_tables = q.fetchall() db.commit() def teardown_module(module): association_table.drop(engine, checkfirst=True) association_table_second.drop(engine, checkfirst=True) ChildSecond.__table__.drop(engine, checkfirst=True) Parent.__table__.drop(engine, checkfirst=True) Child.__table__.drop(engine, checkfirst=True) ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/join_relationship/__init__.py ================================================ ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/join_relationship/test_relationship_extra.py ================================================ import json from fastapi import FastAPI from sqlalchemy import Column, Integer, \ ForeignKey, Table, String from sqlalchemy.orm import declarative_base, sessionmaker, relationship from src.fastapi_quickcrud.misc.type import SqlType from src.fastapi_quickcrud.crud_router import crud_router_builder app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine from sqlalchemy.pool import StaticPool engine = create_engine('sqlite://', echo=True, connect_args={"check_same_thread": False}, pool_recycle=7200, poolclass=StaticPool) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() class User(Base): __tablename__ = 'test_users' id = Column(Integer, primary_key=True, autoincrement=True, unique=True) name = Column(String, nullable=False) email = Column(String, nullable=False) friend = Table( 'test_friend', Base.metadata, Column('id', ForeignKey('test_users.id', ondelete='CASCADE', onupdate='CASCADE'), nullable=False), Column('friend_name', String, nullable=False) ) crud_route_1 = crud_router_builder(db_session=get_transaction_session, db_model=User, prefix="/user", tags=["User"] ) crud_route_2 = crud_router_builder(db_session=get_transaction_session, db_model=friend, prefix="/friend", tags=["friend"] ) from starlette.testclient import TestClient [app.include_router(i) for i in [crud_route_1,crud_route_2]] client = TestClient(app) def test_(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } data = '[{"id": 1,"name": "string","email": "string"}]' response = client.post('/user', headers=headers, data=data) assert response.status_code == 201 assert response.json() == [{"id": 1,"name": "string","email": "string"}] data =' [{"id": 1,"friend_name": "string"}]' response = client.post('/friend', headers=headers, data = data) assert response.status_code == 201 assert response.json() == [ { "id": 1, "friend_name": "string" } ] response = client.get('/friend?join_foreign_table=test_users', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_users_foreign": [ { "id": 1, "name": "string", "email": "string" } ], "id": 1, "friend_name": "string" } ] def setup_module(module): User.__table__.create(module.engine, checkfirst=True) friend.create(module.engine, checkfirst=True) def teardown_module(module): friend.drop(engine, checkfirst=True) User.__table__.drop(engine, checkfirst=True) ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/join_relationship/test_relationship_m2m.py ================================================ from fastapi import FastAPI from sqlalchemy import Column, Integer, \ ForeignKey, Table from sqlalchemy.orm import declarative_base, sessionmaker, relationship from src.fastapi_quickcrud.crud_router import crud_router_builder app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine from sqlalchemy.pool import StaticPool engine = create_engine('sqlite://', echo=True, connect_args={"check_same_thread": False}, pool_recycle=7200, poolclass=StaticPool) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() association_table = Table('test_association', Base.metadata, Column('left_id', ForeignKey('test_left.id')), Column('right_id', ForeignKey('test_right.id')) ) association_table_second = Table('test_association_second', Base.metadata, Column('left_id_second', ForeignKey('test_left.id')), Column('right_id_second', ForeignKey('test_right_second.id')) ) class Child(Base): __tablename__ = 'test_right' id = Column(Integer, primary_key=True) class Parent(Base): __tablename__ = 'test_left' id = Column(Integer, primary_key=True) children = relationship("Child", secondary=association_table) children_second = relationship("ChildSecond", secondary=association_table_second) class ChildSecond(Base): __tablename__ = 'test_right_second' id = Column(Integer, primary_key=True) crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child", tags=["child"], ) crud_route_association_table_second = crud_router_builder(db_session=get_transaction_session, db_model=association_table_second, prefix="/association_table_second", tags=["association_table_second"], ) crud_route_child_second = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child_second", tags=["child_second"], ) crud_route_parent = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"], ) crud_route_association = crud_router_builder(db_session=get_transaction_session, db_model=association_table, prefix="/association", tags=["association"], ) from starlette.testclient import TestClient [app.include_router(i) for i in [crud_route_association_table_second, crud_route_child_second, crud_route_parent, crud_route_child, crud_route_association]] client = TestClient(app) def test_get_parent_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent?join_foreign_table=test_right', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_right_foreign": [ { "id": 1 } ], "id": 1 }, { "test_right_foreign": [ { "id": 2 } ], "id": 2 }, { "test_right_foreign": [ { "id": 3 } ], "id": 3 }, { "test_right_foreign": [ { "id": 4 } ], "id": 4 } ] response = client.get('/parent/1?join_foreign_table=test_right', headers=headers) assert response.status_code == 200 assert response.json() == { "test_right_foreign": [ { "id": 1 } ], "id": 1 } response = client.get('/parent?join_foreign_table=test_right_second', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_right_second_foreign": [ { "id": 1 } ], "id": 1 }, { "test_right_second_foreign": [ { "id": 2 } ], "id": 2 }, { "test_right_second_foreign": [ { "id": 3 } ], "id": 3 }, { "test_right_second_foreign": [ { "id": 4 } ], "id": 4 } ] response = client.get('/parent/1?join_foreign_table=test_right_second', headers=headers) assert response.status_code == 200 assert response.json() == { "test_right_second_foreign": [ { "id": 1 } ], "id": 1 } response = client.get('/parent?join_foreign_table=test_right&join_foreign_table=test_right_second', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_right_foreign": [ { "id": 1 } ], "test_right_second_foreign": [ { "id": 1 } ], "id": 1 }, { "test_right_foreign": [ { "id": 2 } ], "test_right_second_foreign": [ { "id": 2 } ], "id": 2 }, { "test_right_foreign": [ { "id": 3 } ], "test_right_second_foreign": [ { "id": 3 } ], "id": 3 }, { "test_right_foreign": [ { "id": 4 } ], "test_right_second_foreign": [ { "id": 4 } ], "id": 4 } ] response = client.get('/parent/1?join_foreign_table=test_right&join_foreign_table=test_right_second', headers=headers) assert response.status_code == 200 assert response.json() == { "test_right_foreign": [ { "id": 1 } ], "test_right_second_foreign": [ { "id": 1 } ], "id": 1 } def test_get_child_many_without_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1 }, { "id": 2 }, { "id": 3 }, { "id": 4 } ] response = client.get('/child/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1 } def test_get_association_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/association?join_foreign_table=test_left', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_left_foreign": [ { "id": 1 } ], "left_id": 1, "right_id": 1 }, { "test_left_foreign": [ { "id": 2 } ], "left_id": 2, "right_id": 2 }, { "test_left_foreign": [ { "id": 3 } ], "left_id": 3, "right_id": 3 }, { "test_left_foreign": [ { "id": 4 } ], "left_id": 4, "right_id": 4 } ] response = client.get('/association?join_foreign_table=test_left', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_left_foreign": [ { "id": 1 } ], "left_id": 1, "right_id": 1 }, { "test_left_foreign": [ { "id": 2 } ], "left_id": 2, "right_id": 2 }, { "test_left_foreign": [ { "id": 3 } ], "left_id": 3, "right_id": 3 }, { "test_left_foreign": [ { "id": 4 } ], "left_id": 4, "right_id": 4 } ] response = client.get('/association?join_foreign_table=test_right', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_right_foreign": [ { "id": 1 } ], "left_id": 1, "right_id": 1 }, { "test_right_foreign": [ { "id": 2 } ], "left_id": 2, "right_id": 2 }, { "test_right_foreign": [ { "id": 3 } ], "left_id": 3, "right_id": 3 }, { "test_right_foreign": [ { "id": 4 } ], "left_id": 4, "right_id": 4 } ] response = client.get('/association?join_foreign_table=test_left&join_foreign_table=test_right', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_left_foreign": [ { "id": 1 } ], "test_right_foreign": [ { "id": 1 } ], "left_id": 1, "right_id": 1 }, { "test_left_foreign": [ { "id": 2 } ], "test_right_foreign": [ { "id": 2 } ], "left_id": 2, "right_id": 2 }, { "test_left_foreign": [ { "id": 3 } ], "test_right_foreign": [ { "id": 3 } ], "left_id": 3, "right_id": 3 }, { "test_left_foreign": [ { "id": 4 } ], "test_right_foreign": [ { "id": 4 } ], "left_id": 4, "right_id": 4 } ] def test_get_association_many_second_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/association_table_second?join_foreign_table=test_right_second', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_right_second_foreign": [ { "id": 1 } ], "left_id_second": 1, "right_id_second": 1 }, { "test_right_second_foreign": [ { "id": 2 } ], "left_id_second": 2, "right_id_second": 2 }, { "test_right_second_foreign": [ { "id": 3 } ], "left_id_second": 3, "right_id_second": 3 }, { "test_right_second_foreign": [ { "id": 4 } ], "left_id_second": 4, "right_id_second": 4 } ] response = client.get('/association_table_second?join_foreign_table=test_left', headers=headers) assert response.status_code == 200 assert response.json() == [{'left_id_second': 1, 'right_id_second': 1, 'test_left_foreign': [{'id': 1}]}, {'left_id_second': 2, 'right_id_second': 2, 'test_left_foreign': [{'id': 2}]}, {'left_id_second': 3, 'right_id_second': 3, 'test_left_foreign': [{'id': 3}]}, {'left_id_second': 4, 'right_id_second': 4, 'test_left_foreign': [{'id': 4}]}] response = client.get('/association_table_second?join_foreign_table=test_left&join_foreign_table=test_right_second', headers=headers) assert response.status_code == 200 assert response.json() == [{'left_id_second': 1, 'right_id_second': 1, 'test_left_foreign': [{'id': 1}], 'test_right_second_foreign': [{'id': 1}]}, {'left_id_second': 2, 'right_id_second': 2, 'test_left_foreign': [{'id': 2}], 'test_right_second_foreign': [{'id': 2}]}, {'left_id_second': 3, 'right_id_second': 3, 'test_left_foreign': [{'id': 3}], 'test_right_second_foreign': [{'id': 3}]}, {'left_id_second': 4, 'right_id_second': 4, 'test_left_foreign': [{'id': 4}], 'test_right_second_foreign': [{'id': 4}]}] response = client.get('/association_table_second', headers=headers) assert response.status_code == 200 assert response.json() == [ { "left_id_second": 1, "right_id_second": 1 }, { "left_id_second": 2, "right_id_second": 2 }, { "left_id_second": 3, "right_id_second": 3 }, { "left_id_second": 4, "right_id_second": 4 } ] def test_get_child_many_second_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child_second', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1 }, { "id": 2 }, { "id": 3 }, { "id": 4 } ] response = client.get('/child_second/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1 } def setup_module(module): Child.__table__.create(module.engine, checkfirst=True) ChildSecond.__table__.create(module.engine, checkfirst=True) Parent.__table__.create(module.engine, checkfirst=True) association_table.create(module.engine, checkfirst=True) association_table_second.create(module.engine, checkfirst=True) db = module.session() db.add(Child(id=1)) db.add(Child(id=2)) db.add(Child(id=3)) db.add(Child(id=4)) db.flush() db.add(Parent(id=1)) db.add(Parent(id=2)) db.add(Parent(id=3)) db.add(Parent(id=4)) db.flush() db.execute(association_table.insert().values(left_id=1, right_id=1)) db.execute(association_table.insert().values(left_id=2, right_id=2)) db.execute(association_table.insert().values(left_id=3, right_id=3)) db.execute(association_table.insert().values(left_id=4, right_id=4)) db.add(ChildSecond(id=1)) db.add(ChildSecond(id=2)) db.add(ChildSecond(id=3)) db.add(ChildSecond(id=4)) db.flush() db.execute(association_table_second.insert().values(left_id_second=1, right_id_second=1)) db.execute(association_table_second.insert().values(left_id_second=2, right_id_second=2)) db.execute(association_table_second.insert().values(left_id_second=3, right_id_second=3)) db.execute(association_table_second.insert().values(left_id_second=4, right_id_second=4)) q = db.execute(''' SELECT name FROM sqlite_master ''') available_tables = q.fetchall() db.commit() def teardown_module(module): association_table.drop(engine, checkfirst=True) association_table_second.drop(engine, checkfirst=True) ChildSecond.__table__.drop(engine, checkfirst=True) Parent.__table__.drop(engine, checkfirst=True) Child.__table__.drop(engine, checkfirst=True) ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/join_relationship/test_relationship_m2m_back_populates.py ================================================ import os from fastapi import FastAPI from sqlalchemy import Column, Integer, \ ForeignKey, Table from sqlalchemy.orm import declarative_base, sessionmaker, relationship from src.fastapi_quickcrud.crud_router import crud_router_builder TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine from sqlalchemy.pool import StaticPool engine = create_engine('sqlite://', echo=True, connect_args={"check_same_thread": False}, pool_recycle=7200, poolclass=StaticPool) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() association_table = Table('test_association', Base.metadata, Column('left_id', ForeignKey('test_left.id')), Column('right_id', ForeignKey('test_right.id')) ) association_table_second = Table('test_association_second', Base.metadata, Column('left_id_second', ForeignKey('test_left.id')), Column('right_id_second', ForeignKey('test_right_second.id')) ) class Child(Base): __tablename__ = 'test_right' id = Column(Integer, primary_key=True) parent = relationship("Parent", secondary=association_table, back_populates="children") class ChildSecond(Base): __tablename__ = 'test_right_second' id = Column(Integer, primary_key=True) parent_second = relationship("Parent", secondary=association_table_second, back_populates="children_second") class Parent(Base): __tablename__ = 'test_left' id = Column(Integer, primary_key=True) children = relationship("Child", secondary=association_table, back_populates="parent") children_second = relationship("ChildSecond", secondary=association_table_second, back_populates="parent_second") crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child", tags=["child"] ) crud_route_association_table_second = crud_router_builder(db_session=get_transaction_session, db_model=association_table_second, prefix="/association_table_second", tags=["association_table_second"] ) crud_route_child_second = crud_router_builder(db_session=get_transaction_session, db_model=ChildSecond, prefix="/child_second", tags=["child_second"] ) crud_route_parent = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"] ) crud_route_association = crud_router_builder(db_session=get_transaction_session, db_model=association_table, prefix="/association", tags=["association"] ) from starlette.testclient import TestClient [app.include_router(i) for i in [crud_route_association_table_second, crud_route_child_second, crud_route_parent, crud_route_child, crud_route_association]] client = TestClient(app) def test_get_parent_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent?join_foreign_table=test_right', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_right_foreign": [ { "id": 1 } ], "id": 1 }, { "test_right_foreign": [ { "id": 2 } ], "id": 2 }, { "test_right_foreign": [ { "id": 3 } ], "id": 3 }, { "test_right_foreign": [ { "id": 4 } ], "id": 4 } ] response = client.get('/parent/1?join_foreign_table=test_right', headers=headers) assert response.status_code == 200 assert response.json() == { "test_right_foreign": [ { "id": 1 } ], "id": 1 } response = client.get('/parent/1?join_foreign_table=test_right_second', headers=headers) assert response.status_code == 200 assert response.json() == { "test_right_second_foreign": [ { "id": 1 } ], "id": 1 } response = client.get('/parent/1?join_foreign_table=test_right&join_foreign_table=test_right_second', headers=headers) assert response.status_code == 200 assert response.json() == { "test_right_foreign": [ { "id": 1 } ], "test_right_second_foreign": [ { "id": 1 } ], "id": 1 } def test_get_child_many_without_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1 }, { "id": 2 }, { "id": 3 }, { "id": 4 } ] def test_get_child_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child?join_foreign_table=test_left', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_left_foreign": [ { "id": 1 } ], "id": 1 }, { "test_left_foreign": [ { "id": 2 } ], "id": 2 }, { "test_left_foreign": [ { "id": 3 } ], "id": 3 }, { "test_left_foreign": [ { "id": 4 } ], "id": 4 } ] def test_get_association_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/association?join_foreign_table=test_left', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_left_foreign": [ { "id": 1 } ], "left_id": 1, "right_id": 1 }, { "test_left_foreign": [ { "id": 2 } ], "left_id": 2, "right_id": 2 }, { "test_left_foreign": [ { "id": 3 } ], "left_id": 3, "right_id": 3 }, { "test_left_foreign": [ { "id": 4 } ], "left_id": 4, "right_id": 4 } ] response = client.get('/association?join_foreign_table=test_right', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_right_foreign": [ { "id": 1 } ], "left_id": 1, "right_id": 1 }, { "test_right_foreign": [ { "id": 2 } ], "left_id": 2, "right_id": 2 }, { "test_right_foreign": [ { "id": 3 } ], "left_id": 3, "right_id": 3 }, { "test_right_foreign": [ { "id": 4 } ], "left_id": 4, "right_id": 4 } ] response = client.get('/association?join_foreign_table=test_left&join_foreign_table=test_right', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_left_foreign": [ { "id": 1 } ], "test_right_foreign": [ { "id": 1 } ], "left_id": 1, "right_id": 1 }, { "test_left_foreign": [ { "id": 2 } ], "test_right_foreign": [ { "id": 2 } ], "left_id": 2, "right_id": 2 }, { "test_left_foreign": [ { "id": 3 } ], "test_right_foreign": [ { "id": 3 } ], "left_id": 3, "right_id": 3 }, { "test_left_foreign": [ { "id": 4 } ], "test_right_foreign": [ { "id": 4 } ], "left_id": 4, "right_id": 4 } ] def test_get_association_many_second_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/association_table_second?join_foreign_table=test_right_second', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_right_second_foreign": [ { "id": 1 } ], "left_id_second": 1, "right_id_second": 1 }, { "test_right_second_foreign": [ { "id": 2 } ], "left_id_second": 2, "right_id_second": 2 }, { "test_right_second_foreign": [ { "id": 3 } ], "left_id_second": 3, "right_id_second": 3 }, { "test_right_second_foreign": [ { "id": 4 } ], "left_id_second": 4, "right_id_second": 4 } ] response = client.get('/association_table_second?join_foreign_table=test_left', headers=headers) assert response.status_code == 200 assert response.json() == [{'left_id_second': 1, 'right_id_second': 1, 'test_left_foreign': [{'id': 1}]}, {'left_id_second': 2, 'right_id_second': 2, 'test_left_foreign': [{'id': 2}]}, {'left_id_second': 3, 'right_id_second': 3, 'test_left_foreign': [{'id': 3}]}, {'left_id_second': 4, 'right_id_second': 4, 'test_left_foreign': [{'id': 4}]}] response = client.get('/association_table_second?join_foreign_table=test_left&join_foreign_table=test_right_second', headers=headers) assert response.status_code == 200 assert response.json() == [{'left_id_second': 1, 'right_id_second': 1, 'test_left_foreign': [{'id': 1}], 'test_right_second_foreign': [{'id': 1}]}, {'left_id_second': 2, 'right_id_second': 2, 'test_left_foreign': [{'id': 2}], 'test_right_second_foreign': [{'id': 2}]}, {'left_id_second': 3, 'right_id_second': 3, 'test_left_foreign': [{'id': 3}], 'test_right_second_foreign': [{'id': 3}]}, {'left_id_second': 4, 'right_id_second': 4, 'test_left_foreign': [{'id': 4}], 'test_right_second_foreign': [{'id': 4}]}] response = client.get('/association_table_second', headers=headers) assert response.status_code == 200 assert response.json() == [ { "left_id_second": 1, "right_id_second": 1 }, { "left_id_second": 2, "right_id_second": 2 }, { "left_id_second": 3, "right_id_second": 3 }, { "left_id_second": 4, "right_id_second": 4 } ] def test_get_child_many_second_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child_second', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1 }, { "id": 2 }, { "id": 3 }, { "id": 4 } ] response = client.get('/child_second/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1 } response = client.get('/child_second?join_foreign_table=test_left', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_left_foreign": [ { "id": 1 } ], "id": 1 }, { "test_left_foreign": [ { "id": 2 } ], "id": 2 }, { "test_left_foreign": [ { "id": 3 } ], "id": 3 }, { "test_left_foreign": [ { "id": 4 } ], "id": 4 } ] response = client.get('/child_second/1?join_foreign_table=test_left', headers=headers) assert response.status_code == 200 assert response.json() == { "test_left_foreign": [ { "id": 1 } ], "id": 1 } def setup_module(module): Child.__table__.create(engine, checkfirst=True) ChildSecond.__table__.create(engine, checkfirst=True) Parent.__table__.create(engine, checkfirst=True) association_table.create(engine, checkfirst=True) association_table_second.create(engine, checkfirst=True) db = session() db.add(Child(id=1)) db.add(Child(id=2)) db.add(Child(id=3)) db.add(Child(id=4)) db.flush() db.add(Parent(id=1)) db.add(Parent(id=2)) db.add(Parent(id=3)) db.add(Parent(id=4)) db.flush() db.execute(association_table.insert().values(left_id=1, right_id=1)) db.execute(association_table.insert().values(left_id=2, right_id=2)) db.execute(association_table.insert().values(left_id=3, right_id=3)) db.execute(association_table.insert().values(left_id=4, right_id=4)) db.add(ChildSecond(id=1)) db.add(ChildSecond(id=2)) db.add(ChildSecond(id=3)) db.add(ChildSecond(id=4)) db.flush() db.execute(association_table_second.insert().values(left_id_second=1, right_id_second=1)) db.execute(association_table_second.insert().values(left_id_second=2, right_id_second=2)) db.execute(association_table_second.insert().values(left_id_second=3, right_id_second=3)) db.execute(association_table_second.insert().values(left_id_second=4, right_id_second=4)) db.commit() print() def teardown_module(module): association_table.drop(engine, checkfirst=True) association_table_second.drop(engine, checkfirst=True) ChildSecond.__table__.drop(engine, checkfirst=True) Parent.__table__.drop(engine, checkfirst=True) Child.__table__.drop(engine, checkfirst=True) ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/join_relationship/test_relationship_m2o.py ================================================ import json import os from fastapi import FastAPI from sqlalchemy import Column, Integer, \ ForeignKey from sqlalchemy.orm import declarative_base, sessionmaker, relationship from src.fastapi_quickcrud.crud_router import crud_router_builder TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine from sqlalchemy.pool import StaticPool engine = create_engine('sqlite://', echo=True, connect_args={"check_same_thread": False}, pool_recycle=7200, poolclass=StaticPool) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() class Parent(Base): __tablename__ = 'parent_m2o' id = Column(Integer, primary_key=True) child_id = Column(Integer, ForeignKey('child_m2o.id')) child = relationship("Child") class Child(Base): __tablename__ = 'child_m2o' id = Column(Integer, primary_key=True) crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child", tags=["child"] ) crud_route_parent = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"] ) from starlette.testclient import TestClient [app.include_router(i) for i in [crud_route_parent, crud_route_child]] client = TestClient(app) def test_get_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent?join_foreign_table=child_m2o', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1, "child_m2o_foreign": [ { "id": 1 } ], "child_id": 1 }, { "id": 2, "child_m2o_foreign": [ { "id": 1 } ], "child_id": 1 }, { "id": 3, "child_m2o_foreign": [ { "id": 2 } ], "child_id": 2 }, { "id": 4, "child_m2o_foreign": [ { "id": 2 } ], "child_id": 2 } ] response = client.get('/parent/1?join_foreign_table=child_m2o', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1, "child_m2o_foreign": [ { "id": 1 } ], "child_id": 1 } def test_get_child_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1 } def test_get_many_without_join(): query = {"join_foreign_table": "child"} data = json.dumps(query) headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent/1', headers=headers, data=data) assert response.status_code == 200 assert response.json() == { "id": 1, "child_id": 1 } def setup_module(module): Child.__table__.create(engine, checkfirst=True) Parent.__table__.create(engine, checkfirst=True) db = session() db.add(Child(id=1)) db.add(Child(id=2)) db.add(Child(id=3)) db.add(Child(id=4)) db.flush() db.add(Parent(id=1, child_id=1)) db.add(Parent(id=2, child_id=1)) db.add(Parent(id=3, child_id=2)) db.add(Parent(id=4, child_id=2)) db.commit() def teardown_module(module): Parent.__table__.drop(engine, checkfirst=True) Child.__table__.drop(engine, checkfirst=True) ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/join_relationship/test_relationship_m2o_back_populates.py ================================================ import json import os from fastapi import FastAPI from sqlalchemy import Column, Integer, \ ForeignKey from sqlalchemy.orm import declarative_base, sessionmaker, relationship from src.fastapi_quickcrud.crud_router import crud_router_builder TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine from sqlalchemy.pool import StaticPool engine = create_engine('sqlite://', echo=True, connect_args={"check_same_thread": False}, pool_recycle=7200, poolclass=StaticPool) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() class Parent(Base): __tablename__ = 'parent_m2o_back_populates' id = Column(Integer, primary_key=True) child_id = Column(Integer, ForeignKey('child_m2o_back_populates.id')) child = relationship("Child", back_populates="parents") class Child(Base): __tablename__ = 'child_m2o_back_populates' id = Column(Integer, primary_key=True) parents = relationship("Parent", back_populates="child") crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child", tags=["child"] ) crud_route_parent = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"] ) from starlette.testclient import TestClient [app.include_router(i) for i in [crud_route_parent, crud_route_child]] client = TestClient(app) def test_get_parent_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent?join_foreign_table=child_m2o_back_populates', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1, "child_m2o_back_populates_foreign": [ { "id": 1 } ], "child_id": 1 }, { "id": 2, "child_m2o_back_populates_foreign": [ { "id": 1 } ], "child_id": 1 }, { "id": 3, "child_m2o_back_populates_foreign": [ { "id": 2 } ], "child_id": 2 }, { "id": 4, "child_m2o_back_populates_foreign": [ { "id": 2 } ], "child_id": 2 } ] response = client.get('/parent/1?join_foreign_table=child_m2o_back_populates', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1, "child_m2o_back_populates_foreign": [ { "id": 1 } ], "child_id": 1 } def test_get_child_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child?join_foreign_table=parent_m2o_back_populates', headers=headers) assert response.status_code == 200 assert response.json() == [{'id': 1, 'parent_m2o_back_populates_foreign': [{'child_id': 1, 'id': 1}, {'child_id': 1, 'id': 2}]}, {'id': 2, 'parent_m2o_back_populates_foreign': [{'child_id': 2, 'id': 3}, {'child_id': 2, 'id': 4}]}] response = client.get('/child/1?join_foreign_table=parent_m2o_back_populates', headers=headers) assert response.status_code == 200 assert response.json() == { "parent_m2o_back_populates_foreign": [ { "id": 1, "child_id": 1 }, { "id": 2, "child_id": 1 } ], "id": 1 } def test_get_child_many_without_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1, "child_id": 1 }, { "id": 2, "child_id": 1 }, { "id": 3, "child_id": 2 }, { "id": 4, "child_id": 2 } ] response = client.get('/parent/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1, "child_id": 1 } def test_get_parent_many_without_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1 }, { "id": 2 }, { "id": 3 }, { "id": 4 } ] response = client.get('/child/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1 } def setup_module(module): Child.__table__.create(engine, checkfirst=True) Parent.__table__.create(engine, checkfirst=True) db = session() db.add(Child(id=1)) db.add(Child(id=2)) db.add(Child(id=3)) db.add(Child(id=4)) db.flush() db.add(Parent(id=1, child_id=1)) db.add(Parent(id=2, child_id=1)) db.add(Parent(id=3, child_id=2)) db.add(Parent(id=4, child_id=2)) db.commit() def teardown_module(module): Parent.__table__.drop(engine, checkfirst=True) Child.__table__.drop(engine, checkfirst=True) ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/join_relationship/test_relationship_m2o_back_refer.py ================================================ import json import os from fastapi import FastAPI from sqlalchemy import Column, Integer, \ ForeignKey from sqlalchemy.orm import declarative_base, sessionmaker, relationship from src.fastapi_quickcrud.crud_router import crud_router_builder TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine from sqlalchemy.pool import StaticPool engine = create_engine('sqlite://', echo=True, connect_args={"check_same_thread": False}, pool_recycle=7200, poolclass=StaticPool) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() class Child(Base): __tablename__ = 'child_m2o_back_populates' id = Column(Integer, primary_key=True) class Parent(Base): __tablename__ = 'parent_m2o_back_populates' id = Column(Integer, primary_key=True) child_id = Column(Integer, ForeignKey('child_m2o_back_populates.id')) child = relationship("Child", backref="child_m2o_back_populates") crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child", tags=["child"] ) crud_route_parent = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"] ) from starlette.testclient import TestClient [app.include_router(i) for i in [crud_route_parent, crud_route_child]] client = TestClient(app) def test_get_parent_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent?join_foreign_table=child_m2o_back_populates', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1, "child_m2o_back_populates_foreign": [ { "id": 1 } ], "child_id": 1 }, { "id": 2, "child_m2o_back_populates_foreign": [ { "id": 1 } ], "child_id": 1 }, { "id": 3, "child_m2o_back_populates_foreign": [ { "id": 2 } ], "child_id": 2 }, { "id": 4, "child_m2o_back_populates_foreign": [ { "id": 2 } ], "child_id": 2 } ] response = client.get('/parent/1?join_foreign_table=child_m2o_back_populates', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1, "child_m2o_back_populates_foreign": [ { "id": 1 } ], "child_id": 1 } def test_get_child_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child?join_foreign_table=parent_m2o_back_populates', headers=headers) assert response.status_code == 200 assert response.json() == [ { "parent_m2o_back_populates_foreign": [ { "id": 1, "child_id": 1 }, { "id": 2, "child_id": 1 } ], "id": 1 }, { "parent_m2o_back_populates_foreign": [ { "id": 3, "child_id": 2 }, { "id": 4, "child_id": 2 } ], "id": 2 } ] response = client.get('/child/1?join_foreign_table=parent_m2o_back_populates', headers=headers) assert response.status_code == 200 assert response.json() == { "parent_m2o_back_populates_foreign": [ { "id": 1, "child_id": 1 }, { "id": 2, "child_id": 1 } ], "id": 1 } def test_get_child_many_without_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1, "child_id": 1 }, { "id": 2, "child_id": 1 }, { "id": 3, "child_id": 2 }, { "id": 4, "child_id": 2 } ] response = client.get('/parent/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1, "child_id": 1 } def test_get_parent_many_without_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1 }, { "id": 2 }, { "id": 3 }, { "id": 4 } ] response = client.get('/child/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1 } def setup_module(module): Child.__table__.create(engine, checkfirst=True) Parent.__table__.create(engine, checkfirst=True) db = session() db.add(Child(id=1)) db.add(Child(id=2)) db.add(Child(id=3)) db.add(Child(id=4)) db.flush() db.add(Parent(id=1, child_id=1)) db.add(Parent(id=2, child_id=1)) db.add(Parent(id=3, child_id=2)) db.add(Parent(id=4, child_id=2)) db.commit() def teardown_module(module): Parent.__table__.drop(engine, checkfirst=True) Child.__table__.drop(engine, checkfirst=True) ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/join_relationship/test_relationship_o2m.py ================================================ import json import os from fastapi import FastAPI from sqlalchemy import Column, Integer, \ ForeignKey from sqlalchemy.orm import declarative_base, sessionmaker, relationship from src.fastapi_quickcrud.crud_router import crud_router_builder TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine from sqlalchemy.pool import StaticPool engine = create_engine('sqlite://', echo=True, connect_args={"check_same_thread": False}, pool_recycle=7200, poolclass=StaticPool) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() class Parent(Base): __tablename__ = 'parent_one_to_many' id = Column(Integer, primary_key=True) children = relationship("Child") class Child(Base): __tablename__ = 'child_one_to_many' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('parent_one_to_many.id')) crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child", tags=["child"] ) crud_route_parent = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"] ) from starlette.testclient import TestClient [app.include_router(i) for i in [crud_route_parent, crud_route_child]] client = TestClient(app) def test_get_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent?join_foreign_table=child_one_to_many', headers=headers) assert response.status_code == 200 assert response.json() == [ { "child_one_to_many_foreign": [ { "id": 1, "parent_id": 1 }, { "id": 2, "parent_id": 1 } ], "id": 1 }, { "child_one_to_many_foreign": [ { "id": 3, "parent_id": 2 }, { "id": 4, "parent_id": 2 } ], "id": 2 } ] response = client.get('/parent/1?join_foreign_table=child_one_to_many', headers=headers) assert response.status_code == 200 assert response.json() == { "child_one_to_many_foreign": [ { "id": 1, "parent_id": 1 }, { "id": 2, "parent_id": 1 } ], "id": 1 } def test_get_child_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1, "parent_id": 1 }, { "id": 2, "parent_id": 1 }, { "id": 3, "parent_id": 2 }, { "id": 4, "parent_id": 2 }] response = client.get('/child/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1, "parent_id": 1 } def test_get_many_without_join(): query = {"join_foreign_table": "child"} data = json.dumps(query) headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent', headers=headers, data=data) assert response.status_code == 200 assert response.json() == [ { "id": 1 }, { "id": 2 } ] response = client.get('/parent/1', headers=headers, data=data) assert response.status_code == 200 assert response.json() == { "id": 1 } def setup_module(module): Parent.__table__.create(engine, checkfirst=True) Child.__table__.create(engine, checkfirst=True) db = session() db.add(Parent(id=1)) db.add(Parent(id=2)) db.flush() db.add(Child(id=1, parent_id=1)) db.add(Child(id=2, parent_id=1)) db.add(Child(id=3, parent_id=2)) db.add(Child(id=4, parent_id=2)) db.commit() def teardown_module(module): Child.__table__.drop(engine, checkfirst=True) Parent.__table__.drop(engine, checkfirst=True) ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/join_relationship/test_relationship_o2m_back_populates.py ================================================ import json import os from fastapi import FastAPI from sqlalchemy import Column, Integer, \ ForeignKey from sqlalchemy.orm import declarative_base, sessionmaker, relationship from src.fastapi_quickcrud.crud_router import crud_router_builder TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine from sqlalchemy.pool import StaticPool engine = create_engine('sqlite://', echo=True, connect_args={"check_same_thread": False}, pool_recycle=7200, poolclass=StaticPool) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() class Parent(Base): __tablename__ = 'parent_one_to_many_back_populates' id = Column(Integer, primary_key=True) children = relationship("Child", back_populates="parent") class Child(Base): __tablename__ = 'child_one_to_many_back_populates' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('parent_one_to_many_back_populates.id')) parent = relationship("Parent", back_populates="children") crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child", tags=["child"] ) crud_route_parent = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"] ) from starlette.testclient import TestClient [app.include_router(i) for i in [crud_route_parent, crud_route_child]] client = TestClient(app) def test_get_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent?join_foreign_table=child_one_to_many_back_populates', headers=headers) assert response.status_code == 200 assert response.json() == [ { "child_one_to_many_back_populates_foreign": [ { "id": 1, "parent_id": 1 }, { "id": 2, "parent_id": 1 } ], "id": 1 }, { "child_one_to_many_back_populates_foreign": [ { "id": 3, "parent_id": 2 }, { "id": 4, "parent_id": 2 } ], "id": 2 } ] response = client.get('/parent/1?join_foreign_table=child_one_to_many_back_populates', headers=headers) assert response.status_code == 200 assert response.json() == { "child_one_to_many_back_populates_foreign": [ { "id": 1, "parent_id": 1 }, { "id": 2, "parent_id": 1 } ], "id": 1 } def test_get_child_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1, "parent_id": 1 }, { "id": 2, "parent_id": 1 }, { "id": 3, "parent_id": 2 }, { "id": 4, "parent_id": 2 }] response = client.get('/child/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1, "parent_id": 1 } def test_get_many_without_join(): query = {"join_foreign_table": "child"} data = json.dumps(query) headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent', headers=headers, data=data) assert response.status_code == 200 assert response.json() == [ { "id": 1 }, { "id": 2 } ] response = client.get('/parent/1', headers=headers, data=data) assert response.status_code == 200 assert response.json() == { "id": 1 } def setup_module(module): Parent.__table__.create(engine, checkfirst=True) Child.__table__.create(engine, checkfirst=True) db = session() db.add(Parent(id=1)) db.add(Parent(id=2)) db.flush() db.add(Child(id=1, parent_id=1)) db.add(Child(id=2, parent_id=1)) db.add(Child(id=3, parent_id=2)) db.add(Child(id=4, parent_id=2)) db.commit() def teardown_module(module): Child.__table__.drop(engine, checkfirst=True) Parent.__table__.drop(engine, checkfirst=True) ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/join_relationship/test_relationship_o2m_back_ref.py ================================================ import json import os from fastapi import FastAPI from sqlalchemy import Column, Integer, \ ForeignKey from sqlalchemy.orm import declarative_base, sessionmaker, relationship from src.fastapi_quickcrud.crud_router import crud_router_builder TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine from sqlalchemy.pool import StaticPool engine = create_engine('sqlite://', echo=True, connect_args={"check_same_thread": False}, pool_recycle=7200, poolclass=StaticPool) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() class Parent(Base): __tablename__ = 'parent_one_to_many_back_ref' id = Column(Integer, primary_key=True) children = relationship("Child", backref="child_one_to_many_back_ref") class Child(Base): __tablename__ = 'child_one_to_many_back_ref' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('parent_one_to_many_back_ref.id')) crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child", tags=["child"] ) crud_route_parent = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"] ) from starlette.testclient import TestClient [app.include_router(i) for i in [crud_route_parent, crud_route_child]] client = TestClient(app) def test_get_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent?join_foreign_table=child_one_to_many_back_ref', headers=headers) assert response.status_code == 200 assert response.json() == [{'child_one_to_many_back_ref_foreign': [{'id': 1, 'parent_id': 1}, {'id': 2, 'parent_id': 1}], 'id': 1}, {'child_one_to_many_back_ref_foreign': [{'id': 3, 'parent_id': 2}, {'id': 4, 'parent_id': 2}], 'id': 2}] response = client.get('/parent/1?join_foreign_table=child_one_to_many_back_ref', headers=headers) assert response.status_code == 200 assert response.json() == { "child_one_to_many_back_ref_foreign": [ { "id": 1, "parent_id": 1 }, { "id": 2, "parent_id": 1 } ], "id": 1 } def test_get_child_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1, "parent_id": 1 }, { "id": 2, "parent_id": 1 }, { "id": 3, "parent_id": 2 }, { "id": 4, "parent_id": 2 }] response = client.get('/child/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1, "parent_id": 1 } def test_get_many_without_join(): query = {"join_foreign_table": "child"} data = json.dumps(query) headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent', headers=headers, data=data) assert response.status_code == 200 assert response.json() == [ { "id": 1 }, { "id": 2 } ] response = client.get('/parent/1', headers=headers, data=data) assert response.status_code == 200 assert response.json() == { "id": 1 } def setup_module(module): Parent.__table__.create(engine, checkfirst=True) Child.__table__.create(engine, checkfirst=True) db = session() db.add(Parent(id=1)) db.add(Parent(id=2)) db.flush() db.add(Child(id=1, parent_id=1)) db.add(Child(id=2, parent_id=1)) db.add(Child(id=3, parent_id=2)) db.add(Child(id=4, parent_id=2)) db.commit() def teardown_module(module): Child.__table__.drop(engine, checkfirst=True) Parent.__table__.drop(engine, checkfirst=True) ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/join_relationship/test_relationship_o2o.py ================================================ import json import os from fastapi import FastAPI from sqlalchemy import Column, Integer, \ ForeignKey from sqlalchemy.orm import declarative_base, sessionmaker, relationship from src.fastapi_quickcrud.crud_router import crud_router_builder TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine from sqlalchemy.pool import StaticPool engine = create_engine('sqlite://', echo=True, connect_args={"check_same_thread": False}, pool_recycle=7200, poolclass=StaticPool) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() class Parent(Base): __tablename__ = 'parent_o2o' id = Column(Integer, primary_key=True) # one-to-many collection children = relationship("Child", back_populates="parent") class Child(Base): __tablename__ = 'child_o2o' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('parent_o2o.id')) # many-to-one scalar parent = relationship("Parent", back_populates="children") def test_function(self, *args, **kwargs ): print("hello") crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child", tags=["child"] ) crud_route_parent = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"] ) from starlette.testclient import TestClient [app.include_router(i) for i in [crud_route_parent, crud_route_child]] client = TestClient(app) def test_get_parent_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent?join_foreign_table=child_o2o', headers=headers) assert response.status_code == 200 assert response.json() == [{'child_o2o_foreign': [{'id': 1, 'parent_id': 1}, {'id': 2, 'parent_id': 1}], 'id': 1}, {'child_o2o_foreign': [{'id': 3, 'parent_id': 2}, {'id': 4, 'parent_id': 2}], 'id': 2}] response = client.get('/parent/1?join_foreign_table=child_o2o', headers=headers) assert response.status_code == 200 assert response.json() == { "child_o2o_foreign": [ { "id": 1, "parent_id": 1 }, { "id": 2, "parent_id": 1 } ], "id": 1 } def test_get_child_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child?join_foreign_table=parent_o2o', headers=headers) assert response.status_code == 200 assert response.json() == [{'id': 1, 'parent_id': 1, 'parent_o2o_foreign': [{'id': 1}]}, {'id': 2, 'parent_id': 1, 'parent_o2o_foreign': [{'id': 1}]}, {'id': 3, 'parent_id': 2, 'parent_o2o_foreign': [{'id': 2}]}, {'id': 4, 'parent_id': 2, 'parent_o2o_foreign': [{'id': 2}]}] response = client.get('/child/1?join_foreign_table=parent_o2o', headers=headers) assert response.status_code == 200 assert response.json() =={ "id": 1, "parent_o2o_foreign": [ { "id": 1 } ], "parent_id": 1 } def test_get_child_many_without_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1 }, { "id": 2 }, ] response = client.get('/parent/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1 } def test_get_parent_many_without_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1, "parent_id": 1 }, { "id": 2, "parent_id": 1 }, { "id": 3, "parent_id": 2 }, { "id": 4, "parent_id": 2 } ] response = client.get('/child/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1, "parent_id": 1 } def setup_module(module): Parent.__table__.create(engine) Child.__table__.create(engine) db = session() db.add(Parent(id=1)) db.add(Parent(id=2)) db.flush() db.add(Child(id=1, parent_id=1)) db.add(Child(id=2, parent_id=1)) db.add(Child(id=3, parent_id=2)) db.add(Child(id=4, parent_id=2)) db.commit() print() def teardown_module(module): Child.__table__.drop(engine, checkfirst=True) Parent.__table__.drop(engine, checkfirst=True) ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/test_create_many_api.py ================================================ import json from starlette.testclient import TestClient from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud.misc.exceptions import ConflictColumnsCannotHit from tests.test_implementations.test_memory_sqlalchemy.api_test import UntitledTable256, app # Create Many API Test test_create_many = crud_router_builder(crud_methods=[CrudMethods.CREATE_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], db_model=UntitledTable256, prefix="/test_creation_many", tags=["test"], autocommit=True ) [app.include_router(i) for i in [test_create_many]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def create_example_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '[ { "bool_value": true, "char_value": "string", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963Z", "timestamptz_value": "2021-07-23T02:38:24.963Z", "varchar_value": "string"}, { "bool_value": true, "char_value": "string", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963Z", "timestamptz_value": "2021-07-23T02:38:24.963Z", "varchar_value": "string"}, { "bool_value": true, "char_value": "string", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963Z", "timestamptz_value": "2021-07-23T02:38:24.963Z", "varchar_value": "string"} ]' response = client.post('/test_creation_many', headers=headers, data=data) assert response.status_code == 201 return response.json() def test_try_only_input_required_fields(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '[ { "float4_value": 1, "int2_value": 1, "int4_value": 1 },{ "float4_value": 2, "int2_value": 2, "int4_value": 2 },{ "float4_value": 3, "int2_value": 3, "int4_value": 3 } ] ' data_ = json.loads(data) response = client.post('/test_creation_many', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_try_input_with_conflict_but_conflict_columns_not_hit(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } insert_data = [] for i in sample_data: _ = {} for k, v in {"float4_value": 99, "int2_value": 99, "int4_value": 99}.items(): _[k] = v insert_data.append(_) data = insert_data try: _ = json.dumps(data) response = client.post('/test_creation_many', headers=headers, data=json.dumps(sample_data)) except ConflictColumnsCannotHit as e: pass assert response.status_code == 409 def test_try_input_without_conflict(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {} insert_data = [] for i in sample_data: _ = {} for k, v in i.items(): _[k] = v for k, v in {"float4_value": 99, "int2_value": 99, "int4_value": 99}.items(): _[k] = v insert_data.append(_) data['insert'] = insert_data response = client.post('/test_creation_many', headers=headers, data=json.dumps(insert_data)) assert response.status_code == 409 ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/test_create_one_api.py ================================================ import json import random import uuid from datetime import date, timedelta, datetime, timezone from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.exceptions import ConflictColumnsCannotHit, UnknownColumn, UpdateColumnEmptyException from src.fastapi_quickcrud.misc.type import CrudMethods from tests.test_implementations.test_memory_sqlalchemy.api_test import app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_one = crud_router_builder( db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_one", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_many = crud_router_builder( db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_post_and_redirect_get = crud_router_builder( db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_get_data = crud_router_builder( db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields # Create One API Test def create_example_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_creation_one', headers=headers, data=data) assert response.status_code == 201 return response.json() def test_try_only_input_required_fields(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"float4_value": 0.0, "int2_value": 0, "int4_value": 0} response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) assert response.status_code == 201 response_result = response.json() for k, v in data.items(): assert response_result[k] == v def test_try_input_with_conflict_but_conflict_columns_not_hit(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"on_conflict": {"update_columns": ["bool_value", "float8_value", "varchar_value", "interval_value", "time_value", "int8_value", "jsonb_value", "timetz_value", "array_str__value", "text_value", "char_value", "uuid_value", "array_value", "numeric_value", "timestamp_value", "int2_value", "date_value", "json_value", "timestamptz_value"]}} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 99, "int2_value": 99, "int4_value": 99}.items(): data[k] = v # for k, v in {"float4_value": 99.9, "int2_value": 99, "int4_value": 99}.items(): # data[k] = v try: _ = json.dumps(data) response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) except ConflictColumnsCannotHit as e: pass assert response.status_code == 409 def test_try_input_with_conflict(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"on_conflict": {"update_columns": ["bool_value", "float8_value", "varchar_value", "interval_value", "time_value", "int8_value", "jsonb_value", "timetz_value", "array_str__value", "text_value", "char_value", "uuid_value", "array_value", "numeric_value", "timestamp_value", "int2_value", "date_value", "json_value", "timestamptz_value"]}} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 0.0, "int2_value": 99, "int4_value": 0}.items(): data[k] = v response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) assert response.status_code == 409 def test_try_input_without_conflict(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 0.0, "int2_value": 99, "int4_value": 0}.items(): data[k] = v # data['on_conflict'] = {'update_columns': []} response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) assert response.status_code == 409 ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/test_delete_many_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods from tests.test_implementations.test_memory_sqlalchemy.api_test import app, UntitledTable256 test_create_one = crud_router_builder( db_model=UntitledTable256, crud_methods=[ CrudMethods.CREATE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_creation_one", tags=["test"], autocommit=True ) test_create_many = crud_router_builder( db_model=UntitledTable256, crud_methods=[ CrudMethods.CREATE_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_creation_many", tags=["test"], autocommit=True ) test_post_and_redirect_get = crud_router_builder( db_model=UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_post_direct_get", tags=["test"], autocommit=True ) test_get_data = crud_router_builder( db_model=UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"], autocommit=True ) test_delete_data = crud_router_builder( db_model=UntitledTable256, crud_methods=[ CrudMethods.DELETE_MANY ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_delete_many", tags=["test"], autocommit=True ) [app.include_router(i) for i in [test_post_and_redirect_get, test_delete_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def test_create_many_and_delete_many(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) response = client.delete(f'/test_delete_many?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_create_many_and_delete_many_but_not_found(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '10:18:18', "time_value____to": '12:18:18', "time_value____list": '12:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "timez_value____from": '18:18:18+00:00', "timez_value____to": '18:18:18+00:00', "timez_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) response = client.delete(f'/test_delete_many?{query_string}') assert response.status_code == 204 ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/test_delete_one_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_memory_sqlalchemy.api_test import app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_one = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_one", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_many = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_post_and_redirect_get = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_get_data = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.DELETE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_delete_data = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_delete_one", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_delete_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def test_create_one_and_delete_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key ,= [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False} response = client.delete(f'/test_delete_one/{primary_key}?{query_string}') response_data = response.json() assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_create_one_and_delete_one_but_not_found(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key ,= [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '10:18:18', "time_value____to": '12:18:18', "time_value____list": '10:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "timez_value____from": '18:18:18+00:00', "timez_value____to": '18:18:18+00:00', "timez_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False} response = client.delete(f'/test_delete_one/{primary_key}?{query_string}') assert response.status_code == 404 ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/test_get_many_api.py ================================================ import json from collections import OrderedDict from urllib.parse import urlencode from starlette.testclient import TestClient from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.exceptions import UnknownColumn, UnknownOrderType from tests.test_implementations.test_memory_sqlalchemy.api_test import app, UntitledTable256 test_create_many = crud_router_builder(db_model=UntitledTable256, prefix="/test_creation_many", tags=["test"], exclude_columns=['bytea_value'] ) test_find_many = crud_router_builder(db_model=UntitledTable256, prefix="/test_get_many", tags=["test"], exclude_columns=['bytea_value'] ) [app.include_router(i) for i in [test_create_many, test_find_many]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields # test create many def create_example_data(num=1, **kwargs): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } insert_sample_item = {"bool_value": kwargs.get('bool_value', True), "char_value": kwargs.get('char_value', 'string'), "date_value": kwargs.get('date_value', "2021-07-23"), "float4_value": kwargs.get('float4_value', 0.6), "float8_value": kwargs.get('float8_value', 0.8), "int2_value": kwargs.get('int2_value', 11), "int4_value": kwargs.get('int4_value', 1), "int8_value": kwargs.get('int8_value', 3), "numeric_value": kwargs.get('numeric_value', 110), "text_value": kwargs.get('text_value', 'string'), "timestamp_value": kwargs.get('timestamp_value', "2021-07-23T02:38:24.963Z"), "timestamptz_value": kwargs.get('timestamptz_value', "2021-07-23T02:38:24.963Z"), "varchar_value": kwargs.get('varchar_value', 'string')} data = [insert_sample_item for i in range(num)] response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 response_result = response.json() for i in response_result: assert primary_key_name in i assert i[primary_key_name] return response_result # test pagination by offset and limit and ordering def test_pagination_and_ording(): sample_data = create_example_data(5 * 10) assert len(sample_data) == 5 * 10 limit = 5 seem = [] for num in range(0, 5 * 10, 5): response = client.get( f'/test_get_many?limit={limit}&offset={num}&order_by_columns=primary_key%20%3A%20DESC%20') response.headers['x-total-count'] == limit assert response.status_code == 200 _ = response.json() # test create a new data and get by primary key def test_create_new_data_and_get_by_primary_key(): sample_data = create_example_data(10) primary_key_list = [i[primary_key_name] for i in sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key} from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in response_data: assert i['primary_key'] in primary_key_list params = {"primary_key____from": min_key, "primary_key____to": max_key, "primary_key____from_____comparison_operator": 'Greater_than', "primary_key____to_____comparison_operator": 'Less_than'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 8 for i in response_data: assert i['primary_key'] in primary_key_list # test create a more than one data which value is TRUE of boolean type, and get many def test_create_a_more_than_one_data_which_value_is_TRUE_of_boolean_type_and_get_many(): bool_false_sample_data = create_example_data(5, bool_value=False) bool_true_sample_data = create_example_data(5, bool_value=True) primary_key_list = [i[primary_key_name] for i in bool_false_sample_data] + \ [i[primary_key_name] for i in bool_true_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "In", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) + f"&bool_value____list=False" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "In", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "In", "bool_value____list": False} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Equal", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) + f"&bool_value____list=False" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Equal", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Equal", "bool_value____list": False} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_in", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) + f"&bool_value____list=False" response = client.get(f'/test_get_many?{query_string}') assert response.status_code == 204 params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_in", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_in", "bool_value____list": False} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_equal", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) + f"&bool_value____list=False" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_equal", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_equal", "bool_value____list": False} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # test create a more than one data of char/text/varchar type, and get many def test_create_a_more_than_one_data_and_get_many_1(): char_str_sample_data = create_example_data(5, char_value='string') char_test_sample_data = create_example_data(5, char_value='test') primary_key_list = [i[primary_key_name] for i in char_str_sample_data] + \ [i[primary_key_name] for i in char_test_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) # match_regex_with_case_sensitive/ dose not match_regex_with_case_sensitive # def match_regex_with_case_sensitive(): # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'match_regex_with_case_sensitive', # "char_value____str": 'str.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # _ = response.json() # assert i in _ # for i in char_test_sample_data: # assert i not in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'match_regex_with_case_sensitive', # "char_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # # not_match_regex_with_case_sensitive # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', # "char_value____str": 'str.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', # "char_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i not in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'match_regex_with_case_sensitive', # "char_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'match_regex_with_case_insensitive', # "char_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', # "char_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', # "char_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # # def match_regex_with_case_insensitive(): # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'match_regex_with_case_insensitive', # "char_value____str": 'STR.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i not in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'match_regex_with_case_insensitive', # "char_value____str": 'TES.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # # does_not_match_regex_with_case_insensitive # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', # "char_value____str": 'STR.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', # "char_value____str": 'TES.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i not in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', # "char_value____str": 'TES.*'} # query_string = urlencode(OrderedDict(**params)) + "&char_value____str=STR.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', # "char_value____str": 'TES.*'} # query_string = urlencode(OrderedDict(**params)) + "&char_value____str=STR.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() def case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'case_sensitive', "char_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response_data # for i in char_test_sample_data: # assert i not in response_data params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'case_sensitive', "char_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # not_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_sensitive', "char_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_sensitive', "char_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_sensitive', "char_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=string" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_insensitive', "char_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=string" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() def case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'case_insensitive', "char_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'case_insensitive', "char_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_insensitive', "char_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_insensitive', "char_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_insensitive', "char_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_sensitive', "char_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # def similar_to(): # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'similar_to', # "char_value____str": 'string%'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i not in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'similar_to', # "char_value____str": 'test%'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # # not_case_insensitive # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'not_similar_to', # "char_value____str": 'string%'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'not_similar_to', # "char_value____str": 'test%'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i not in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'similar_to'} # query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str%&char_value____str=_es%" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "char_value____str_____matching_pattern": 'similar_to'} # query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str%&char_value____str=_es%" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # match_regex_with_case_sensitive() # match_regex_with_case_insensitive() case_sensitive() case_insensitive() # similar_to() # Varchar char_str_sample_data = create_example_data(5, varchar_value='string') char_test_sample_data = create_example_data(5, varchar_value='test') primary_key_list = [i[primary_key_name] for i in char_str_sample_data] + \ [i[primary_key_name] for i in char_test_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) # match_regex_with_case_sensitive/ dose not match_regex_with_case_sensitive # def match_regex_with_case_sensitive(): # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'match_regex_with_case_sensitive', # "varchar_value____str": 'str.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i not in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'match_regex_with_case_sensitive', # "varchar_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # for i in char_str_sample_data: # # assert i not in response.json() # # for i in char_test_sample_data: # # assert i in response.json() # # # not_match_regex_with_case_sensitive # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', # "varchar_value____str": 'str.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # for i in char_str_sample_data: # # assert i not in response.json() # # for i in char_test_sample_data: # # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', # "varchar_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i not in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'match_regex_with_case_sensitive', # "varchar_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'match_regex_with_case_insensitive', # "varchar_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i in response.json() # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', # "varchar_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', # "varchar_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i in response.json() # # def match_regex_with_case_insensitive(): # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'match_regex_with_case_insensitive', # "varchar_value____str": 'STR.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i not in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'match_regex_with_case_insensitive', # "varchar_value____str": 'TES.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # for i in char_str_sample_data: # # assert i not in response.json() # # for i in char_test_sample_data: # # assert i in response.json() # # # does_not_match_regex_with_case_insensitive # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', # "varchar_value____str": 'STR.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # for i in char_str_sample_data: # # assert i not in response.json() # # for i in char_test_sample_data: # # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', # "varchar_value____str": 'TES.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i not in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', # "varchar_value____str": 'TES.*'} # query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=STR.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', # "varchar_value____str": 'TES.*'} # query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=STR.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i in response.json() def case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # not_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_sensitive', "varchar_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_sensitive', "varchar_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_sensitive', "varchar_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=strinG" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_insensitive', "varchar_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=string" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() def case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'case_insensitive', "varchar_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'case_insensitive', "varchar_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_insensitive', "varchar_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_insensitive', "varchar_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_insensitive', "varchar_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_sensitive', "varchar_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # def similar_to(): # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'similar_to', # "varchar_value____str": 'string%'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i not in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'similar_to', # "varchar_value____str": 'test%'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # for i in char_str_sample_data: # # assert i not in response.json() # # for i in char_test_sample_data: # # assert i in response.json() # # # not_case_insensitive # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'not_similar_to', # "varchar_value____str": 'string%'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # for i in char_str_sample_data: # # assert i not in response.json() # # for i in char_test_sample_data: # # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'not_similar_to', # "varchar_value____str": 'test%'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i not in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'similar_to'} # query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str%&varchar_value____str=_es%" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # # for i in char_str_sample_data: # # assert i in response.json() # # for i in char_test_sample_data: # # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "varchar_value____str_____matching_pattern": 'similar_to'} # query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str%&varchar_value____str=_es%" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # match_regex_with_case_sensitive() # match_regex_with_case_insensitive() case_sensitive() case_insensitive() # similar_to() # Text char_str_sample_data = create_example_data(5, text_value='string') char_test_sample_data = create_example_data(5, text_value='test') primary_key_list = [i[primary_key_name] for i in char_str_sample_data] + \ [i[primary_key_name] for i in char_test_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) # match_regex_with_case_sensitive/ dose not match_regex_with_case_sensitive # def match_regex_with_case_sensitive(): # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'match_regex_with_case_sensitive', # "text_value____str": 'str.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'match_regex_with_case_sensitive', # "text_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # # not_match_regex_with_case_sensitive # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', # "text_value____str": 'str.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', # "text_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'match_regex_with_case_sensitive', # "text_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'match_regex_with_case_insensitive', # "text_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', # "text_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', # "text_value____str": 'tes.*'} # query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # def match_regex_with_case_insensitive(): # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'match_regex_with_case_insensitive', # "text_value____str": 'STR.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'match_regex_with_case_insensitive', # "text_value____str": 'TES.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # # does_not_match_regex_with_case_insensitive # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', # "text_value____str": 'STR.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', # "text_value____str": 'TES.*'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', # "text_value____str": 'TES.*'} # query_string = urlencode(OrderedDict(**params)) + "&text_value____str=STR.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', # "text_value____str": 'TES.*'} # query_string = urlencode(OrderedDict(**params)) + "&text_value____str=STR.*" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() def case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'case_sensitive', "text_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'case_sensitive', "text_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # not_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_sensitive', "text_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_sensitive', "text_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_sensitive', "text_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=string" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_insensitive', "text_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=string" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 def case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'case_insensitive', "text_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'case_insensitive', "text_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_insensitive', "text_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_insensitive', "text_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_insensitive', "text_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_sensitive', "text_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 # def similar_to(): # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'similar_to', # "text_value____str": 'string%'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'similar_to', # "text_value____str": 'test%'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # # not_case_insensitive # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'not_similar_to', # "text_value____str": 'string%'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # for i in char_str_sample_data: # assert i not in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'not_similar_to', # "text_value____str": 'test%'} # query_string = urlencode(OrderedDict(**params)) # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 5 # # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'similar_to'} # query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str%&text_value____str=_es%" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # # params = {"primary_key____from": min_key, # "primary_key____to": max_key, # "text_value____str_____matching_pattern": 'similar_to'} # query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str%&text_value____str=_es%" # response = client.get(f'/test_get_many?{query_string}') # response_data = response.json() # assert len(response_data) == 10 # for i in char_str_sample_data: # assert i in response.json() # for i in char_test_sample_data: # assert i in response.json() # match_regex_with_case_sensitive() # match_regex_with_case_insensitive() case_sensitive() case_insensitive() # similar_to() # test create a more than one data of float4/text/varchar type, and get many def test_create_a_more_than_one_data_and_get_many_2(): float_one = 5.5 float_two = 10.7 # float 4 <= will round down to the odd floating even # data = 0.4 # <= 0.4 # result = [] # data = 0.4 # <= 0.5 # result = [0.4] num_one_sample_data = create_example_data(5, float4_value=float_one) num_two_sample_data = create_example_data(5, float4_value=float_two) primary_key_list = [i[primary_key_name] for i in num_one_sample_data] + \ [i[primary_key_name] for i in num_two_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) def greater_than_or_equal_to_Less_than_or_equal_to(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "float4_value____from_____comparison_operator": 'Greater_than_or_equal_to', "float4_value____to_____comparison_operator": 'Less_than_or_equal_to', "float4_value____from": float_one, "float4_value____to": float_two} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 # data = 10.7 # < 10.7 # still got 10.7 but if data is 10.6 def less_than_or_equal_to_less_than(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "float4_value____from_____comparison_operator": 'Greater_than', "float4_value____to_____comparison_operator": 'Less_than', "float4_value____from": float_one, "float4_value____to": float_two + 0.1} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 greater_than_or_equal_to_Less_than_or_equal_to() less_than_or_equal_to_less_than() # float 4 < will round down to the odd floating odd # data = 0.3 # <= 0.4 # result = [] # data = 0.4 # <= 0.5 # result = [0.4] float_one = 5.5 float_two = 10.6 num_one_sample_data = create_example_data(5, float8_value=float_one) num_two_sample_data = create_example_data(5, float8_value=float_two) primary_key_list = [i[primary_key_name] for i in num_one_sample_data] + \ [i[primary_key_name] for i in num_two_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) def greater_than_or_equal_to_Less_than_or_equal_to(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "float8_value____from_____comparison_operator": 'Greater_than_or_equal_to', "float8_value____to_____comparison_operator": 'Less_than_or_equal_to', "float8_value____from": float_one, "float8_value____to": float_two} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 def less_than_or_equal_to_less_than(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "float8_value____from_____comparison_operator": 'Greater_than', "float8_value____to_____comparison_operator": 'Less_than', "float8_value____from": float_one, "float8_value____to": float_two + 0.1} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 greater_than_or_equal_to_Less_than_or_equal_to() less_than_or_equal_to_less_than() def test_get_many_with_ordering_unknown_column(): try: response = client.get(f'/test_get_many?order_by_columns=testestset') except UnknownColumn as e: assert str(e) == "column testestset is not exited" return assert False def test_get_many_with_ordering_with_default_order(): response = client.get(f'/test_get_many?order_by_columns=primary_key&limit=10&offset=0') a = response.json() init = 1 for i in a: assert i['primary_key'] == init init += 1 def test_get_many_with_ordering_with_ASC(): response = client.get(f'/test_get_many?order_by_columns=primary_key:ASC&limit=10&offset=0') a = response.json() init = 1 for i in a: assert i['primary_key'] == init init += 1 def test_get_many_with_ordering_with_DESC(): response = client.get(f'/test_get_many?order_by_columns=primary_key:DESC&limit=10&offset=10') a = response.json() init = a[0]['primary_key'] for i in a: assert i['primary_key'] == init init -= 1 def test_get_many_with_unknown_order_tyoe(): try: response = client.get(f'/test_get_many?order_by_columns=primary_key:DESCSS&limit=10&offset=0') except UnknownOrderType as e: assert str(e) == 'Unknown order type DESCSS, only accept DESC or ASC' return assert False def test_get_many_with_ordering_with_empty_input_list(): try: response = client.get(f'/test_get_many?order_by_columns=') except Exception as e: assert False assert True ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/test_get_one_api.py ================================================ import json from starlette.testclient import TestClient from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_memory_sqlalchemy.api_test import app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_one = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_get_data = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", tags=["test"] ) [app.include_router(i) for i in [test_get_data, test_create_one]] client = TestClient(app) # create a sample data headers = { 'accept': '*/*', 'Content-Type': 'application/json', } data = '{ "bool_value": true, "char_value": "string", "date_value": "2021-07-26", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-26T02:17:46.846Z", "timestamptz_value": "2021-07-26T02:17:46.846Z", "timetz_value": "18:18:18+00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }' response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_data = response.json() dict_data = json.loads(data) sample_primary_key = response_data['primary_key'] ''' { "primary_key": 1013, "interval_value": 0, <- querying not supported "json_value": {},<- querying not supported "jsonb_value": {},<- querying not supported "array_value": [ 0 ], "array_str__value": [ "string" ] } ''' # try find the data by primary key def test_get_by_primary_key_without_any_query_param(): response = client.get(f'/test/{sample_primary_key}', headers=headers) assert response.status_code == 200 assert response.json()['primary_key'] == sample_primary_key # "bool_value": true # try find the data by primary key but false by bool def test_get_by_primary_key_with_false_bool_query_param(): response = client.get(f'/test/{sample_primary_key}?bool_value____list=false', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?bool_value____list=true', headers=headers) assert response.status_code == 200 # "char_value": "string ", # try find the data by primary key but false by char def test_get_by_primary_key_with_false_char_query_param(): response = client.get(f'/test/{sample_primary_key}?char_value____list=string1&char_value____list=string2', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?char_value____list=string&char_value____list=string1&', headers=headers) assert response.status_code == 200 # Like operator response = client.get( f'/test/{sample_primary_key}?char_value____str=string1&char_value____str=%tri%&char_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 200 # sql lite response = client.get( f'/test/{sample_primary_key}?char_value____str=string1&char_value____str=%Tri%&char_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=string1&char_value____str=%tsri%&char_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 404 # Ilike operator response = client.get( f'/test/{sample_primary_key}?char_value____str=string1&char_value____str=%tRi%&char_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=string1&char_value____str=%tsri%&char_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 404 # not like operator response = client.get( f'/test/{sample_primary_key}?char_value____str=string2&char_value____str=%strg%&char_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=string%&char_value____str=%strin%&char_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 404 # not ilike operator response = client.get( f'/test/{sample_primary_key}?char_value____str=String2&char_value____str=%Strg%&char_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=STRING%&char_value____str=%TRI%&char_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 404 # match regex with case sensitive operator # response = client.get( # f'/test/{sample_primary_key}?char_value____str=stri.*&varchar_value____stg=str&char_value____str_____matching_pattern=match_regex_with_case_sensitive', # headers=headers) # assert response.status_code == 200 # response = client.get( # f'/test/{sample_primary_key}?char_value____str=stg.*&char_value____str=stg&char_value____str_____matching_pattern=match_regex_with_case_sensitive', # headers=headers) # assert response.status_code == 404 # match regex with case insensitive operator # response = client.get( # f'/test/{sample_primary_key}?char_value____str=strI.*&char_value____str=STG&char_value____str_____matching_pattern=match_regex_with_case_insensitive', # headers=headers) # assert response.status_code == 200 # response = client.get( # f'/test/{sample_primary_key}?char_value____str=stG.*&char_value____str=STG&char_value____str_____matching_pattern=match_regex_with_case_insensitive', # headers=headers) # assert response.status_code == 404 # does_not_match_regex_with_case_insensitive # response = client.get( # f'/test/{sample_primary_key}?char_value____str=strI.*&char_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', # headers=headers) # assert response.status_code == 404 # response = client.get( # f'/test/{sample_primary_key}?char_value____str=stG.*&char_value____str=STG&char_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', # headers=headers) # assert response.status_code == 200 # dose not match regex with case sensitive operator # response = client.get( # f'/test/{sample_primary_key}?char_value____str=stri.*&varchar_value____stg=str&char_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', # headers=headers) # assert response.status_code == 404 # response = client.get( # f'/test/{sample_primary_key}?char_value____str=stg.*&char_value____str=stg&char_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', # headers=headers) # assert response.status_code == 200 # similar_to # response = client.get( # f'/test/{sample_primary_key}?char_value____str=string&char_value____str=%(r|z)%&char_value____str_____matching_pattern=similar_to', # headers=headers) # assert response.status_code == 200 # response = client.get( # f'/test/{sample_primary_key}?char_value____str=str&char_value____str=(r|z)%&char_value____str_____matching_pattern=similar_to', # headers=headers) # assert response.status_code == 404 # not_similar_to # response = client.get( # f'/test/{sample_primary_key}?char_value____str=string%&char_value____str=%(r|z)%&char_value____str_____matching_pattern=not_similar_to', # headers=headers) # assert response.status_code == 404 # response = client.get( # f'/test/{sample_primary_key}?char_value____str=str&char_value____str=(r|z)%&char_value____str_____matching_pattern=not_similar_to', # headers=headers) # assert response.status_code == 200 # "float4_value": 0, # try find the data by primary key but false by float4 def test_get_by_primary_key_with_false_float4_query_param(): # from response = client.get(f'/test/{sample_primary_key}?float4_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?float4_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??float4_value____from=-2&float4_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?float4_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?float4_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?float4_value____from=0&float4_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?float4_value____from=0&float4_value____to=0&float4_value____from_____comparison_operator=Greater_than_or_equal_to&float4_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?float4_value____from=-1&float4_value____to=2&float4_value____from_____comparison_operator=Greater_than&float4_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?float4_value____from=1&float4_value____to=2&float4_value____from_____comparison_operator=Greater_than&float4_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?float4_value____from=1&float4_value____to=2&float4_value____from_____comparison_operator=Greater_than_or_equal_to&float4_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # "float8_value": 0, # try find the data by primary key but false by float8 def test_get_by_primary_key_with_false_float8_query_param(): # from response = client.get(f'/test/{sample_primary_key}?float8_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?float8_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??float8_value____from=-2&float8_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?float8_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?float8_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?float8_value____from=0&float8_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?float8_value____from=0&float8_value____to=0&float8_value____from_____comparison_operator=Greater_than_or_equal_to&float8_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?float8_value____from=-1&float8_value____to=2&float8_value____from_____comparison_operator=Greater_than&float8_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?float8_value____from=1&float8_value____to=2&float8_value____from_____comparison_operator=Greater_than&float8_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?float8_value____from=1&float8_value____to=2&float8_value____from_____comparison_operator=Greater_than_or_equal_to&float8_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by int2 # int2 0 def test_get_by_primary_key_with_false_int2_query_param(): # from response = client.get(f'/test/{sample_primary_key}?int2_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?int2_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??int2_value____from=-2&int2_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?int2_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?int2_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?int2_value____from=0&int2_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int2_value____from=0&int2_value____to=0&int2_value____from_____comparison_operator=Greater_than_or_equal_to&int2_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int2_value____from=-1&int2_value____to=2&int2_value____from_____comparison_operator=Greater_than&int2_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int2_value____from=1&int2_value____to=2&int2_value____from_____comparison_operator=Greater_than&int2_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int2_value____from=1&int2_value____to=2&int2_value____from_____comparison_operator=Greater_than_or_equal_to&int2_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by int4 # int 4 0 def test_get_by_primary_key_with_false_int4_query_param(): # from response = client.get(f'/test/{sample_primary_key}?int4_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?int4_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??int4_value____from=-2&int4_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?int4_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?int4_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?int4_value____from=0&int4_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int4_value____from=0&int4_value____to=0&int4_value____from_____comparison_operator=Greater_than_or_equal_to&int4_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int4_value____from=-1&int4_value____to=2&int4_value____from_____comparison_operator=Greater_than&int4_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int4_value____from=1&int4_value____to=2&int4_value____from_____comparison_operator=Greater_than&int4_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int4_value____from=1&int4_value____to=2&int4_value____from_____comparison_operator=Greater_than_or_equal_to&int4_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by int8 # int 8 0 def test_get_by_primary_key_with_false_int8_query_param(): # from response = client.get(f'/test/{sample_primary_key}?int8_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?int8_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??int8_value____from=-2&int8_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?int8_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?int8_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?int8_value____from=0&int8_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int8_value____from=0&int8_value____to=0&int8_value____from_____comparison_operator=Greater_than_or_equal_to&int8_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int8_value____from=-1&int8_value____to=2&int8_value____from_____comparison_operator=Greater_than&int8_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int8_value____from=1&int8_value____to=2&int8_value____from_____comparison_operator=Greater_than&int8_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int8_value____from=1&int8_value____to=2&int8_value____from_____comparison_operator=Greater_than_or_equal_to&int8_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by numeric # numeric 0 def test_get_by_primary_key_with_false_numeric_query_param(): # from response = client.get(f'/test/{sample_primary_key}?numeric_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?numeric_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??numeric_value____from=-2&numeric_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?numeric_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?numeric_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?numeric_value____from=0&numeric_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?numeric_value____from=0&numeric_value____to=0&numeric_value____from_____comparison_operator=Greater_than_or_equal_to&numeric_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?numeric_value____from=-1&numeric_value____to=2&numeric_value____from_____comparison_operator=Greater_than&numeric_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?numeric_value____from=1&numeric_value____to=2&numeric_value____from_____comparison_operator=Greater_than&numeric_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?numeric_value____from=1&numeric_value____to=2&numeric_value____from_____comparison_operator=Greater_than_or_equal_to&numeric_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by text # "text_value": "string", def test_get_by_primary_key_with_false_text_query_param(): response = client.get(f'/test/{sample_primary_key}?text_value____list=string1&text_value____list=string2', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?text_value____list=string&text_value____list=string1&', headers=headers) assert response.status_code == 200 # Like operator response = client.get(f'/test/{sample_primary_key}?text_value____str=string1&text_value____str=%tri%&text_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?text_value____str=string1&text_value____str=%tsri%&text_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 404 # Ilike operator response = client.get(f'/test/{sample_primary_key}?text_value____str=string1&text_value____str=%tRi%&text_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?text_value____str=string1&text_value____str=%tsri%&text_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 404 # not like operator response = client.get(f'/test/{sample_primary_key}?text_value____str=string2&text_value____str=%strg%&text_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?text_value____str=string&text_value____str=%strin%&text_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 404 # not ilike operator response = client.get(f'/test/{sample_primary_key}?text_value____str=String2&text_value____str=%Strg%&text_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?text_value____str=STRING&text_value____str=%TRI%&text_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 404 # match regex with case sensitive operator # response = client.get(f'/test/{sample_primary_key}?text_value____str=stri.*&varchar_value____stg=str&text_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) # assert response.status_code == 200 # response = client.get(f'/test/{sample_primary_key}?text_value____str=stg.*&text_value____str=stg&text_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) # assert response.status_code == 404 # match regex with case insensitive operator # response = client.get(f'/test/{sample_primary_key}?text_value____str=strI.*&text_value____str=STG&text_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) # assert response.status_code == 200 # response = client.get(f'/test/{sample_primary_key}?text_value____str=stG.*&text_value____str=STG&text_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) # assert response.status_code == 404 # does_not_match_regex_with_case_insensitive # response = client.get(f'/test/{sample_primary_key}?text_value____str=strI.*&text_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) # assert response.status_code == 404 # response = client.get(f'/test/{sample_primary_key}?text_value____str=stG.*&text_value____str=STG&text_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) # assert response.status_code == 200 # dose not match regex with case sensitive operator # response = client.get(f'/test/{sample_primary_key}?text_value____str=stri.*&varchar_value____stg=str&text_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) # assert response.status_code == 404 # response = client.get(f'/test/{sample_primary_key}?text_value____str=stg.*&text_value____str=stg&text_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) # assert response.status_code == 200 # similar_to # response = client.get(f'/test/{sample_primary_key}?text_value____str=string&text_value____str=%(r|z)%&text_value____str_____matching_pattern=similar_to', headers=headers) # assert response.status_code == 200 # response = client.get(f'/test/{sample_primary_key}?text_value____str=str&text_value____str=(r|z)%&text_value____str_____matching_pattern=similar_to', headers=headers) # assert response.status_code == 404 # not_similar_to # response = client.get(f'/test/{sample_primary_key}?text_value____str=string&text_value____str=%(r|z)%&text_value____str_____matching_pattern=not_similar_to', headers=headers) # assert response.status_code == 404 # response = client.get(f'/test/{sample_primary_key}?text_value____str=str&text_value____str=(r|z)%&text_value____str_____matching_pattern=not_similar_to', headers=headers) # assert response.status_code == 200 # try find the data by primary key but false by uuid # def test_get_by_primary_key_with_false_uuid_query_param(): # # In operator # response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa6&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9', headers=headers) # assert response.status_code == 200 # response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afb6', headers=headers) # assert response.status_code == 404 # # not In operator # response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa6&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list_____comparison_operator=Not_in', headers=headers) # assert response.status_code == 404 # response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afb6&uuid_value____list_____comparison_operator=Not_in', headers=headers) # assert response.status_code == 200 # # Equal operator # response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa6&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list_____comparison_operator=Equal', headers=headers) # assert response.status_code == 200 # response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afb6&uuid_value____list_____comparison_operator=Equal', headers=headers) # assert response.status_code == 404 # # not Equal operator # response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa6&uuid_value____list_____comparison_operator=Not_equal', headers=headers) # assert response.status_code == 404 # response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afb6&uuid_value____list_____comparison_operator=Not_equal', headers=headers) # assert response.status_code == 200 # try find the data by primary key but false by varchar def test_get_by_primary_key_with_false_varchar_query_param(): response = client.get(f'/test/{sample_primary_key}?varchar_value____list=string1&varchar_value____list=string2', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?varchar_value____list=string&varchar_value____list=string1&', headers=headers) assert response.status_code == 200 # Like operator response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string1&varchar_value____str=%tri%&varchar_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string1&varchar_value____str=%tsri%&varchar_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 404 # Ilike operator response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string1&varchar_value____str=%tRi%&varchar_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string1&varchar_value____str=%tsri%&varchar_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 404 # not like operator response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string2&varchar_value____str=%strg%&varchar_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string&varchar_value____str=%strin%&varchar_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 404 # not ilike operator response = client.get(f'/test/{sample_primary_key}?varchar_value____str=String2&varchar_value____str=%Strg%&varchar_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=STRING&varchar_value____str=%TRI%&varchar_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 404 # match regex with case sensitive operator # response = client.get(f'/test/{sample_primary_key}?varchar_value____str=stri.*&varchar_value____stg=str&varchar_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) # assert response.status_code == 200 # response = client.get(f'/test/{sample_primary_key}?varchar_value____str=stg.*&varchar_value____str=stg&varchar_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) # assert response.status_code == 404 # match regex with case insensitive operator # response = client.get(f'/test/{sample_primary_key}?varchar_value____str=strI.*&varchar_value____str=STG&varchar_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) # assert response.status_code == 200 # response = client.get(f'/test/{sample_primary_key}?varchar_value____str=stG.*&varchar_value____str=STG&varchar_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) # assert response.status_code == 404 # does_not_match_regex_with_case_insensitive # response = client.get(f'/test/{sample_primary_key}?varchar_value____str=strI.*&varchar_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) # assert response.status_code == 404 # response = client.get(f'/test/{sample_primary_key}?varchar_value____str=stG.*&varchar_value____str=STG&varchar_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) # assert response.status_code == 200 # dose not match regex with case sensitive operator # response = client.get(f'/test/{sample_primary_key}?varchar_value____str=stri.*&varchar_value____stg=str&varchar_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) # assert response.status_code == 404 # response = client.get(f'/test/{sample_primary_key}?varchar_value____str=stg.*&varchar_value____str=stg&varchar_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) # assert response.status_code == 200 # similar_to # response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string&varchar_value____str=%(r|z)%&varchar_value____str_____matching_pattern=similar_to', headers=headers) # assert response.status_code == 200 # response = client.get(f'/test/{sample_primary_key}?varchar_value____str=str&varchar_value____str=(r|z)%&varchar_value____str_____matching_pattern=similar_to', headers=headers) # assert response.status_code == 404 # not_similar_to # response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string&varchar_value____str=%(r|z)%&varchar_value____str_____matching_pattern=not_similar_to', headers=headers) # assert response.status_code == 404 # response = client.get(f'/test/{sample_primary_key}?varchar_value____str=str&varchar_value____str=(r|z)%&varchar_value____str_____matching_pattern=not_similar_to', headers=headers) # assert response.status_code == 200 # query by range of date field def test_get_by_primary_key_with_false_date_range_query_param(): # from response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-27', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?date_value____to=2021-07-24', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??date_value____from=2021-07-21&date_value____to=2021-07-24', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-24', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?date_value____to=2021-07-27', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-24&date_value____to=2021-07-27', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-26&date_value____to=2021-07-26&date_value____from_____comparison_operator=Greater_than_or_equal_to&date_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-25&date_value____to=2021-07-27&date_value____from_____comparison_operator=Greater_than&date_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-26&date_value____to=2021-07-26&date_value____from_____comparison_operator=Greater_than&date_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-27&date_value____to=2021-07-29&date_value____from_____comparison_operator=Greater_than_or_equal_to&date_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 def test_get_by_primary_key_with_false_time_range_query_param(): # from response = client.get(f'/test/{sample_primary_key}?time_value____from=19:18:18', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?time_value____to=17:18:18', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}?time_value____from=10:18:18&time_value____to=17:18:18', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?time_value____from=10:18:18', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?time_value____to=19:18:18', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?time_value____from=10:18:18&time_value____to=19:18:18', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?time_value____from=18:18:18&time_value____to=18:18:18&time_value____from_____comparison_operator=Greater_than_or_equal_to&time_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?time_value____from=18:18:17&time_value____to=18:18:19&time_value____from_____comparison_operator=Greater_than&time_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?time_value____from=18:18:18&time_value____to=18:18:18&time_value____from_____comparison_operator=Greater_than&time_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?time_value____from=19:18:18&time_value____to=19:19:18&time_value____from_____comparison_operator=Greater_than_or_equal_to&time_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 def test_get_by_primary_key_with_false_timestamp_range_query_param(): # "timestamp_value": "2021-07-26T02:17:46.846000", # from response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-27T02:17:46.846000', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?timestamp_value____to=2021-07-25T02:17:46.846000', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-20T02:17:46.846000×tamp_value____to=2021-07-25T02:17:46.846000', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-24T02:17:46.846000', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?timestamp_value____to=2021-07-28T02:17:46.846000', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-24T02:17:46.846000×tamp_value____to=2021-07-28T02:17:46.846000', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-26T02:17:46.846×tamp_value____to=2021-07-26T02:17:46.846Z×tampt_value____from_____comparison_operator=Greater_than_or_equal_to×tampt_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-26T02:17:46.746Z×tamp_value____to=2021-07-26T02:17:46.946Z×tampt_value____from_____comparison_operator=Greater_than×tampt_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-26T02:17:46.846Z×tamp_value____to=2021-07-26T02:17:46.946Z×tamp_value____from_____comparison_operator=Greater_than×tamp_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-26T02:17:46.856Z×tamp_value____to=2021-07-26T02:17:46.986Z×tamp_value____from_____comparison_operator=Greater_than_or_equal_to×tamp_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 def test_get_by_primary_key_with_false_timetz_range_query_param(): # from response = client.get(f'/test/{sample_primary_key}?timetz_value____from=19%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?timetz_value____to=17%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}?timetz_value____from=16%3A18%3A18%2B00%3A00&timetz_value____to=17%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?timetz_value____from=17%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?timetz_value____to=19%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?timetz_value____from=16%3A18%3A18%2B00%3A00&timetz_value____to=19%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timetz_value____from_____comparison_operator=Greater_than&timetz_value____to_____comparison_operator=Less_than&timetz_value____from=17%3A18%3A18%2B00&timetz_value____to=19%3A18%3A18%2B00', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timetz_value____from_____comparison_operator=Greater_than_or_equal_to&timetz_value____to_____comparison_operator=Less_than_or_equal_to&timetz_value____from=18%3A18%3A18%2B00&timetz_value____to=18%3A19%3A18%2B00', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timetz_value____from_____comparison_operator=Greater_than&timetz_value____to_____comparison_operator=Less_than&timetz_value____from=16%3A18%3A18%2B00&timetz_value____to=18%3A18%3A18%2B00', headers=headers) assert response.status_code == 404 # failure from - to with special operator response = client.get(f'/test/{sample_primary_key}?timetz_value____from_____comparison_operator=Greater_than_or_equal_to&timetz_value____to_____comparison_operator=Less_than_or_equal_to&timetz_value____from=16%3A18%3A18%2B00&timetz_value____to=17%3A19%3A18%2B00', headers=headers) assert response.status_code == 404 def test_get_by_primary_key_with_false_timestamptz_range_query_param(): # "timestamp_value": "2021-07-26T02:17:46.846000", # from response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-27T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?timestamptz_value____to=2021-07-25T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-27T02%3A17%3A46.846000%2B00%3A00×tamptz_value____to=2021-07-28T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-20T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?timestamptz_value____to=2021-07-29T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-20T02%3A17%3A46.846000%2B00%3A00×tamptz_value____to=2021-07-27T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-26T02%3A17%3A46.846Z×tamptz_value____to=2021-07-26T02%3A17%3A46.846Z×tamptz_value____from_____comparison_operator=Greater_than_or_equal_to×tamptz_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-26T02%3A17%3A46.800Z×tamptz_value____to=2021-07-26T02%3A17%3A46.946Z×tamptz_value____from_____comparison_operator=Greater_than×tamptz_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-26T02%3A17%3A46.846Z×tamptz_value____to=2021-07-26T02%3A17%3A46.900Z×tamptz_value____from_____comparison_operator=Greater_than×tamptz_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-26T02%3A17%3A46.847Z×tamptz_value____to=2021-07-26T02%3A17%3A46.946Z×tamptz_value____from_____comparison_operator=Greater_than_or_equal_to×tamptz_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/test_other_default_value.py ================================================ import json import os from datetime import datetime, timezone, date, timedelta from http import HTTPStatus from urllib.parse import urlencode from fastapi import FastAPI from sqlalchemy import BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text, func from sqlalchemy.orm import declarative_base from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata class UUIDTable(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_default_value_sync' __table_args__ = ( UniqueConstraint('primary_key', 'int4_value', 'float4_value'), ) primary_key = Column(Integer, primary_key=True, info={'alias_name': 'primary_key'}, autoincrement=True) bool_value = Column(Boolean, nullable=False, default=False) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=func.now()) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) varchar_value = Column(String) model_1 = sqlalchemy_to_pydantic(UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.FIND_MANY, CrudMethods.CREATE_MANY, CrudMethods.UPDATE_ONE, CrudMethods.UPDATE_MANY, CrudMethods.PATCH_MANY, CrudMethods.PATCH_ONE, CrudMethods.DELETE_MANY, CrudMethods.DELETE_ONE, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) route_1 = crud_router_builder(db_model=UUIDTable, crud_models=model_1, prefix="/test", tags=["test"] ) model_2 = sqlalchemy_to_pydantic(UUIDTable, crud_methods=[ CrudMethods.CREATE_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) route_2 = crud_router_builder(db_model=UUIDTable, crud_models=model_2, prefix="/test_2", tags=["test"] ) model_3 = sqlalchemy_to_pydantic(UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) route_3 = crud_router_builder(db_model=UUIDTable, crud_models=model_3, prefix="/test_3", tags=["test"] ) [app.include_router(i) for i in [route_1, route_2, route_3]] client = TestClient(app) def test_get_one_data_and_create_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() find_target = create_response['primary_key'] response = client.get(f'/test/{find_target}', headers=headers, data=data) assert response.status_code == 200 assert response.json() == create_response create_response.pop('primary_key') query_param = urlencode(create_response) response = client.get(f'/test/{find_target}?{query_param}', headers=headers, data=data) assert response.status_code == 200 def test_get_many_data_and_create_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = ''' [ { "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00","varchar_value": "string" }, { "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string"},{ "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string"} ] ''' data_dict = json.loads(data) response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_dict): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_update_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() created_primary_key = create_response['primary_key'] update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} query_param = urlencode(update_data) response = client.put(f'/test/{created_primary_key}?{query_param}', data=json.dumps(update_data)) update_data["bool_value"] = False response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_update_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [{"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test?{query_string}', data=json.dumps(update_data)) update_data["bool_value"] = False response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: assert k[i] == update_data[i] def test_patch_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) update_data = {"bool_value": False} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(params) update_data = {"char_value": "string_u "} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(params) update_data = {"date_value": "2022-07-24"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(params) update_data = {"char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) update_data['bool_value'] = False response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_patch_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [{"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value": True, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test?{query_string}', data=json.dumps(update_data)) update_data['bool_value'] = True response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_delete_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) response = client.delete(f'/test/{primary_key}?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_delete_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [{"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' response = client.delete(f'/test?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_post_redirect_get_data(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19.0 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_3', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() response_data['bool_value'] = False assert 'primary_key' in response_data return response_data def test_upsert_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 10 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k, v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/test_other_set_description.py ================================================ import json import os import uuid from copy import deepcopy from datetime import datetime, timezone, date, timedelta from http import HTTPStatus from urllib.parse import urlencode from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text, func from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine class UUIDTable(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_default_value_sync' __table_args__ = ( UniqueConstraint('primary_key', 'int4_value', 'float4_value'), ) primary_key=Column(Integer, primary_key=True, autoincrement=True) bool_value = Column(Boolean, nullable=False, default=False) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=func.now()) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) varchar_value = Column(String) model_1 = sqlalchemy_to_pydantic(UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.FIND_MANY, CrudMethods.CREATE_MANY, CrudMethods.UPDATE_ONE, CrudMethods.UPDATE_MANY, CrudMethods.PATCH_MANY, CrudMethods.PATCH_ONE, CrudMethods.DELETE_MANY, CrudMethods.DELETE_ONE, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) route_1 = crud_router_builder(db_model=UUIDTable, crud_models=model_1, prefix="/test", tags=["test"] ) model_2 = sqlalchemy_to_pydantic(UUIDTable, crud_methods=[ CrudMethods.CREATE_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) route_2 = crud_router_builder(db_model=UUIDTable, crud_models=model_2, prefix="/test_2", tags=["test"] ) model_3 = sqlalchemy_to_pydantic(UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) route_3 = crud_router_builder(db_model=UUIDTable, crud_models=model_3, prefix="/test_3", tags=["test"] ) [app.include_router(i) for i in [route_1, route_2, route_3]] client = TestClient(app) def test_get_one_data_and_create_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() find_target = create_response['primary_key'] response = client.get(f'/test/{find_target}', headers=headers, data=data) assert response.status_code == 200 assert response.json() == create_response create_response.pop('primary_key') query_param = urlencode(create_response) response = client.get(f'/test/{find_target}?{query_param}', headers=headers, data=data) assert response.status_code == 200 def test_get_many_data_and_create_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '''[ { "char_value":"string ", "date_value":"2021-07-23", "float4_value":0, "float8_value":0, "int2_value":0, "int4_value":0, "int8_value":0, "numeric_value":0, "text_value":"string", "timestamp_value":"2021-07-23T02:38:24.963000", "timestamptz_value":"2021-07-23T02:38:24.963000+00:00", "varchar_value":"string" }, { "char_value":"string ", "date_value":"2021-07-23", "float4_value":0, "float8_value":0, "int2_value":0, "int4_value":0, "int8_value":0, "numeric_value":0, "text_value":"string", "timestamp_value":"2021-07-23T02:38:24.963000", "timestamptz_value":"2021-07-23T02:38:24.963000+00:00", "varchar_value":"string" }, { "char_value":"string ", "date_value":"2021-07-23", "float4_value":0, "float8_value":0, "int2_value":0, "int4_value":0, "int8_value":0, "numeric_value":0, "text_value":"string", "timestamp_value":"2021-07-23T02:38:24.963000", "timestamptz_value":"2021-07-23T02:38:24.963000+00:00", "varchar_value":"string" } ] ''' data_dict = json.loads(data) response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_dict): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_update_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() created_primary_key = create_response['primary_key'] update_data = { "bool_value":False,"char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} query_param = urlencode(update_data) response = client.put(f'/test/{created_primary_key}?{query_param}', data=json.dumps(update_data)) update_data["bool_value"] = False response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_update_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [{"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, { "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params)+f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value":False,"char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test?{query_string}', data=json.dumps(update_data)) update_data["bool_value"] = False response_data = response.json() assert len(response_data) == 3 def test_patch_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) update_data = {"bool_value": False} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(params) update_data = {"char_value": "string_u "} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(params) update_data = {"date_value": "2022-07-24"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(params) update_data = {"char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) update_data['bool_value'] = False response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_patch_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [{"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, { "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0,"numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value": True, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00","varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test?{query_string}', data=json.dumps(update_data)) update_data['bool_value'] = True response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_delete_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) response = client.delete(f'/test/{primary_key}?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_delete_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [{ "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, { "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, { "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' response = client.delete(f'/test?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_post_redirect_get_data(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19.0 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_3', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() response_data['bool_value'] = False assert 'primary_key' in response_data return response_data def test_upsert_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 10 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k,v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/test_other_single_unique.py ================================================ import json import os import uuid from copy import deepcopy from datetime import datetime, timezone, date, timedelta from http import HTTPStatus from urllib.parse import urlencode from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text, func from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine class UUIDTable(Base): __tablename__ = 'test_single_unique_table_model' id = Column(Integer, primary_key=True, autoincrement=True) bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=func.now()) float4_value = Column(Float, nullable=False,unique=True) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=True) int4_value = Column(Integer, nullable=True) int8_value = Column(BigInteger, server_default=text("99")) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) varchar_value = Column(String) model_1 = sqlalchemy_to_pydantic(UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.FIND_MANY, CrudMethods.CREATE_MANY, CrudMethods.UPDATE_ONE, CrudMethods.UPDATE_MANY, CrudMethods.PATCH_MANY, CrudMethods.PATCH_ONE, CrudMethods.DELETE_MANY, CrudMethods.DELETE_ONE, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) route_1 = crud_router_builder(db_model=UUIDTable, crud_models=model_1, prefix="/test", tags=["test"] ) model_2 = sqlalchemy_to_pydantic(UUIDTable, crud_methods=[ CrudMethods.CREATE_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) route_2 = crud_router_builder(db_model=UUIDTable, crud_models=model_2, prefix="/test_2", tags=["test"] ) model_3 = sqlalchemy_to_pydantic(UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) route_3 = crud_router_builder(db_model=UUIDTable, crud_models=model_3, prefix="/test_3", tags=["test"] ) [app.include_router(i) for i in [route_1, route_2, route_3]] client = TestClient(app) def test_get_one_data_and_create_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0.443}' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() find_target = create_response['id'] response = client.get(f'/test/{find_target}', headers=headers, data=data) assert response.status_code == 200 assert response.json() == create_response create_response.pop('id') query_param = urlencode(create_response) response = client.get(f'/test/{find_target}?{query_param}', headers=headers, data=data) assert response.status_code == 200 def test_get_many_data_and_create_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '''[ { "bool_value":true, "char_value":"string ", "date_value":"2021-07-23", "float4_value":0.12, "float8_value":0, "int2_value":0, "int4_value":0, "int8_value":0, "numeric_value":0, "text_value":"string", "timestamp_value":"2021-07-23T02:38:24.963000", "timestamptz_value":"2021-07-23T02:38:24.963000+00:00", "varchar_value":"string" }, { "bool_value":true, "char_value":"string ", "date_value":"2021-07-23", "float4_value":1.2, "float8_value":0, "int2_value":0, "int4_value":0, "int8_value":0, "numeric_value":0, "text_value":"string", "timestamp_value":"2021-07-23T02:38:24.963000", "timestamptz_value":"2021-07-23T02:38:24.963000+00:00", "varchar_value":"string" }, { "bool_value":true, "char_value":"string ", "date_value":"2021-07-23", "float4_value":9.3, "float8_value":0, "int2_value":0, "int4_value":0, "int8_value":0, "numeric_value":0, "text_value":"string", "timestamp_value":"2021-07-23T02:38:24.963000", "timestamptz_value":"2021-07-23T02:38:24.963000+00:00", "varchar_value":"string" } ] ''' data_dict = json.loads(data) response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_dict): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_update_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0.98}' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() created_primary_key = create_response['id'] update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 12.7, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} query_param = urlencode(update_data) response = client.put(f'/test/{created_primary_key}?{query_param}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_update_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 3.5, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 3.6, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 3.7, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['id'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 200, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params)+f'&id____list={primary_key_list[0]}&id____list={primary_key_list[1]}&id____list={primary_key_list[2]}&float4_value____list=3.5&float4_value____list=3.6&float4_value____list=3.7' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.58, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test?{query_string}', data=json.dumps(update_data)) # FIXME: update the unique column will conflict, it may not a issue, because it should input all columns, you can use the patch assert response.status_code == 409 # response_data = response.json() # assert len(response_data) == 3 # for k in response_data: # for i in update_data: # assert k[i] == update_data[i] def test_patch_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 5.78, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['id'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 500, "float4_value____list": 5.78, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) update_data = {"bool_value": False} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(params) update_data = {"char_value": "string_u "} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(params) update_data = {"date_value": "2022-07-24"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(params) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 1.70, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_patch_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.91, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.92, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.93, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['id'] for i in insert_response_data] params = { "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 500, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&id____list={primary_key_list[0]}&id____list={primary_key_list[1]}&id____list={primary_key_list[2]}&float4_value____list=0.91&float4_value____list=0.92&float4_value____list=0.93' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00","varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_delete_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 2.54, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['id'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 500, "float4_value____list": 2.54, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) response = client.delete(f'/test/{primary_key}?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_delete_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.875, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.876, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.877, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['id'] for i in insert_response_data] params = { "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 500, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&id____list={primary_key_list[0]}&id____list={primary_key_list[1]}&id____list={primary_key_list[2]}&float4_value____list=0.875&float4_value____list=0.876&&float4_value____list=0.877' response = client.delete(f'/test?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_post_redirect_get_data(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} bool_value_change = False char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19.0 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 55.7 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_3', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() assert 'id' in response_data return response_data def test_upsert_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 12.784}' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k,v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/test_patch_many_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_memory_sqlalchemy.api_test import app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_one = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_one", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_many = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_post_and_redirect_get = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_get_data = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.PATCH_MANY ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_patch_data = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_patch_many", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_patch_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def test_create_many_and_patch_many(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ { "bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18" , "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list":True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = { "bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [ 1,2,3,4,5 ], "time_value": "18:19:18" , "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test_patch_many?{query_string}', data= json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/test_patch_one_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_memory_sqlalchemy.api_test import app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_one = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_one", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_many = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_post_and_redirect_get = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_get_data = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.PATCH_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_update_data = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_patch_one", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_update_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def test_create_one_and_patch_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key ,= [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False} response = client.patch(f'/test_patch_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(OrderedDict(**params)) update_data = { "char_value": "string_u "} response = client.patch(f'/test_patch_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(OrderedDict(**params)) update_data = {"date_value": "2022-07-24"} # update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, # "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, # "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, # "text_value": "string_update", # "timestamp_value": "2022-07-24T02:54:53.285000", # "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", # "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", # "array_value": [1, 2, 3, 4, 5], # "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test_patch_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test_patch_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/test_post_redirect_get_api.py ================================================ import json import uuid from datetime import date, timedelta, datetime, timezone from http import HTTPStatus from starlette.testclient import TestClient from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_memory_sqlalchemy.api_test import app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_post_and_redirect_get = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_get_data = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_post_and_redirect_get_without_get = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get_without_get", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_get_data, test_post_and_redirect_get_without_get]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields # Post Redirect Get API Test def test_create_one_but_no_follow_redirect(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } data = '{ "bool_value": true, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }' response = client.post('/test_post_direct_get', headers=headers, data=data, allow_redirects=False) assert response.status_code == HTTPStatus.SEE_OTHER def test_create_one_with_redirect(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} bool_value_change = False char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19.0 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' uuid_value_change = str(uuid.uuid4()) varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['uuid_value'] = uuid_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_post_direct_get', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() assert primary_key_name in response_data return response_data def test_create_but_conflict(): data = test_create_one_with_redirect() headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.post('/test_post_direct_get', headers=headers, data=json.dumps(data), allow_redirects=True) assert response.status_code == HTTPStatus.CONFLICT def test_create_but_not_found_get_api(): change = {} bool_value_change = False char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' uuid_value_change = str(uuid.uuid4()) varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['uuid_value'] = uuid_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data = json.dumps(change) headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.post('/test_post_direct_get_without_get', headers=headers, data=data, allow_redirects=True) assert response.status_code == HTTPStatus.NOT_FOUND ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/test_put_many_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_memory_sqlalchemy.api_test import app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_one = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_one", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_many = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_post_and_redirect_get = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_get_data = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPDATE_MANY ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_update_data = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_update_many", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_update_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def test_create_many_and_update_many(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ { "bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18" , "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list":True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = { "bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18" , "timetz_value": "18:19:18+00:00"} response = client.put(f'/test_update_many?{query_string}', data= json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_create_many_and_update_many_but_not_found(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ { "bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18" , "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list":True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '10:18:18', "time_value____to": '12:18:18', "time_value____list": '10:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "timez_value____from": '18:18:18+00:00', "timez_value____to": '18:18:18+00:00', "timez_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = { "bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18" , "timetz_value": "18:19:18+00:00"} response = client.put(f'/test_update_many?{query_string}', data= json.dumps(update_data)) # response_data = response.json() # assert len(response_data) == 3 # for k in response_data: # for i in update_data: # print(i) # print(k[i]) # assert k[i] == update_data[i] assert response.status_code == 204 ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/api_test/test_put_one_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_memory_sqlalchemy.api_test import app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_one = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_one", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.CREATE_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_many = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_post_and_redirect_get = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_get_data = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPDATE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_update_data = crud_router_builder(db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_update_one", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_update_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def test_create_one_and_update_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key ,= [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test_update_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_create_one_and_update_one_but_not_found(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data =[ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key ,= [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '10:18:18', "time_value____to": '12:18:18', "time_value____list": '10:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_valuez____from": '18:18:18+00:00', "time_valuez____to": '18:18:18+00:00', "time_valuez____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test_update_one/{primary_key}?{query_string}', data=json.dumps(update_data)) # response_data = response.json() response.status_code = 404 # assert response_data # for i in update_data: # assert response_data[i] == update_data[i] ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/error_test/__init__.py ================================================ ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/error_test/test_create_null_type.py ================================================ from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, text, PrimaryKeyConstraint, Table, UniqueConstraint from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, synonym from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods from src.fastapi_quickcrud.misc.exceptions import SchemaException, ColumnTypeNotSupportedException, PrimaryMissing Base = declarative_base() metadata = Base.metadata class UntitledTable256(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_build_myself_async' primary_key = Column(Integer, info={'alias_name': 'primary_key'}, autoincrement=True,primary_key=True, server_default="nextval('test_build_myself_id_seq'::regclass)") bool_value = Column(Boolean, nullable=False, server_default=text("false")) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(None) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.PATCH_ONE, ], exclude_columns=['xml_value', 'box_valaue']) except ColumnTypeNotSupportedException as e: print(str(e)) assert 'The type of column array_str__value (NULL) not supported yet' in str(e) ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/error_test/test_create_specific_api_when_no_pk.py ================================================ from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, text, PrimaryKeyConstraint, Table, UniqueConstraint from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, synonym from src.fastapi_quickcrud.misc.utils import table_to_declarative_base from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods from src.fastapi_quickcrud.misc.exceptions import SchemaException, ColumnTypeNotSupportedException, PrimaryMissing Base = declarative_base() metadata = Base.metadata UntitledTable256 = Table( 'test_table', metadata, Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float, nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL), Column('json_value', JSON), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric), Column('text_value', Text), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('uuid_value', UUID), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), UniqueConstraint('interval_value', 'numeric_value', 'text_value'), ) UntitledTable256 = table_to_declarative_base(UntitledTable256) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.PATCH_ONE, ], exclude_columns=['xml_value', 'box_valaue']) except PrimaryMissing as e: print(str(e)) assert 'The generation of this API [PATCH_ONE] requires a primary key' in str(e) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE, ], exclude_columns=['xml_value', 'box_valaue']) except PrimaryMissing as e: print(str(e)) assert 'The generation of this API [FIND_ONE] requires a primary key' in str(e) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.DELETE_ONE, ], exclude_columns=['xml_value', 'box_valaue']) except PrimaryMissing as e: print(str(e)) assert 'The generation of this API [DELETE_ONE] requires a primary key' in str(e) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPDATE_ONE, ], exclude_columns=['xml_value', 'box_valaue']) except PrimaryMissing as e: print(str(e)) assert 'The generation of this API [UPDATE_ONE] requires a primary key' in str(e) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['xml_value', 'box_valaue']) except PrimaryMissing as e: print(str(e)) assert 'The generation of this API [POST_REDIRECT_GET] requires a primary key' in str(e) ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/error_test/test_create_table_with_more_than_one_unique_but_no_use_composite.py ================================================ from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, text, PrimaryKeyConstraint, Table, UniqueConstraint from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, synonym from src.fastapi_quickcrud.misc.utils import table_to_declarative_base from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods from src.fastapi_quickcrud.misc.exceptions import SchemaException, ColumnTypeNotSupportedException, PrimaryMissing Base = declarative_base() metadata = Base.metadata UntitledTable256 = Table( 'test_table', metadata, Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float, nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL, unique=True), Column('json_value', JSON, unique=True), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric, unique=True), Column('text_value', Text), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('uuid_value', UUID), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), ) UntitledTable256 = table_to_declarative_base(UntitledTable256) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.PATCH_ONE, ], exclude_columns=['xml_value', 'box_valaue']) except SchemaException as e: assert 'nly support one unique constraint/ Use unique constraint and composite unique constraint at same time is not supported / Use composite unique constraint if there are more than one unique constraint' in str(e) ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/error_test/test_use_blob_type_column.py ================================================ from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, text, PrimaryKeyConstraint from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, synonym from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods from src.fastapi_quickcrud.misc.exceptions import SchemaException, ColumnTypeNotSupportedException Base = declarative_base() class UntitledTable256(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_build_myself_async' primary_key = Column(Integer, info={'alias_name': 'primary_key'}, autoincrement=True,primary_key=True, server_default="nextval('test_build_myself_id_seq'::regclass)") bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['xml_value', 'box_valaue']) except ColumnTypeNotSupportedException as e: print(str(e)) assert 'The type of column bytea_value (BLOB) not supported yet' in str(e) ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/error_test/test_use_composite_primary.py ================================================ from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, text, PrimaryKeyConstraint from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, synonym from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods from src.fastapi_quickcrud.misc.exceptions import SchemaException Base = declarative_base() class UntitledTable256(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_build_myself_async' __table_args__ = ( PrimaryKeyConstraint('primary_key', 'int4_value', 'float4_value'), ) primary_key = Column(Integer, info={'alias_name': 'primary_key'}, autoincrement=True, server_default="nextval('test_build_myself_id_seq'::regclass)") bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False, unique=True) int4_value = Column(Integer, nullable=False, unique=True) int8_value = Column(BigInteger, server_default=text("99"), unique=True) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) except SchemaException as e: print(e) 'multiple primary key / or composite not supported;' in str(e) ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/error_test/test_use_more_than_one_pk.py ================================================ from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, text, PrimaryKeyConstraint from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, synonym from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods from src.fastapi_quickcrud.misc.exceptions import SchemaException Base = declarative_base() class UntitledTable256(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_build_myself_async' primary_key = Column(Integer,primary_key=True, info={'alias_name': 'primary_key'}, autoincrement=True, server_default="nextval('test_build_myself_id_seq'::regclass)") bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10),primary_key=True,) date_value = Column(Date, server_default=text("now()"),primary_key=True,) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False, unique=True) int4_value = Column(Integer, nullable=False, unique=True) int8_value = Column(BigInteger, server_default=text("99"), unique=True) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) except SchemaException as e: print(e) 'multiple primary key / or composite not supported;' in str(e) ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/error_test/test_use_more_than_one_unique.py ================================================ from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods from src.fastapi_quickcrud.misc.exceptions import SchemaException, MultipleSingleUniqueNotSupportedException Base = declarative_base() class UntitledTable256(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_build_myself_async' primary_key = Column(Integer, primary_key=True, info={'alias_name': 'primary_key'},autoincrement=True,server_default="nextval('test_build_myself_id_seq'::regclass)") bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False, unique=True) int4_value = Column(Integer, nullable=False, unique=True) int8_value = Column(BigInteger, server_default=text("99"), unique=True) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) except SchemaException as e: str(e) == 'Only support one unique constraint/ Use unique constraint and composite unique constraint at same time is not supported / Use composite unique constraint if there are more than one unique constraint' ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/error_test/test_use_unique_and_composite_unique.py ================================================ from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods from src.fastapi_quickcrud.misc.exceptions import SchemaException Base = declarative_base() class UntitledTable256(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_build_myself_async' __table_args__ = ( UniqueConstraint('primary_key', 'int4_value', 'float4_value'), ) primary_key = Column(Integer, primary_key=True, info={'alias_name': 'primary_key'},autoincrement=True,server_default="nextval('test_build_myself_id_seq'::regclass)") bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99"), unique=True) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) except SchemaException as e: str(e) == 'Only support one unique constraint/ Use unique constraint and composite unique constraint at same time is not supported / Use composite unique constraint if there are more than one unique constraint' ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/error_test/test_use_unsupported_type_pk.py ================================================ from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, text, PrimaryKeyConstraint from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, synonym from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods from src.fastapi_quickcrud.misc.exceptions import SchemaException, ColumnTypeNotSupportedException Base = declarative_base() class UntitledTable256(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_build_myself_async' primary_key = Column(LargeBinary, primary_key = True, info={'alias_name': 'primary_key'}, autoincrement=True, server_default="nextval('test_build_myself_id_seq'::regclass)") bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False, unique=True) int4_value = Column(Integer, nullable=False, unique=True) int8_value = Column(BigInteger, server_default=text("99"), unique=True) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) except ColumnTypeNotSupportedException as e: 'not supported yet' in str(e) ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/error_test/test_use_unsupported_type_pk_2.py ================================================ from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, text, PrimaryKeyConstraint from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, synonym from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods from src.fastapi_quickcrud.misc.exceptions import SchemaException, ColumnTypeNotSupportedException Base = declarative_base() class UntitledTable256(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_build_myself_async' primary_key = Column(INTERVAL, primary_key = True, info={'alias_name': 'primary_key'}, autoincrement=True, server_default="nextval('test_build_myself_id_seq'::regclass)") bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False, unique=True) int4_value = Column(Integer, nullable=False, unique=True) int8_value = Column(BigInteger, server_default=text("99"), unique=True) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) except ColumnTypeNotSupportedException as e: 'not supported yet' in str(e) ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/error_test/test_use_unsupported_type_pk_3.py ================================================ from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, text, PrimaryKeyConstraint from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, synonym from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods from src.fastapi_quickcrud.misc.exceptions import SchemaException, ColumnTypeNotSupportedException Base = declarative_base() class UntitledTable256(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_build_myself_async' primary_key = Column(JSON, primary_key = True, info={'alias_name': 'primary_key'}, autoincrement=True, server_default="nextval('test_build_myself_id_seq'::regclass)") bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False, unique=True) int4_value = Column(Integer, nullable=False, unique=True) int8_value = Column(BigInteger, server_default=text("99"), unique=True) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) except ColumnTypeNotSupportedException as e: 'not supported yet' in str(e) ================================================ FILE: tests/test_implementations/test_memory_sqlalchemy/error_test/test_use_unsupported_type_pk_4.py ================================================ from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, text, PrimaryKeyConstraint from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, synonym from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods from src.fastapi_quickcrud.misc.exceptions import SchemaException, ColumnTypeNotSupportedException Base = declarative_base() class UntitledTable256(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_build_myself_async' primary_key = Column(JSONB, primary_key = True, info={'alias_name': 'primary_key'}, autoincrement=True, server_default="nextval('test_build_myself_id_seq'::regclass)") bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False, unique=True) int4_value = Column(Integer, nullable=False, unique=True) int8_value = Column(BigInteger, server_default=text("99"), unique=True) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) except ColumnTypeNotSupportedException as e: 'not supported yet' in str(e) ================================================ FILE: tests/test_implementations/test_sqlalchemy/__init__.py ================================================ ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/__init__.py ================================================ import os from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = async_session() yield db finally: db.close() class UntitledTable256(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_build_myself' __table_args__ = ( UniqueConstraint('primary_key', 'int4_value', 'float4_value'), ) primary_key = Column(Integer, primary_key=True, info={'alias_name': 'primary_key'},autoincrement=True,server_default="nextval('test_build_myself_id_seq'::regclass)") bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) # xml_value = Column(NullType) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) # box_valaue = Column(NullType) UntitledTable256.__table__.create(engine, checkfirst=True) ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/join_relationship/__init__.py ================================================ ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/join_relationship/test_relationship_m2m.py ================================================ import json import os from fastapi import FastAPI from sqlalchemy import Column, Integer, \ ForeignKey, Table, insert from sqlalchemy.orm import declarative_base, sessionmaker, relationship from src.fastapi_quickcrud.crud_router import crud_router_builder TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() association_table = Table('test_association', Base.metadata, Column('left_id', ForeignKey('test_left.id')), Column('right_id', ForeignKey('test_right.id')) ) association_table_second = Table('test_association_second', Base.metadata, Column('left_id_second', ForeignKey('test_left.id')), Column('right_id_second', ForeignKey('test_right_second.id')) ) class Child(Base): __tablename__ = 'test_right' id = Column(Integer, primary_key=True) class Parent(Base): __tablename__ = 'test_left' id = Column(Integer, primary_key=True) children = relationship("Child", secondary=association_table) children_second = relationship("ChildSecond", secondary=association_table_second) class ChildSecond(Base): __tablename__ = 'test_right_second' id = Column(Integer, primary_key=True) crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child", tags=["child"] ) crud_route_association_table_second = crud_router_builder(db_session=get_transaction_session, db_model=association_table_second, prefix="/association_table_second", tags=["association_table_second"] ) crud_route_child_second = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child_second", tags=["child_second"] ) crud_route_parent = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"] ) crud_route_association = crud_router_builder(db_session=get_transaction_session, db_model=association_table, prefix="/association", tags=["association"] ) from starlette.testclient import TestClient [app.include_router(i) for i in [crud_route_association_table_second,crud_route_child_second,crud_route_parent, crud_route_child, crud_route_association]] client = TestClient(app) def test_get_parent_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent?join_foreign_table=test_right', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_right_foreign": [ { "id": 1 } ], "id": 1 }, { "test_right_foreign": [ { "id": 2 } ], "id": 2 }, { "test_right_foreign": [ { "id": 3 } ], "id": 3 }, { "test_right_foreign": [ { "id": 4 } ], "id": 4 } ] response = client.get('/parent/1?join_foreign_table=test_right', headers=headers) assert response.status_code == 200 assert response.json() == { "test_right_foreign": [ { "id": 1 } ], "id": 1 } response = client.get('/parent?join_foreign_table=test_right_second', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_right_second_foreign": [ { "id": 1 } ], "id": 1 }, { "test_right_second_foreign": [ { "id": 2 } ], "id": 2 }, { "test_right_second_foreign": [ { "id": 3 } ], "id": 3 }, { "test_right_second_foreign": [ { "id": 4 } ], "id": 4 } ] response = client.get('/parent/1?join_foreign_table=test_right_second', headers=headers) assert response.status_code == 200 assert response.json() == { "test_right_second_foreign": [ { "id": 1 } ], "id": 1 } response = client.get('/parent?join_foreign_table=test_right&join_foreign_table=test_right_second', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_right_foreign": [ { "id": 1 } ], "test_right_second_foreign": [ { "id": 1 } ], "id": 1 }, { "test_right_foreign": [ { "id": 2 } ], "test_right_second_foreign": [ { "id": 2 } ], "id": 2 }, { "test_right_foreign": [ { "id": 3 } ], "test_right_second_foreign": [ { "id": 3 } ], "id": 3 }, { "test_right_foreign": [ { "id": 4 } ], "test_right_second_foreign": [ { "id": 4 } ], "id": 4 } ] response = client.get('/parent/1?join_foreign_table=test_right&join_foreign_table=test_right_second', headers=headers) assert response.status_code == 200 assert response.json() == { "test_right_foreign": [ { "id": 1 } ], "test_right_second_foreign": [ { "id": 1 } ], "id": 1 } def test_get_child_many_without_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1 }, { "id": 2 }, { "id": 3 }, { "id": 4 } ] response = client.get('/child/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1 } def test_get_association_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/association?join_foreign_table=test_left', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_left_foreign": [ { "id": 1 } ], "left_id": 1, "right_id": 1 }, { "test_left_foreign": [ { "id": 2 } ], "left_id": 2, "right_id": 2 }, { "test_left_foreign": [ { "id": 3 } ], "left_id": 3, "right_id": 3 }, { "test_left_foreign": [ { "id": 4 } ], "left_id": 4, "right_id": 4 } ] response = client.get('/association?join_foreign_table=test_left', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_left_foreign": [ { "id": 1 } ], "left_id": 1, "right_id": 1 }, { "test_left_foreign": [ { "id": 2 } ], "left_id": 2, "right_id": 2 }, { "test_left_foreign": [ { "id": 3 } ], "left_id": 3, "right_id": 3 }, { "test_left_foreign": [ { "id": 4 } ], "left_id": 4, "right_id": 4 } ] response = client.get('/association?join_foreign_table=test_right', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_right_foreign": [ { "id": 1 } ], "left_id": 1, "right_id": 1 }, { "test_right_foreign": [ { "id": 2 } ], "left_id": 2, "right_id": 2 }, { "test_right_foreign": [ { "id": 3 } ], "left_id": 3, "right_id": 3 }, { "test_right_foreign": [ { "id": 4 } ], "left_id": 4, "right_id": 4 } ] response = client.get('/association?join_foreign_table=test_left&join_foreign_table=test_right', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_left_foreign": [ { "id": 1 } ], "test_right_foreign": [ { "id": 1 } ], "left_id": 1, "right_id": 1 }, { "test_left_foreign": [ { "id": 2 } ], "test_right_foreign": [ { "id": 2 } ], "left_id": 2, "right_id": 2 }, { "test_left_foreign": [ { "id": 3 } ], "test_right_foreign": [ { "id": 3 } ], "left_id": 3, "right_id": 3 }, { "test_left_foreign": [ { "id": 4 } ], "test_right_foreign": [ { "id": 4 } ], "left_id": 4, "right_id": 4 } ] def test_get_association_many_second_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/association_table_second?join_foreign_table=test_right_second', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_right_second_foreign": [ { "id": 1 } ], "left_id_second": 1, "right_id_second": 1 }, { "test_right_second_foreign": [ { "id": 2 } ], "left_id_second": 2, "right_id_second": 2 }, { "test_right_second_foreign": [ { "id": 3 } ], "left_id_second": 3, "right_id_second": 3 }, { "test_right_second_foreign": [ { "id": 4 } ], "left_id_second": 4, "right_id_second": 4 } ] response = client.get('/association_table_second?join_foreign_table=test_left', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_left_foreign": [ { "id": 1 } ], "left_id_second": 1, "right_id_second": 1 }, { "test_left_foreign": [ { "id": 2 } ], "left_id_second": 2, "right_id_second": 2 }, { "test_left_foreign": [ { "id": 3 } ], "left_id_second": 3, "right_id_second": 3 }, { "test_left_foreign": [ { "id": 4 } ], "left_id_second": 4, "right_id_second": 4 } ] response = client.get('/association_table_second?join_foreign_table=test_left&join_foreign_table=test_right_second', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_left_foreign": [ { "id": 1 } ], "test_right_second_foreign": [ { "id": 1 } ], "left_id_second": 1, "right_id_second": 1 }, { "test_left_foreign": [ { "id": 2 } ], "test_right_second_foreign": [ { "id": 2 } ], "left_id_second": 2, "right_id_second": 2 }, { "test_left_foreign": [ { "id": 3 } ], "test_right_second_foreign": [ { "id": 3 } ], "left_id_second": 3, "right_id_second": 3 }, { "test_left_foreign": [ { "id": 4 } ], "test_right_second_foreign": [ { "id": 4 } ], "left_id_second": 4, "right_id_second": 4 } ] response = client.get('/association_table_second', headers=headers) assert response.status_code == 200 assert response.json() == [ { "left_id_second": 1, "right_id_second": 1 }, { "left_id_second": 2, "right_id_second": 2 }, { "left_id_second": 3, "right_id_second": 3 }, { "left_id_second": 4, "right_id_second": 4 } ] def test_get_child_many_second_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child_second', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1 }, { "id": 2 }, { "id": 3 }, { "id": 4 } ] response = client.get('/child_second/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1 } def setup_module(module): Child.__table__.create(engine, checkfirst=True) ChildSecond.__table__.create(engine, checkfirst=True) Parent.__table__.create(engine, checkfirst=True) association_table.create(engine, checkfirst=True) association_table_second.create(engine, checkfirst=True) db = session() db.add(Child(id=1)) db.add(Child(id=2)) db.add(Child(id=3)) db.add(Child(id=4)) db.flush() db.add(Parent(id=1)) db.add(Parent(id=2)) db.add(Parent(id=3)) db.add(Parent(id=4)) db.flush() db.execute(association_table.insert().values(left_id = 1, right_id=1)) db.execute(association_table.insert().values(left_id = 2, right_id=2)) db.execute(association_table.insert().values(left_id = 3, right_id=3)) db.execute(association_table.insert().values(left_id = 4, right_id=4)) db.add(ChildSecond(id = 1)) db.add(ChildSecond(id = 2)) db.add(ChildSecond(id = 3)) db.add(ChildSecond(id = 4)) db.flush() db.execute(association_table_second.insert().values(left_id_second=1, right_id_second=1)) db.execute(association_table_second.insert().values(left_id_second=2, right_id_second=2)) db.execute(association_table_second.insert().values(left_id_second=3, right_id_second=3)) db.execute(association_table_second.insert().values(left_id_second=4, right_id_second=4)) db.commit() def teardown_module(module): association_table.drop(engine, checkfirst=True) association_table_second.drop(engine, checkfirst=True) ChildSecond.__table__.drop(engine, checkfirst=True) Parent.__table__.drop(engine, checkfirst=True) Child.__table__.drop(engine, checkfirst=True) ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/join_relationship/test_relationship_m2m_back_populates.py ================================================ import os from fastapi import FastAPI from sqlalchemy import Column, Integer, \ ForeignKey, Table from sqlalchemy.orm import declarative_base, sessionmaker, relationship from src.fastapi_quickcrud.crud_router import crud_router_builder TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() association_table = Table('test_association', Base.metadata, Column('left_id', ForeignKey('test_left.id')), Column('right_id', ForeignKey('test_right.id')) ) association_table_second = Table('test_association_second', Base.metadata, Column('left_id_second', ForeignKey('test_left.id')), Column('right_id_second', ForeignKey('test_right_second.id')) ) class Child(Base): __tablename__ = 'test_right' id = Column(Integer, primary_key=True) parent = relationship("Parent", secondary=association_table, back_populates="children") class ChildSecond(Base): __tablename__ = 'test_right_second' id = Column(Integer, primary_key=True) parent_second = relationship("Parent", secondary=association_table_second, back_populates="children_second") class Parent(Base): __tablename__ = 'test_left' id = Column(Integer, primary_key=True) children = relationship("Child", secondary=association_table, back_populates="parent") children_second = relationship("ChildSecond", secondary=association_table_second, back_populates="parent_second") crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child", tags=["child"] ) crud_route_association_table_second = crud_router_builder(db_session=get_transaction_session, db_model=association_table_second, prefix="/association_table_second", tags=["association_table_second"] ) crud_route_child_second = crud_router_builder(db_session=get_transaction_session, db_model=ChildSecond, prefix="/child_second", tags=["child_second"] ) crud_route_parent = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"] ) crud_route_association = crud_router_builder(db_session=get_transaction_session, db_model=association_table, prefix="/association", tags=["association"] ) from starlette.testclient import TestClient [app.include_router(i) for i in [crud_route_association_table_second, crud_route_child_second, crud_route_parent, crud_route_child, crud_route_association]] client = TestClient(app) def test_get_parent_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent?join_foreign_table=test_right', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_right_foreign": [ { "id": 1 } ], "id": 1 }, { "test_right_foreign": [ { "id": 2 } ], "id": 2 }, { "test_right_foreign": [ { "id": 3 } ], "id": 3 }, { "test_right_foreign": [ { "id": 4 } ], "id": 4 } ] response = client.get('/parent/1?join_foreign_table=test_right', headers=headers) assert response.status_code == 200 assert response.json() == { "test_right_foreign": [ { "id": 1 } ], "id": 1 } response = client.get('/parent/1?join_foreign_table=test_right_second', headers=headers) assert response.status_code == 200 assert response.json() == { "test_right_second_foreign": [ { "id": 1 } ], "id": 1 } response = client.get('/parent/1?join_foreign_table=test_right&join_foreign_table=test_right_second', headers=headers) assert response.status_code == 200 assert response.json() == { "test_right_foreign": [ { "id": 1 } ], "test_right_second_foreign": [ { "id": 1 } ], "id": 1 } def test_get_child_many_without_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1 }, { "id": 2 }, { "id": 3 }, { "id": 4 } ] def test_get_child_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child?join_foreign_table=test_left', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_left_foreign": [ { "id": 1 } ], "id": 1 }, { "test_left_foreign": [ { "id": 2 } ], "id": 2 }, { "test_left_foreign": [ { "id": 3 } ], "id": 3 }, { "test_left_foreign": [ { "id": 4 } ], "id": 4 } ] def test_get_association_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/association?join_foreign_table=test_left', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_left_foreign": [ { "id": 1 } ], "left_id": 1, "right_id": 1 }, { "test_left_foreign": [ { "id": 2 } ], "left_id": 2, "right_id": 2 }, { "test_left_foreign": [ { "id": 3 } ], "left_id": 3, "right_id": 3 }, { "test_left_foreign": [ { "id": 4 } ], "left_id": 4, "right_id": 4 } ] response = client.get('/association?join_foreign_table=test_right', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_right_foreign": [ { "id": 1 } ], "left_id": 1, "right_id": 1 }, { "test_right_foreign": [ { "id": 2 } ], "left_id": 2, "right_id": 2 }, { "test_right_foreign": [ { "id": 3 } ], "left_id": 3, "right_id": 3 }, { "test_right_foreign": [ { "id": 4 } ], "left_id": 4, "right_id": 4 } ] response = client.get('/association?join_foreign_table=test_left&join_foreign_table=test_right', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_left_foreign": [ { "id": 1 } ], "test_right_foreign": [ { "id": 1 } ], "left_id": 1, "right_id": 1 }, { "test_left_foreign": [ { "id": 2 } ], "test_right_foreign": [ { "id": 2 } ], "left_id": 2, "right_id": 2 }, { "test_left_foreign": [ { "id": 3 } ], "test_right_foreign": [ { "id": 3 } ], "left_id": 3, "right_id": 3 }, { "test_left_foreign": [ { "id": 4 } ], "test_right_foreign": [ { "id": 4 } ], "left_id": 4, "right_id": 4 } ] def test_get_association_many_second_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/association_table_second?join_foreign_table=test_right_second', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_right_second_foreign": [ { "id": 1 } ], "left_id_second": 1, "right_id_second": 1 }, { "test_right_second_foreign": [ { "id": 2 } ], "left_id_second": 2, "right_id_second": 2 }, { "test_right_second_foreign": [ { "id": 3 } ], "left_id_second": 3, "right_id_second": 3 }, { "test_right_second_foreign": [ { "id": 4 } ], "left_id_second": 4, "right_id_second": 4 } ] response = client.get('/association_table_second?join_foreign_table=test_left', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_left_foreign": [ { "id": 1 } ], "left_id_second": 1, "right_id_second": 1 }, { "test_left_foreign": [ { "id": 2 } ], "left_id_second": 2, "right_id_second": 2 }, { "test_left_foreign": [ { "id": 3 } ], "left_id_second": 3, "right_id_second": 3 }, { "test_left_foreign": [ { "id": 4 } ], "left_id_second": 4, "right_id_second": 4 } ] response = client.get('/association_table_second?join_foreign_table=test_left&join_foreign_table=test_right_second', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_left_foreign": [ { "id": 1 } ], "test_right_second_foreign": [ { "id": 1 } ], "left_id_second": 1, "right_id_second": 1 }, { "test_left_foreign": [ { "id": 2 } ], "test_right_second_foreign": [ { "id": 2 } ], "left_id_second": 2, "right_id_second": 2 }, { "test_left_foreign": [ { "id": 3 } ], "test_right_second_foreign": [ { "id": 3 } ], "left_id_second": 3, "right_id_second": 3 }, { "test_left_foreign": [ { "id": 4 } ], "test_right_second_foreign": [ { "id": 4 } ], "left_id_second": 4, "right_id_second": 4 } ] response = client.get('/association_table_second', headers=headers) assert response.status_code == 200 assert response.json() == [ { "left_id_second": 1, "right_id_second": 1 }, { "left_id_second": 2, "right_id_second": 2 }, { "left_id_second": 3, "right_id_second": 3 }, { "left_id_second": 4, "right_id_second": 4 } ] def test_get_child_many_second_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child_second', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1 }, { "id": 2 }, { "id": 3 }, { "id": 4 } ] response = client.get('/child_second/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1 } response = client.get('/child_second?join_foreign_table=test_left', headers=headers) assert response.status_code == 200 assert response.json() == [ { "test_left_foreign": [ { "id": 1 } ], "id": 1 }, { "test_left_foreign": [ { "id": 2 } ], "id": 2 }, { "test_left_foreign": [ { "id": 3 } ], "id": 3 }, { "test_left_foreign": [ { "id": 4 } ], "id": 4 } ] response = client.get('/child_second/1?join_foreign_table=test_left', headers=headers) assert response.status_code == 200 assert response.json() == { "test_left_foreign": [ { "id": 1 } ], "id": 1 } def setup_module(module): Child.__table__.create(engine, checkfirst=True) ChildSecond.__table__.create(engine, checkfirst=True) Parent.__table__.create(engine, checkfirst=True) association_table.create(engine, checkfirst=True) association_table_second.create(engine, checkfirst=True) db = session() db.add(Child(id=1)) db.add(Child(id=2)) db.add(Child(id=3)) db.add(Child(id=4)) db.flush() db.add(Parent(id=1)) db.add(Parent(id=2)) db.add(Parent(id=3)) db.add(Parent(id=4)) db.flush() db.execute(association_table.insert().values(left_id=1, right_id=1)) db.execute(association_table.insert().values(left_id=2, right_id=2)) db.execute(association_table.insert().values(left_id=3, right_id=3)) db.execute(association_table.insert().values(left_id=4, right_id=4)) db.add(ChildSecond(id=1)) db.add(ChildSecond(id=2)) db.add(ChildSecond(id=3)) db.add(ChildSecond(id=4)) db.flush() db.execute(association_table_second.insert().values(left_id_second=1, right_id_second=1)) db.execute(association_table_second.insert().values(left_id_second=2, right_id_second=2)) db.execute(association_table_second.insert().values(left_id_second=3, right_id_second=3)) db.execute(association_table_second.insert().values(left_id_second=4, right_id_second=4)) db.commit() print() def teardown_module(module): association_table.drop(engine, checkfirst=True) association_table_second.drop(engine, checkfirst=True) ChildSecond.__table__.drop(engine, checkfirst=True) Parent.__table__.drop(engine, checkfirst=True) Child.__table__.drop(engine, checkfirst=True) ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/join_relationship/test_relationship_m2o.py ================================================ import json import os from fastapi import FastAPI from sqlalchemy import Column, Integer, \ ForeignKey from sqlalchemy.orm import declarative_base, sessionmaker, relationship from src.fastapi_quickcrud.crud_router import crud_router_builder TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() class Parent(Base): __tablename__ = 'parent_m2o' id = Column(Integer, primary_key=True) child_id = Column(Integer, ForeignKey('child_m2o.id')) child = relationship("Child") class Child(Base): __tablename__ = 'child_m2o' id = Column(Integer, primary_key=True) crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child", tags=["child"] ) crud_route_parent = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"] ) from starlette.testclient import TestClient [app.include_router(i) for i in [crud_route_parent, crud_route_child]] client = TestClient(app) def test_get_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent?join_foreign_table=child_m2o', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1, "child_m2o_foreign": [ { "id": 1 } ], "child_id": 1 }, { "id": 2, "child_m2o_foreign": [ { "id": 1 } ], "child_id": 1 }, { "id": 3, "child_m2o_foreign": [ { "id": 2 } ], "child_id": 2 }, { "id": 4, "child_m2o_foreign": [ { "id": 2 } ], "child_id": 2 } ] response = client.get('/parent/1?join_foreign_table=child_m2o', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1, "child_m2o_foreign": [ { "id": 1 } ], "child_id": 1 } def test_get_child_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1 } def test_get_many_without_join(): query = {"join_foreign_table": "child"} data = json.dumps(query) headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent/1', headers=headers, data=data) assert response.status_code == 200 assert response.json() == { "id": 1, "child_id": 1 } def setup_module(module): Child.__table__.create(engine, checkfirst=True) Parent.__table__.create(engine, checkfirst=True) db = session() db.add(Child(id=1)) db.add(Child(id=2)) db.add(Child(id=3)) db.add(Child(id=4)) db.flush() db.add(Parent(id=1, child_id=1)) db.add(Parent(id=2, child_id=1)) db.add(Parent(id=3, child_id=2)) db.add(Parent(id=4, child_id=2)) db.commit() def teardown_module(module): Parent.__table__.drop(engine, checkfirst=True) Child.__table__.drop(engine, checkfirst=True) ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/join_relationship/test_relationship_m2o_back_populates.py ================================================ import json import os from fastapi import FastAPI from sqlalchemy import Column, Integer, \ ForeignKey from sqlalchemy.orm import declarative_base, sessionmaker, relationship from src.fastapi_quickcrud.crud_router import crud_router_builder TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() class Parent(Base): __tablename__ = 'parent_m2o_back_populates' id = Column(Integer, primary_key=True) child_id = Column(Integer, ForeignKey('child_m2o_back_populates.id')) child = relationship("Child", back_populates="parents") class Child(Base): __tablename__ = 'child_m2o_back_populates' id = Column(Integer, primary_key=True) parents = relationship("Parent", back_populates="child") crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child", tags=["child"] ) crud_route_parent = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"] ) from starlette.testclient import TestClient [app.include_router(i) for i in [crud_route_parent, crud_route_child]] client = TestClient(app) def test_get_parent_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent?join_foreign_table=child_m2o_back_populates', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1, "child_m2o_back_populates_foreign": [ { "id": 1 } ], "child_id": 1 }, { "id": 2, "child_m2o_back_populates_foreign": [ { "id": 1 } ], "child_id": 1 }, { "id": 3, "child_m2o_back_populates_foreign": [ { "id": 2 } ], "child_id": 2 }, { "id": 4, "child_m2o_back_populates_foreign": [ { "id": 2 } ], "child_id": 2 } ] response = client.get('/parent/1?join_foreign_table=child_m2o_back_populates', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1, "child_m2o_back_populates_foreign": [ { "id": 1 } ], "child_id": 1 } def test_get_child_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child?join_foreign_table=parent_m2o_back_populates', headers=headers) assert response.status_code == 200 a = response.json() assert response.json() == [ { "parent_m2o_back_populates_foreign": [ { "id": 1, "child_id": 1 }, { "id": 2, "child_id": 1 } ], "id": 1 }, { "parent_m2o_back_populates_foreign": [ { "id": 3, "child_id": 2 }, { "id": 4, "child_id": 2 } ], "id": 2 } ] response = client.get('/child/1?join_foreign_table=parent_m2o_back_populates', headers=headers) assert response.status_code == 200 a = response.json() assert response.json() == { "parent_m2o_back_populates_foreign": [ { "id": 1, "child_id": 1 }, { "id": 2, "child_id": 1 } ], "id": 1 } def test_get_child_many_without_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1, "child_id": 1 }, { "id": 2, "child_id": 1 }, { "id": 3, "child_id": 2 }, { "id": 4, "child_id": 2 } ] response = client.get('/parent/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1, "child_id": 1 } def test_get_parent_many_without_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1 }, { "id": 2 }, { "id": 3 }, { "id": 4 } ] response = client.get('/child/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1 } def setup_module(module): Child.__table__.create(engine, checkfirst=True) Parent.__table__.create(engine, checkfirst=True) db = session() db.add(Child(id=1)) db.add(Child(id=2)) db.add(Child(id=3)) db.add(Child(id=4)) db.flush() db.add(Parent(id=1, child_id=1)) db.add(Parent(id=2, child_id=1)) db.add(Parent(id=3, child_id=2)) db.add(Parent(id=4, child_id=2)) db.commit() def teardown_module(module): Parent.__table__.drop(engine, checkfirst=True) Child.__table__.drop(engine, checkfirst=True) ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/join_relationship/test_relationship_m2o_back_refer.py ================================================ import json import os from fastapi import FastAPI from sqlalchemy import Column, Integer, \ ForeignKey from sqlalchemy.orm import declarative_base, sessionmaker, relationship from src.fastapi_quickcrud.crud_router import crud_router_builder TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() class Child(Base): __tablename__ = 'child_m2o_back_populates' id = Column(Integer, primary_key=True) class Parent(Base): __tablename__ = 'parent_m2o_back_populates' id = Column(Integer, primary_key=True) child_id = Column(Integer, ForeignKey('child_m2o_back_populates.id')) child = relationship("Child", backref="child_m2o_back_populates") crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child", tags=["child"] ) crud_route_parent = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"] ) from starlette.testclient import TestClient [app.include_router(i) for i in [crud_route_parent, crud_route_child]] client = TestClient(app) def test_get_parent_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent?join_foreign_table=child_m2o_back_populates', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1, "child_m2o_back_populates_foreign": [ { "id": 1 } ], "child_id": 1 }, { "id": 2, "child_m2o_back_populates_foreign": [ { "id": 1 } ], "child_id": 1 }, { "id": 3, "child_m2o_back_populates_foreign": [ { "id": 2 } ], "child_id": 2 }, { "id": 4, "child_m2o_back_populates_foreign": [ { "id": 2 } ], "child_id": 2 } ] response = client.get('/parent/1?join_foreign_table=child_m2o_back_populates', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1, "child_m2o_back_populates_foreign": [ { "id": 1 } ], "child_id": 1 } def test_get_child_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child?join_foreign_table=parent_m2o_back_populates', headers=headers) assert response.status_code == 200 assert response.json() == [ { "parent_m2o_back_populates_foreign": [ { "id": 1, "child_id": 1 }, { "id": 2, "child_id": 1 } ], "id": 1 }, { "parent_m2o_back_populates_foreign": [ { "id": 3, "child_id": 2 }, { "id": 4, "child_id": 2 } ], "id": 2 } ] response = client.get('/child/1?join_foreign_table=parent_m2o_back_populates', headers=headers) assert response.status_code == 200 assert response.json() == { "parent_m2o_back_populates_foreign": [ { "id": 1, "child_id": 1 }, { "id": 2, "child_id": 1 } ], "id": 1 } def test_get_child_many_without_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1, "child_id": 1 }, { "id": 2, "child_id": 1 }, { "id": 3, "child_id": 2 }, { "id": 4, "child_id": 2 } ] response = client.get('/parent/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1, "child_id": 1 } def test_get_parent_many_without_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1 }, { "id": 2 }, { "id": 3 }, { "id": 4 } ] response = client.get('/child/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1 } def setup_module(module): Child.__table__.create(engine, checkfirst=True) Parent.__table__.create(engine, checkfirst=True) db = session() db.add(Child(id=1)) db.add(Child(id=2)) db.add(Child(id=3)) db.add(Child(id=4)) db.flush() db.add(Parent(id=1, child_id=1)) db.add(Parent(id=2, child_id=1)) db.add(Parent(id=3, child_id=2)) db.add(Parent(id=4, child_id=2)) db.commit() def teardown_module(module): Parent.__table__.drop(engine, checkfirst=True) Child.__table__.drop(engine, checkfirst=True) ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/join_relationship/test_relationship_o2m.py ================================================ import json import os from fastapi import FastAPI from sqlalchemy import Column, Integer, \ ForeignKey from sqlalchemy.orm import declarative_base, sessionmaker, relationship from src.fastapi_quickcrud.crud_router import crud_router_builder TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() class Parent(Base): __tablename__ = 'parent_one_to_many' id = Column(Integer, primary_key=True) children = relationship("Child") class Child(Base): __tablename__ = 'child_one_to_many' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('parent_one_to_many.id')) crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child", tags=["child"] ) crud_route_parent = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"] ) from starlette.testclient import TestClient [app.include_router(i) for i in [crud_route_parent, crud_route_child]] client = TestClient(app) def test_get_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent?join_foreign_table=child_one_to_many', headers=headers) assert response.status_code == 200 assert response.json() == [ { "child_one_to_many_foreign": [ { "id": 1, "parent_id": 1 }, { "id": 2, "parent_id": 1 } ], "id": 1 }, { "child_one_to_many_foreign": [ { "id": 3, "parent_id": 2 }, { "id": 4, "parent_id": 2 } ], "id": 2 } ] response = client.get('/parent/1?join_foreign_table=child_one_to_many', headers=headers) assert response.status_code == 200 assert response.json() == { "child_one_to_many_foreign": [ { "id": 1, "parent_id": 1 }, { "id": 2, "parent_id": 1 } ], "id": 1 } def test_get_child_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1, "parent_id": 1 }, { "id": 2, "parent_id": 1 }, { "id": 3, "parent_id": 2 }, { "id": 4, "parent_id": 2 }] response = client.get('/child/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1, "parent_id": 1 } def test_get_many_without_join(): query = {"join_foreign_table": "child"} data = json.dumps(query) headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent', headers=headers, data=data) assert response.status_code == 200 assert response.json() == [ { "id": 1 }, { "id": 2 } ] response = client.get('/parent/1', headers=headers, data=data) assert response.status_code == 200 assert response.json() == { "id": 1 } def setup_module(module): Parent.__table__.create(engine, checkfirst=True) Child.__table__.create(engine, checkfirst=True) db = session() db.add(Parent(id=1)) db.add(Parent(id=2)) db.flush() db.add(Child(id=1, parent_id=1)) db.add(Child(id=2, parent_id=1)) db.add(Child(id=3, parent_id=2)) db.add(Child(id=4, parent_id=2)) db.commit() def teardown_module(module): Child.__table__.drop(engine, checkfirst=True) Parent.__table__.drop(engine, checkfirst=True) ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/join_relationship/test_relationship_o2m_back_populates.py ================================================ import json import os from fastapi import FastAPI from sqlalchemy import Column, Integer, \ ForeignKey from sqlalchemy.orm import declarative_base, sessionmaker, relationship from src.fastapi_quickcrud.crud_router import crud_router_builder TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() class Parent(Base): __tablename__ = 'parent_one_to_many_back_populates' id = Column(Integer, primary_key=True) children = relationship("Child", back_populates="parent") class Child(Base): __tablename__ = 'child_one_to_many_back_populates' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('parent_one_to_many_back_populates.id')) parent = relationship("Parent", back_populates="children") crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child", tags=["child"] ) crud_route_parent = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"] ) from starlette.testclient import TestClient [app.include_router(i) for i in [crud_route_parent, crud_route_child]] client = TestClient(app) def test_get_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent?join_foreign_table=child_one_to_many_back_populates', headers=headers) assert response.status_code == 200 assert response.json() == [ { "child_one_to_many_back_populates_foreign": [ { "id": 1, "parent_id": 1 }, { "id": 2, "parent_id": 1 } ], "id": 1 }, { "child_one_to_many_back_populates_foreign": [ { "id": 3, "parent_id": 2 }, { "id": 4, "parent_id": 2 } ], "id": 2 } ] response = client.get('/parent/1?join_foreign_table=child_one_to_many_back_populates', headers=headers) assert response.status_code == 200 assert response.json() == { "child_one_to_many_back_populates_foreign": [ { "id": 1, "parent_id": 1 }, { "id": 2, "parent_id": 1 } ], "id": 1 } def test_get_child_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1, "parent_id": 1 }, { "id": 2, "parent_id": 1 }, { "id": 3, "parent_id": 2 }, { "id": 4, "parent_id": 2 }] response = client.get('/child/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1, "parent_id": 1 } def test_get_many_without_join(): query = {"join_foreign_table": "child"} data = json.dumps(query) headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent', headers=headers, data=data) assert response.status_code == 200 assert response.json() == [ { "id": 1 }, { "id": 2 } ] response = client.get('/parent/1', headers=headers, data=data) assert response.status_code == 200 assert response.json() == { "id": 1 } def setup_module(module): Parent.__table__.create(engine, checkfirst=True) Child.__table__.create(engine, checkfirst=True) db = session() db.add(Parent(id=1)) db.add(Parent(id=2)) db.flush() db.add(Child(id=1, parent_id=1)) db.add(Child(id=2, parent_id=1)) db.add(Child(id=3, parent_id=2)) db.add(Child(id=4, parent_id=2)) db.commit() def teardown_module(module): Child.__table__.drop(engine, checkfirst=True) Parent.__table__.drop(engine, checkfirst=True) ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/join_relationship/test_relationship_o2m_back_ref.py ================================================ import json import os from fastapi import FastAPI from sqlalchemy import Column, Integer, \ ForeignKey from sqlalchemy.orm import declarative_base, sessionmaker, relationship from src.fastapi_quickcrud.crud_router import crud_router_builder TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() class Parent(Base): __tablename__ = 'parent_one_to_many_back_ref' id = Column(Integer, primary_key=True) children = relationship("Child", backref="child_one_to_many_back_ref") class Child(Base): __tablename__ = 'child_one_to_many_back_ref' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('parent_one_to_many_back_ref.id')) crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child", tags=["child"] ) crud_route_parent = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"] ) from starlette.testclient import TestClient [app.include_router(i) for i in [crud_route_parent, crud_route_child]] client = TestClient(app) def test_get_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent?join_foreign_table=child_one_to_many_back_ref', headers=headers) assert response.status_code == 200 assert response.json() == [ { "child_one_to_many_back_ref_foreign": [ { "id": 1, "parent_id": 1 }, { "id": 2, "parent_id": 1 } ], "id": 1 }, { "child_one_to_many_back_ref_foreign": [ { "id": 3, "parent_id": 2 }, { "id": 4, "parent_id": 2 } ], "id": 2 } ] response = client.get('/parent/1?join_foreign_table=child_one_to_many_back_ref', headers=headers) assert response.status_code == 200 assert response.json() == { "child_one_to_many_back_ref_foreign": [ { "id": 1, "parent_id": 1 }, { "id": 2, "parent_id": 1 } ], "id": 1 } def test_get_child_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1, "parent_id": 1 }, { "id": 2, "parent_id": 1 }, { "id": 3, "parent_id": 2 }, { "id": 4, "parent_id": 2 }] response = client.get('/child/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1, "parent_id": 1 } def test_get_many_without_join(): query = {"join_foreign_table": "child"} data = json.dumps(query) headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent', headers=headers, data=data) assert response.status_code == 200 assert response.json() == [ { "id": 1 }, { "id": 2 } ] response = client.get('/parent/1', headers=headers, data=data) assert response.status_code == 200 assert response.json() == { "id": 1 } def setup_module(module): Parent.__table__.create(engine, checkfirst=True) Child.__table__.create(engine, checkfirst=True) db = session() db.add(Parent(id=1)) db.add(Parent(id=2)) db.flush() db.add(Child(id=1, parent_id=1)) db.add(Child(id=2, parent_id=1)) db.add(Child(id=3, parent_id=2)) db.add(Child(id=4, parent_id=2)) db.commit() def teardown_module(module): Child.__table__.drop(engine, checkfirst=True) Parent.__table__.drop(engine, checkfirst=True) ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/join_relationship/test_relationship_o2o.py ================================================ import json import os from fastapi import FastAPI from sqlalchemy import Column, Integer, \ ForeignKey from sqlalchemy.orm import declarative_base, sessionmaker, relationship from src.fastapi_quickcrud.crud_router import crud_router_builder TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() class Parent(Base): __tablename__ = 'parent_o2o' id = Column(Integer, primary_key=True) # one-to-many collection children = relationship("Child", back_populates="parent") class Child(Base): __tablename__ = 'child_o2o' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('parent_o2o.id')) # many-to-one scalar parent = relationship("Parent", back_populates="children") def test_function(self, *args, **kwargs ): print("hello") crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child", tags=["child"] ) crud_route_parent = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"] ) from starlette.testclient import TestClient [app.include_router(i) for i in [crud_route_parent, crud_route_child]] client = TestClient(app) def test_get_parent_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent?join_foreign_table=child_o2o', headers=headers) assert response.status_code == 200 assert response.json() == [ { "child_o2o_foreign": [ { "id": 1, "parent_id": 1 }, { "id": 2, "parent_id": 1 } ], "id": 1 }, { "child_o2o_foreign": [ { "id": 3, "parent_id": 2 }, { "id": 4, "parent_id": 2 } ], "id": 2 } ] response = client.get('/parent/1?join_foreign_table=child_o2o', headers=headers) assert response.status_code == 200 assert response.json() == { "child_o2o_foreign": [ { "id": 1, "parent_id": 1 }, { "id": 2, "parent_id": 1 } ], "id": 1 } def test_get_child_many_with_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child?join_foreign_table=parent_o2o', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1, "parent_o2o_foreign": [ { "id": 1 } ], "parent_id": 1 }, { "id": 2, "parent_o2o_foreign": [ { "id": 1 } ], "parent_id": 1 }, { "id": 3, "parent_o2o_foreign": [ { "id": 2 } ], "parent_id": 2 }, { "id": 4, "parent_o2o_foreign": [ { "id": 2 } ], "parent_id": 2 } ] response = client.get('/child/1?join_foreign_table=parent_o2o', headers=headers) assert response.status_code == 200 assert response.json() =={ "id": 1, "parent_o2o_foreign": [ { "id": 1 } ], "parent_id": 1 } def test_get_child_many_without_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/parent', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1 }, { "id": 2 }, ] response = client.get('/parent/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1 } def test_get_parent_many_without_join(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.get('/child', headers=headers) assert response.status_code == 200 assert response.json() == [ { "id": 1, "parent_id": 1 }, { "id": 2, "parent_id": 1 }, { "id": 3, "parent_id": 2 }, { "id": 4, "parent_id": 2 } ] response = client.get('/child/1', headers=headers) assert response.status_code == 200 assert response.json() == { "id": 1, "parent_id": 1 } def setup_module(module): Parent.__table__.create(engine) Child.__table__.create(engine) db = session() db.add(Parent(id=1)) db.add(Parent(id=2)) db.flush() db.add(Child(id=1, parent_id=1)) db.add(Child(id=2, parent_id=1)) db.add(Child(id=3, parent_id=2)) db.add(Child(id=4, parent_id=2)) db.commit() print() def teardown_module(module): Child.__table__.drop(engine, checkfirst=True) Parent.__table__.drop(engine, checkfirst=True) ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/test_create_many_api.py ================================================ import json import uuid from datetime import date, timedelta, datetime, timezone from starlette.testclient import TestClient from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.misc.exceptions import ConflictColumnsCannotHit from tests.test_implementations.test_sqlalchemy.api_test import get_transaction_session, app, UntitledTable256 # Create Many API Test test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, prefix="/test_creation_many", crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], tags=["test"] ) [app.include_router(i) for i in [test_create_many]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def create_example_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{ "insert": [ { "bool_value": true, "char_value": "string", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963Z", "timestamptz_value": "2021-07-23T02:38:24.963Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }, { "bool_value": true, "char_value": "string", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963Z", "timestamptz_value": "2021-07-23T02:38:24.963Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }, { "bool_value": true, "char_value": "string", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963Z", "timestamptz_value": "2021-07-23T02:38:24.963Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] } ] }' response = client.post('/test_creation_many', headers=headers, data=data) assert response.status_code == 201 return response.json() def test_try_only_input_required_fields(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{ "insert": [ { "float4_value": 1, "int2_value": 1, "int4_value": 1 },{ "float4_value": 2, "int2_value": 2, "int4_value": 2 },{ "float4_value": 3, "int2_value": 3, "int4_value": 3 } ] }' data_ = json.loads(data)['insert'] response = client.post('/test_creation_many', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_try_input_with_conflict_but_conflict_columns_not_hit(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"on_conflict": {"update_columns": ["bool_value", "float8_value", "varchar_value", "interval_value", "time_value", "int8_value", "jsonb_value", "timetz_value", "array_str__value", "text_value", "char_value", "uuid_value", "array_value", "numeric_value", "timestamp_value", "int2_value", "date_value", "json_value", "timestamptz_value"]}} insert_data = [] for i in sample_data: _ = {} for k, v in i.items(): _[k] = v for k, v in {"float4_value": 99, "int2_value": 99, "int4_value": 99}.items(): _[k] = v insert_data.append(_) data['insert'] = insert_data try: _ = json.dumps(data) response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) except ConflictColumnsCannotHit as e: pass assert response.status_code == 409 def test_try_input_with_conflict(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"on_conflict": {"update_columns": ["bool_value", "float8_value", "varchar_value", "interval_value", "time_value", "int8_value", "jsonb_value", "timetz_value", "array_str__value", "text_value", "char_value", "uuid_value", "array_value", "numeric_value", "timestamp_value", "int2_value", "date_value", "json_value", "timestamptz_value"]}} insert_data = [] for i in sample_data: _ = {} for k, v in i.items(): _[k] = v for k, v in {"float8_value": 0.7}.items(): _[k] = v insert_data.append(_) data['insert'] = insert_data response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data['insert']): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == value[k] def test_try_input_without_conflict(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {} insert_data = [] for i in sample_data: _ = {} for k, v in i.items(): _[k] = v for k, v in {"float4_value": 99, "int2_value": 99, "int4_value": 99}.items(): _[k] = v insert_data.append(_) data['insert'] = insert_data response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 409 def test_update_specific_columns_when_conflict(): def update_all_fields(): headers = { 'accept': 'application/json', } response_data = create_example_data() # create the data update_column_on_conflict = { "update_columns": [ "int8_value", "numeric_value", "varchar_value", "json_value", "float8_value", "time_value", "timestamp_value", "timestamptz_value", "array_value", "bool_value", "array_str__value", "int2_value", "text_value", "uuid_value", "char_value", "jsonb_value", "interval_value", "date_value", "timetz_value" ] } tmp = {} tmp['on_conflict'] = update_column_on_conflict bool_value_change = not response_data[0]['bool_value'] char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' uuid_value_change = str(uuid.uuid4()) varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change = {} change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['uuid_value'] = uuid_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change for i in response_data: for k, v in change.items(): i[k] = v tmp['insert'] = response_data response = client.post('/test_creation_many', headers=headers, data=json.dumps(tmp)) assert response.status_code == 201 response_result = response.json() for i in response_result: for k, v in i.items(): if k in change: if isinstance(v, str): v = v.strip() assert json.dumps(change[k]).strip() == json.dumps(v).strip() def update_partial_fields_1(): headers = { 'accept': 'application/json', } response_data = create_example_data() # create the data update_column_on_conflict = { "update_columns": [ "int8_value", "numeric_value", "varchar_value", "json_value", "float8_value", "time_value", "timestamp_value", "timestamptz_value", "array_value", "bool_value", "array_str__value", ] } tmp = {} tmp['on_conflict'] = update_column_on_conflict bool_value_change = not response_data[0]['bool_value'] float8_value_change = 0.1 int8_value_change = 100 json_value_change = {"hello": "world"} numeric_value_change = 19 time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) uuid_value_change = str(uuid.uuid4()) varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change = {} change['int8_value'] = int8_value_change change['numeric_value'] = numeric_value_change change['varchar_value'] = varchar_value_change change['json_value'] = json_value_change change['float8_value'] = float8_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['array_value'] = array_value_change change['bool_value'] = bool_value_change change['array_str__value'] = array_str__value_change for i in response_data: for k, v in change.items(): i[k] = v tmp['insert'] = response_data response = client.post('/test_creation_many', headers=headers, data=json.dumps(tmp)) assert response.status_code == 201 response_result = response.json() for i in response_result: for k, v in i.items(): if k in change: if isinstance(v, str): v = v.strip() assert json.dumps(change[k]).strip() == json.dumps(v).strip() def update_partial_fields_2(): headers = { 'accept': 'application/json', } response_data = create_example_data() # create the data update_column_on_conflict = { "update_columns": [ "int2_value", "text_value", "uuid_value", "char_value", "jsonb_value", "interval_value", "date_value", "timetz_value" ] } tmp = {} tmp['on_conflict'] = update_column_on_conflict char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) int2_value_change = 100 interval_value_change = float(5400) jsonb_value_change = {"hello": "world"} text_value_change = 'hello world' timetz_value_change = '18:18:18+00:00' uuid_value_change = str(uuid.uuid4()) change = {} change['int2_value'] = int2_value_change change['text_value'] = text_value_change change['uuid_value'] = uuid_value_change change['char_value'] = char_value_change change['jsonb_value'] = jsonb_value_change change['interval_value'] = interval_value_change change['date_value'] = date_value_change change['timetz_value'] = timetz_value_change for i in response_data: for k, v in change.items(): i[k] = v tmp['insert'] = response_data response = client.post('/test_creation_many', headers=headers, data=json.dumps(tmp)) assert response.status_code == 201 response_result = response.json() for i in response_result: for k, v in i.items(): if k in change: if isinstance(v, str): v = v.strip() assert json.dumps(change[k]).strip() == json.dumps(v).strip() update_all_fields() update_partial_fields_1() update_partial_fields_2() ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/test_create_one_api.py ================================================ import json import random import uuid from datetime import date, timedelta, datetime, timezone from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.exceptions import ConflictColumnsCannotHit, UnknownColumn, UpdateColumnEmptyException from src.fastapi_quickcrud.misc.type import CrudMethods from tests.test_implementations.test_sqlalchemy.api_test import get_transaction_session, app, UntitledTable256 test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, prefix="/test_creation_one", crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], tags=["test"] ) test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, prefix="/test_creation_many", crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], tags=["test"] ) test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_post_direct_get", tags=["test"] ) test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields # Create One API Test def create_example_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_creation_one', headers=headers, data=data) assert response.status_code == 201 return response.json() def test_try_only_input_required_fields(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"float4_value": 0.0, "int2_value": 0, "int4_value": 0, 'uuid_value': '3fa85f64-5717-4562-b3fc-2c963f66afa6'} response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) assert response.status_code == 201 response_result = response.json() for k, v in data.items(): assert response_result[k] == v def test_try_input_with_conflict_but_conflict_columns_not_hit(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"on_conflict": {"update_columns": ["bool_value", "float8_value", "varchar_value", "interval_value", "time_value", "int8_value", "jsonb_value", "timetz_value", "array_str__value", "text_value", "char_value", "uuid_value", "array_value", "numeric_value", "timestamp_value", "int2_value", "date_value", "json_value", "timestamptz_value"]}} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 99, "int2_value": 99, "int4_value": 99}.items(): data[k] = v # for k, v in {"float4_value": 99.9, "int2_value": 99, "int4_value": 99}.items(): # data[k] = v try: _ = json.dumps(data) response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) except ConflictColumnsCannotHit as e: pass assert response.status_code == 409 def test_try_input_with_conflict(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"on_conflict": {"update_columns": ["bool_value", "float8_value", "varchar_value", "interval_value", "time_value", "int8_value", "jsonb_value", "timetz_value", "array_str__value", "text_value", "char_value", "uuid_value", "array_value", "numeric_value", "timestamp_value", "int2_value", "date_value", "json_value", "timestamptz_value"]}} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 0.0, "int2_value": 99, "int4_value": 0}.items(): data[k] = v response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) assert response.status_code == 201 response_result = response.json() for k, v in response_result.items(): if k in data: if isinstance(v, str): v = v.strip() assert json.dumps(data[k]).strip() == json.dumps(v).strip() def test_try_input_without_conflict(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 0.0, "int2_value": 99, "int4_value": 0}.items(): data[k] = v # data['on_conflict'] = {'update_columns': []} response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) assert response.status_code == 409 def test_update_specific_columns_when_conflict(): def update_all_fields(): headers = { 'accept': 'application/json', } sample_data = create_example_data() response = client.get(f'/test/{sample_data[primary_key_name]}', headers=headers) assert response.status_code == 200 response_data = response.json() # create the data update_column_on_conflict = { "update_columns": [ "int8_value", "numeric_value", "varchar_value", "json_value", "float8_value", "time_value", "timestamp_value", "timestamptz_value", "array_value", "bool_value", "array_str__value", "int2_value", "text_value", "uuid_value", "char_value", "jsonb_value", "interval_value", "date_value", "timetz_value" ] } response_data['on_conflict'] = update_column_on_conflict ran_num = random.randint(5, 100) bool_value_change = not response_data['bool_value'] char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' uuid_value_change = str(uuid.uuid4()) varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change = {} change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['uuid_value'] = uuid_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change for k, v in change.items(): response_data[k] = v response = client.post('/test_creation_one', headers=headers, data=json.dumps(response_data)) assert response.status_code == 201 response_result = response.json() for k, v in response_result.items(): if k in change: if isinstance(v, str): v = v.strip() assert json.dumps(change[k]).strip() == json.dumps(v).strip() def update_partial_fields(): headers = { 'accept': 'application/json', } sample_data = create_example_data() response = client.get(f'/test/{sample_data[primary_key_name]}', headers=headers) assert response.status_code == 200 response_data = response.json() # create the data update_column_on_conflict = { "update_columns": [ "varchar_value", "json_value", "float8_value", "time_value", "timestamp_value", "timestamptz_value", "array_value", "bool_value", "array_str__value", "char_value", "jsonb_value", "interval_value", "date_value", "timetz_value" ] } response_data['on_conflict'] = update_column_on_conflict ran_num = random.randint(5, 100) bool_value_change = not response_data['bool_value'] char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change = {} change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change for k, v in change.items(): response_data[k] = v response = client.post('/test_creation_one', headers=headers, data=json.dumps(response_data)) assert response.status_code == 201 response_result = response.json() for k, v in response_result.items(): if k in change: if isinstance(v, str): v = v.strip() assert json.dumps(change[k]).strip() == json.dumps(v).strip() update_all_fields() update_partial_fields() def test_try_input_with_conflict_but_missing_update_columns(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 0.0, "int2_value": 99, "int4_value": 0}.items(): data[k] = v data['on_conflict'] = {'update_columns': []} try: response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) except UpdateColumnEmptyException as e: assert True return assert False def test_try_input_with_conflict_but_unknown_update_columns(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 0.0, "int2_value": 99, "int4_value": 0}.items(): data[k] = v data['on_conflict'] = {'update_columns': ['testsetsetset']} try: response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) except UnknownColumn as e: assert True return assert False ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/test_delete_many_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods from tests.test_implementations.test_sqlalchemy.api_test import get_transaction_session, app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_one", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", tags=["test"] ) # Response Mode Test # response_many = create_many_response_model['__root__'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in response_many.items(): # assert not v.required UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # post_redirect_get_model = api_model[CrudMethods.POST_REDIRECT_GET].__dict__ # assert post_redirect_get_model['requestModel'] or post_redirect_get_model['responseModel'] # post_redirect_get_request_model = deepcopy(post_redirect_get_model['requestModel'].__dict__['__fields__']) # post_redirect_get_response_model = deepcopy(post_redirect_get_model['responseModel'].__dict__['__fields__']) # Request Model Test # for k, v in post_redirect_get_request_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Response Model Test # for k, v in post_redirect_get_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # for k, v in post_redirect_get_response_model.items(): # assert v.required test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # # FIXME some thing may not require # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.DELETE_MANY ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # # FIXME some thing may not require # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_delete_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_delete_many", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_delete_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def test_create_many_and_delete_many(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = { "insert": [ { "bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ], "time_value": "18:18:18" , "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] } response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list":True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) response = client.delete(f'/test_delete_many?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_create_many_and_delete_many_but_not_found(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = { "insert": [ { "bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ], "time_value": "18:18:18" , "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] } response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list":True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '10:18:18', "time_value____to": '12:18:18', "time_value____list": '12:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "timez_value____from": '18:18:18+00:00', "timez_value____to": '18:18:18+00:00', "timez_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) response = client.delete(f'/test_delete_many?{query_string}') assert response.status_code == 204 ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/test_delete_one_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy.api_test import get_transaction_session, app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # create_one_model = api_model[CrudMethods.UPSERT_ONE].__dict__ # assert create_one_model['requestModel'] or create_one_model['responseModel'] # create_one_request_model = deepcopy(create_one_model['requestModel'].__dict__['__fields__']) # create_one_response_model = deepcopy(create_one_model['responseModel'].__dict__['__fields__']) # Request Test # assert create_one_request_model.pop('on_conflict', False) # for k, v in create_one_request_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Response Test # for k, v in create_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_one", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # create_many_model = api_model[CrudMethods.UPSERT_MANY].__dict__ # assert create_many_model['requestModel'] or create_many_model['responseModel'] # create_many_request_model = deepcopy(create_many_model['requestModel'].__dict__['__fields__']) # create_many_response_model = deepcopy(create_many_model['responseModel'].__dict__['__fields__']) # # # Request Model Test # assert create_many_request_model.pop('on_conflict', None) # insert_many_model = create_many_request_model['insert'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in insert_many_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # # # Response Model Test # for k, v in create_many_response_model.items(): # create_many_response_model_item = v.type_.__dict__['__fields__'] # for k, v in create_many_response_model_item.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", tags=["test"] ) # Response Mode Test # response_many = create_many_response_model['__root__'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in response_many.items(): # assert not v.required UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # post_redirect_get_model = api_model[CrudMethods.POST_REDIRECT_GET].__dict__ # assert post_redirect_get_model['requestModel'] or post_redirect_get_model['responseModel'] # post_redirect_get_request_model = deepcopy(post_redirect_get_model['requestModel'].__dict__['__fields__']) # post_redirect_get_response_model = deepcopy(post_redirect_get_model['responseModel'].__dict__['__fields__']) # Request Model Test # for k, v in post_redirect_get_request_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Response Model Test # for k, v in post_redirect_get_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # for k, v in post_redirect_get_response_model.items(): # assert v.required test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # # FIXME some thing may not require # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.DELETE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # # FIXME some thing may not require # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_delete_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_delete_one", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_delete_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def test_create_one_and_delete_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key ,= [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False} response = client.delete(f'/test_delete_one/{primary_key}?{query_string}') response_data = response.json() assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_create_one_and_delete_one_but_not_found(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key ,= [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '10:18:18', "time_value____to": '12:18:18', "time_value____list": '10:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "timez_value____from": '18:18:18+00:00', "timez_value____to": '18:18:18+00:00', "timez_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False} response = client.delete(f'/test_delete_one/{primary_key}?{query_string}') assert response.status_code == 404 def test_create_one_and_delete_one_but_not_found_test_case_sensitive(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key ,= [i[primary_key_name] for i in insert_response_data] params = { "varchar_value____str": 'String', "varchar_value____str_____matching_pattern": 'case_sensitive', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False} response = client.delete(f'/test_delete_one/{primary_key}?{query_string}') assert response.status_code == 404 params = { "varchar_value____str": 'String', "varchar_value____str_____matching_pattern": 'case_insensitive', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False} response = client.delete(f'/test_delete_one/{primary_key}?{query_string}') assert response.status_code == 200 ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/test_get_many_api.py ================================================ import json from collections import OrderedDict from urllib.parse import urlencode from starlette.testclient import TestClient from src.fastapi_quickcrud.misc.exceptions import UnknownColumn, UnknownOrderType from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods from src.fastapi_quickcrud.misc.utils import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy.api_test import get_transaction_session, app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # create_many_model = api_model[CrudMethods.UPSERT_MANY].__dict__ # assert create_many_model['requestModel'] or create_many_model['responseModel'] # create_many_request_model = deepcopy(create_many_model['requestModel'].__dict__['__fields__']) # create_many_response_model = deepcopy(create_many_model['responseModel'].__dict__['__fields__']) # # # Request Model Test # assert create_many_request_model.pop('on_conflict', None) # insert_many_model = create_many_request_model['insert'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in insert_many_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # # # Response Model Test # for k, v in create_many_response_model.items(): # create_many_response_model_item = v.type_.__dict__['__fields__'] # for k, v in create_many_response_model_item.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Create Many API Test test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_find_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_get_many", tags=["test"] ) [app.include_router(i) for i in [test_create_many, test_find_many]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields # test create many def create_example_data(num=1, **kwargs): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } insert_sample_item = {"bool_value": kwargs.get('bool_value', True), "char_value": kwargs.get('char_value', 'string'), "date_value": kwargs.get('date_value', "2021-07-23"), "float4_value": kwargs.get('float4_value', 0.6), "float8_value": kwargs.get('float8_value', 0.8), "int2_value": kwargs.get('int2_value', 11), "int4_value": kwargs.get('int4_value', 1), "int8_value": kwargs.get('int8_value', 3), "interval_value": kwargs.get('interval_value', 5), "json_value": kwargs.get('json_value', {}), "jsonb_value": kwargs.get('jsonb_value', {}), "numeric_value": kwargs.get('numeric_value', 110), "text_value": kwargs.get('text_value', 'string'), "timestamp_value": kwargs.get('timestamp_value', "2021-07-23T02:38:24.963Z"), "timestamptz_value": kwargs.get('timestamptz_value', "2021-07-23T02:38:24.963Z"), "uuid_value": kwargs.get('uuid_value', "3fa85f64-5717-4562-b3fc-2c963f66afa6"), "varchar_value": kwargs.get('varchar_value', 'string'), "array_value": kwargs.get('array_value', [1, 2, 3, 4]), "array_str__value": kwargs.get('array_str__value', ["string", "string1"])} data = {'insert': [insert_sample_item for i in range(num)]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 response_result = response.json() for i in response_result: assert primary_key_name in i assert i[primary_key_name] return response_result # test pagination by offset and limit and ordering def test_pagination_and_ording(): sample_data = create_example_data(5 * 10) assert len(sample_data) == 5 * 10 limit = 5 seem = [] for num in range(0, 5 * 10, 5): response = client.get( f'/test_get_many?limit={limit}&offset={num}&order_by_columns=primary_key%20%3A%20DESC%20') response.headers['x-total-count'] == limit assert response.status_code == 200 _ = response.json() for i in _: assert i not in seem seem.append(i) assert i in sample_data # test create a new data and get by primary key def test_create_new_data_and_get_by_primary_key(): sample_data = create_example_data(10) primary_key_list = [i[primary_key_name] for i in sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key} from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in response_data: assert i['primary_key'] in primary_key_list params = {"primary_key____from": min_key, "primary_key____to": max_key, "primary_key____from_____comparison_operator": 'Greater_than', "primary_key____to_____comparison_operator": 'Less_than'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 8 for i in response_data: assert i['primary_key'] in primary_key_list # test create a more than one data which value is TRUE of boolean type, and get many def test_create_a_more_than_one_data_which_value_is_TRUE_of_boolean_type_and_get_many(): bool_false_sample_data = create_example_data(5, bool_value=False) bool_true_sample_data = create_example_data(5, bool_value=True) primary_key_list = [i[primary_key_name] for i in bool_false_sample_data] + \ [i[primary_key_name] for i in bool_true_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "In", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) + f"&bool_value____list=False" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "In", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i not in response.json() for i in bool_true_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "In", "bool_value____list": False} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Equal", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) + f"&bool_value____list=False" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Equal", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i not in response.json() for i in bool_true_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Equal", "bool_value____list": False} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i not in response.json() # params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_in", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) + f"&bool_value____list=False" response = client.get(f'/test_get_many?{query_string}') assert response.status_code == 204 params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_in", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_in", "bool_value____list": False} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i not in response.json() for i in bool_true_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_equal", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) + f"&bool_value____list=False" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_equal", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_equal", "bool_value____list": False} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i not in response.json() for i in bool_true_sample_data: assert i in response.json() # test create a more than one data of char/text/varchar type, and get many def test_create_a_more_than_one_data_and_get_many_1(): char_str_sample_data = create_example_data(5, char_value='string') char_test_sample_data = create_example_data(5, char_value='test') primary_key_list = [i[primary_key_name] for i in char_str_sample_data] + \ [i[primary_key_name] for i in char_test_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) # match_regex_with_case_sensitive/ dose not match_regex_with_case_sensitive def match_regex_with_case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "char_value____str": 'str.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: _ = response.json() assert i in _ for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "char_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_match_regex_with_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "char_value____str": 'str.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "char_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "char_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "char_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "char_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "char_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def match_regex_with_case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "char_value____str": 'STR.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "char_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # does_not_match_regex_with_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "char_value____str": 'STR.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "char_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "char_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=STR.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "char_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=STR.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'case_sensitive', "char_value____str": 'string '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'case_sensitive', "char_value____str": 'test '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_sensitive', "char_value____str": 'string '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_sensitive', "char_value____str": 'test '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_sensitive', "char_value____str": 'test '} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=string " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_insensitive', "char_value____str": 'test '} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=string " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'case_insensitive', "char_value____str": 'STRING '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'case_insensitive', "char_value____str": 'TEST '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_insensitive', "char_value____str": 'STRING '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_insensitive', "char_value____str": 'TEST '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_insensitive', "char_value____str": 'TEST '} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=STRING " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_sensitive', "char_value____str": 'TEST '} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=STRING " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def similar_to(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'similar_to', "char_value____str": 'string%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'similar_to', "char_value____str": 'test%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_similar_to', "char_value____str": 'string%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_similar_to', "char_value____str": 'test%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'similar_to'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str%&char_value____str=_es%" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'similar_to'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str%&char_value____str=_es%" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() match_regex_with_case_sensitive() match_regex_with_case_insensitive() case_sensitive() case_insensitive() similar_to() # Varchar char_str_sample_data = create_example_data(5, varchar_value='string') char_test_sample_data = create_example_data(5, varchar_value='test') primary_key_list = [i[primary_key_name] for i in char_str_sample_data] + \ [i[primary_key_name] for i in char_test_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) # match_regex_with_case_sensitive/ dose not match_regex_with_case_sensitive def match_regex_with_case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "varchar_value____str": 'str.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "varchar_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_match_regex_with_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "varchar_value____str": 'str.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "varchar_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "varchar_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "varchar_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "varchar_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "varchar_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def match_regex_with_case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "varchar_value____str": 'STR.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "varchar_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # does_not_match_regex_with_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "varchar_value____str": 'STR.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "varchar_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "varchar_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=STR.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "varchar_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=STR.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_sensitive', "varchar_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_sensitive', "varchar_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_sensitive', "varchar_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=string " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_insensitive', "varchar_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=string " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'case_insensitive', "varchar_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'case_insensitive', "varchar_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_insensitive', "varchar_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_insensitive', "varchar_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_insensitive', "varchar_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_sensitive', "varchar_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def similar_to(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'similar_to', "varchar_value____str": 'string%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'similar_to', "varchar_value____str": 'test%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_similar_to', "varchar_value____str": 'string%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_similar_to', "varchar_value____str": 'test%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'similar_to'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str%&varchar_value____str=_es%" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'similar_to'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str%&varchar_value____str=_es%" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() match_regex_with_case_sensitive() match_regex_with_case_insensitive() case_sensitive() case_insensitive() similar_to() # Text char_str_sample_data = create_example_data(5, text_value='string') char_test_sample_data = create_example_data(5, text_value='test') primary_key_list = [i[primary_key_name] for i in char_str_sample_data] + \ [i[primary_key_name] for i in char_test_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) # match_regex_with_case_sensitive/ dose not match_regex_with_case_sensitive def match_regex_with_case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "text_value____str": 'str.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "text_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_match_regex_with_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "text_value____str": 'str.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "text_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "text_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "text_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "text_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "text_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def match_regex_with_case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "text_value____str": 'STR.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "text_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # does_not_match_regex_with_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "text_value____str": 'STR.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "text_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "text_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=STR.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "text_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=STR.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'case_sensitive', "text_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'case_sensitive', "text_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_sensitive', "text_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_sensitive', "text_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_sensitive', "text_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=string " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_insensitive', "text_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=string " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'case_insensitive', "text_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'case_insensitive', "text_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_insensitive', "text_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_insensitive', "text_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_insensitive', "text_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_sensitive', "text_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def similar_to(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'similar_to', "text_value____str": 'string%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'similar_to', "text_value____str": 'test%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_similar_to', "text_value____str": 'string%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_similar_to', "text_value____str": 'test%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'similar_to'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str%&text_value____str=_es%" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'similar_to'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str%&text_value____str=_es%" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() match_regex_with_case_sensitive() match_regex_with_case_insensitive() case_sensitive() case_insensitive() similar_to() # test create a more than one data of float4/text/varchar type, and get many def test_create_a_more_than_one_data_and_get_many_2(): float_one = 5.5 float_two = 10.7 # float 4 <= will round down to the odd floating even # data = 0.4 # <= 0.4 # result = [] # data = 0.4 # <= 0.5 # result = [0.4] num_one_sample_data = create_example_data(5, float4_value=float_one) num_two_sample_data = create_example_data(5, float4_value=float_two) primary_key_list = [i[primary_key_name] for i in num_one_sample_data] + \ [i[primary_key_name] for i in num_two_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) def greater_than_or_equal_to_Less_than_or_equal_to(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "float4_value____from_____comparison_operator": 'Greater_than_or_equal_to', "float4_value____to_____comparison_operator": 'Less_than_or_equal_to', "float4_value____from": float_one, "float4_value____to": float_two} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in num_one_sample_data: assert i in response.json() for i in num_two_sample_data: assert i in response.json() # data = 10.7 # < 10.7 # still got 10.7 but if data is 10.6 def less_than_or_equal_to_less_than(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "float4_value____from_____comparison_operator": 'Greater_than', "float4_value____to_____comparison_operator": 'Less_than', "float4_value____from": float_one, "float4_value____to": float_two+0.1} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in num_one_sample_data: assert i not in response.json() for i in num_two_sample_data: assert i in response.json() greater_than_or_equal_to_Less_than_or_equal_to() less_than_or_equal_to_less_than() # float 4 < will round down to the odd floating odd # data = 0.3 # <= 0.4 # result = [] # data = 0.4 # <= 0.5 # result = [0.4] float_one = 5.5 float_two = 10.6 num_one_sample_data = create_example_data(5, float8_value=float_one) num_two_sample_data = create_example_data(5, float8_value=float_two) primary_key_list = [i[primary_key_name] for i in num_one_sample_data] + \ [i[primary_key_name] for i in num_two_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) def greater_than_or_equal_to_Less_than_or_equal_to(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "float8_value____from_____comparison_operator": 'Greater_than_or_equal_to', "float8_value____to_____comparison_operator": 'Less_than_or_equal_to', "float8_value____from": float_one, "float8_value____to": float_two} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in num_one_sample_data: assert i in response.json() for i in num_two_sample_data: assert i in response.json() def less_than_or_equal_to_less_than(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "float8_value____from_____comparison_operator": 'Greater_than', "float8_value____to_____comparison_operator": 'Less_than', "float8_value____from": float_one, "float8_value____to": float_two+0.1} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in num_one_sample_data: assert i not in response.json() for i in num_two_sample_data: assert i in response.json() greater_than_or_equal_to_Less_than_or_equal_to() less_than_or_equal_to_less_than() def test_get_many_with_ordering_unknown_column(): try: response = client.get(f'/test_get_many?order_by_columns=testestset') except UnknownColumn as e: assert str(e) == "column testestset is not exited" return assert False def test_get_many_with_ordering_with_default_order(): response = client.get(f'/test_get_many?order_by_columns=primary_key&limit=10&offset=0') a = response.json() init = 1 for i in a: assert i['primary_key'] == init init += 1 def test_get_many_with_ordering_with_ASC(): response = client.get(f'/test_get_many?order_by_columns=primary_key:ASC&limit=10&offset=0') a = response.json() init = 1 for i in a: assert i['primary_key'] == init init += 1 def test_get_many_with_ordering_with_DESC(): response = client.get(f'/test_get_many?order_by_columns=primary_key:DESC&limit=10&offset=10') a = response.json() init = a[0]['primary_key'] for i in a: assert i['primary_key'] == init init -= 1 def test_get_many_with_unknown_order_tyoe(): try: response = client.get(f'/test_get_many?order_by_columns=primary_key:DESCSS&limit=10&offset=0') except UnknownOrderType as e: assert str(e) == 'Unknown order type DESCSS, only accept DESC or ASC' return assert False def test_get_many_with_ordering_with_empty_input_list(): try: response = client.get(f'/test_get_many?order_by_columns=') except Exception as e: assert False assert True test_create_a_more_than_one_data_and_get_many_1() ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/test_get_one_api.py ================================================ import json from starlette.testclient import TestClient from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy.api_test import get_transaction_session, app, UntitledTable256 test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) [app.include_router(i) for i in [test_get_data, test_create_one]] client = TestClient(app) # create a sample data headers = { 'accept': '*/*', 'Content-Type': 'application/json', } data = '{ "bool_value": true, "char_value": "string", "date_value": "2021-07-26", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-26T02:17:46.846Z", "timestamptz_value": "2021-07-26T02:17:46.846Z", "timetz_value": "18:18:18+00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }' response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_data = response.json() dict_data = json.loads(data) sample_primary_key = response_data['primary_key'] ''' { "primary_key": 1013, "interval_value": 0, <- querying not supported "json_value": {},<- querying not supported "jsonb_value": {},<- querying not supported "array_value": [ 0 ], "array_str__value": [ "string" ] } ''' # try find the data by primary key def test_get_by_primary_key_without_any_query_param(): response = client.get(f'/test/{sample_primary_key}', headers=headers) assert response.status_code == 200 assert response.json()['primary_key'] == sample_primary_key # "bool_value": true # try find the data by primary key but false by bool def test_get_by_primary_key_with_false_bool_query_param(): response = client.get(f'/test/{sample_primary_key}?bool_value____list=false', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?bool_value____list=true', headers=headers) assert response.status_code == 200 # "char_value": "string ", # try find the data by primary key but false by char def test_get_by_primary_key_with_false_char_query_param(): response = client.get(f'/test/{sample_primary_key}?char_value____list=string1&char_value____list=string2', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?char_value____list=string&char_value____list=string1&', headers=headers) assert response.status_code == 200 # Like operator response = client.get( f'/test/{sample_primary_key}?char_value____str=string1&char_value____str=%tri%&char_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=string1&char_value____str=%tsri%&char_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 404 # Ilike operator response = client.get( f'/test/{sample_primary_key}?char_value____str=string1&char_value____str=%tRi%&char_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=string1&char_value____str=%tsri%&char_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 404 # not like operator response = client.get( f'/test/{sample_primary_key}?char_value____str=string2&char_value____str=%strg%&char_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=string%&char_value____str=%strin%&char_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 404 # not ilike operator response = client.get( f'/test/{sample_primary_key}?char_value____str=String2&char_value____str=%Strg%&char_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=STRING%&char_value____str=%TRI%&char_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 404 # match regex with case sensitive operator response = client.get( f'/test/{sample_primary_key}?char_value____str=stri.*&varchar_value____stg=str&char_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=stg.*&char_value____str=stg&char_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) assert response.status_code == 404 # match regex with case insensitive operator response = client.get( f'/test/{sample_primary_key}?char_value____str=strI.*&char_value____str=STG&char_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=stG.*&char_value____str=STG&char_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) assert response.status_code == 404 # does_not_match_regex_with_case_insensitive response = client.get( f'/test/{sample_primary_key}?char_value____str=strI.*&char_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?char_value____str=stG.*&char_value____str=STG&char_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) assert response.status_code == 200 # dose not match regex with case sensitive operator response = client.get( f'/test/{sample_primary_key}?char_value____str=stri.*&varchar_value____stg=str&char_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?char_value____str=stg.*&char_value____str=stg&char_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) assert response.status_code == 200 # similar_to response = client.get( f'/test/{sample_primary_key}?char_value____str=string&char_value____str=%(r|z)%&char_value____str_____matching_pattern=similar_to', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=str&char_value____str=(r|z)%&char_value____str_____matching_pattern=similar_to', headers=headers) assert response.status_code == 404 # not_similar_to response = client.get( f'/test/{sample_primary_key}?char_value____str=string%&char_value____str=%(r|z)%&char_value____str_____matching_pattern=not_similar_to', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?char_value____str=str&char_value____str=(r|z)%&char_value____str_____matching_pattern=not_similar_to', headers=headers) assert response.status_code == 200 # "float4_value": 0, # try find the data by primary key but false by float4 def test_get_by_primary_key_with_false_float4_query_param(): # from response = client.get(f'/test/{sample_primary_key}?float4_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?float4_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??float4_value____from=-2&float4_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?float4_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?float4_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?float4_value____from=0&float4_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?float4_value____from=0&float4_value____to=0&float4_value____from_____comparison_operator=Greater_than_or_equal_to&float4_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?float4_value____from=-1&float4_value____to=2&float4_value____from_____comparison_operator=Greater_than&float4_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?float4_value____from=1&float4_value____to=2&float4_value____from_____comparison_operator=Greater_than&float4_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?float4_value____from=1&float4_value____to=2&float4_value____from_____comparison_operator=Greater_than_or_equal_to&float4_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # "float8_value": 0, # try find the data by primary key but false by float8 def test_get_by_primary_key_with_false_float8_query_param(): # from response = client.get(f'/test/{sample_primary_key}?float8_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?float8_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??float8_value____from=-2&float8_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?float8_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?float8_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?float8_value____from=0&float8_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?float8_value____from=0&float8_value____to=0&float8_value____from_____comparison_operator=Greater_than_or_equal_to&float8_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?float8_value____from=-1&float8_value____to=2&float8_value____from_____comparison_operator=Greater_than&float8_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?float8_value____from=1&float8_value____to=2&float8_value____from_____comparison_operator=Greater_than&float8_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?float8_value____from=1&float8_value____to=2&float8_value____from_____comparison_operator=Greater_than_or_equal_to&float8_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by int2 # int2 0 def test_get_by_primary_key_with_false_int2_query_param(): # from response = client.get(f'/test/{sample_primary_key}?int2_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?int2_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??int2_value____from=-2&int2_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?int2_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?int2_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?int2_value____from=0&int2_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int2_value____from=0&int2_value____to=0&int2_value____from_____comparison_operator=Greater_than_or_equal_to&int2_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int2_value____from=-1&int2_value____to=2&int2_value____from_____comparison_operator=Greater_than&int2_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int2_value____from=1&int2_value____to=2&int2_value____from_____comparison_operator=Greater_than&int2_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int2_value____from=1&int2_value____to=2&int2_value____from_____comparison_operator=Greater_than_or_equal_to&int2_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by int4 # int 4 0 def test_get_by_primary_key_with_false_int4_query_param(): # from response = client.get(f'/test/{sample_primary_key}?int4_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?int4_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??int4_value____from=-2&int4_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?int4_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?int4_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?int4_value____from=0&int4_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int4_value____from=0&int4_value____to=0&int4_value____from_____comparison_operator=Greater_than_or_equal_to&int4_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int4_value____from=-1&int4_value____to=2&int4_value____from_____comparison_operator=Greater_than&int4_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int4_value____from=1&int4_value____to=2&int4_value____from_____comparison_operator=Greater_than&int4_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int4_value____from=1&int4_value____to=2&int4_value____from_____comparison_operator=Greater_than_or_equal_to&int4_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by int8 # int 8 0 def test_get_by_primary_key_with_false_int8_query_param(): # from response = client.get(f'/test/{sample_primary_key}?int8_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?int8_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??int8_value____from=-2&int8_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?int8_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?int8_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?int8_value____from=0&int8_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int8_value____from=0&int8_value____to=0&int8_value____from_____comparison_operator=Greater_than_or_equal_to&int8_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int8_value____from=-1&int8_value____to=2&int8_value____from_____comparison_operator=Greater_than&int8_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int8_value____from=1&int8_value____to=2&int8_value____from_____comparison_operator=Greater_than&int8_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int8_value____from=1&int8_value____to=2&int8_value____from_____comparison_operator=Greater_than_or_equal_to&int8_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by numeric # numeric 0 def test_get_by_primary_key_with_false_numeric_query_param(): # from response = client.get(f'/test/{sample_primary_key}?numeric_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?numeric_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??numeric_value____from=-2&numeric_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?numeric_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?numeric_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?numeric_value____from=0&numeric_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?numeric_value____from=0&numeric_value____to=0&numeric_value____from_____comparison_operator=Greater_than_or_equal_to&numeric_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?numeric_value____from=-1&numeric_value____to=2&numeric_value____from_____comparison_operator=Greater_than&numeric_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?numeric_value____from=1&numeric_value____to=2&numeric_value____from_____comparison_operator=Greater_than&numeric_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?numeric_value____from=1&numeric_value____to=2&numeric_value____from_____comparison_operator=Greater_than_or_equal_to&numeric_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by text # "text_value": "string", def test_get_by_primary_key_with_false_text_query_param(): response = client.get(f'/test/{sample_primary_key}?text_value____list=string1&text_value____list=string2', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?text_value____list=string&text_value____list=string1&', headers=headers) assert response.status_code == 200 # Like operator response = client.get(f'/test/{sample_primary_key}?text_value____str=string1&text_value____str=%tri%&text_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?text_value____str=string1&text_value____str=%tsri%&text_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 404 # Ilike operator response = client.get(f'/test/{sample_primary_key}?text_value____str=string1&text_value____str=%tRi%&text_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?text_value____str=string1&text_value____str=%tsri%&text_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 404 # not like operator response = client.get(f'/test/{sample_primary_key}?text_value____str=string2&text_value____str=%strg%&text_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?text_value____str=string&text_value____str=%strin%&text_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 404 # not ilike operator response = client.get(f'/test/{sample_primary_key}?text_value____str=String2&text_value____str=%Strg%&text_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?text_value____str=STRING&text_value____str=%TRI%&text_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 404 # match regex with case sensitive operator response = client.get(f'/test/{sample_primary_key}?text_value____str=stri.*&varchar_value____stg=str&text_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?text_value____str=stg.*&text_value____str=stg&text_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) assert response.status_code == 404 # match regex with case insensitive operator response = client.get(f'/test/{sample_primary_key}?text_value____str=strI.*&text_value____str=STG&text_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?text_value____str=stG.*&text_value____str=STG&text_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) assert response.status_code == 404 # does_not_match_regex_with_case_insensitive response = client.get(f'/test/{sample_primary_key}?text_value____str=strI.*&text_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?text_value____str=stG.*&text_value____str=STG&text_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) assert response.status_code == 200 # dose not match regex with case sensitive operator response = client.get(f'/test/{sample_primary_key}?text_value____str=stri.*&varchar_value____stg=str&text_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?text_value____str=stg.*&text_value____str=stg&text_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) assert response.status_code == 200 # similar_to response = client.get(f'/test/{sample_primary_key}?text_value____str=string&text_value____str=%(r|z)%&text_value____str_____matching_pattern=similar_to', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?text_value____str=str&text_value____str=(r|z)%&text_value____str_____matching_pattern=similar_to', headers=headers) assert response.status_code == 404 # not_similar_to response = client.get(f'/test/{sample_primary_key}?text_value____str=string&text_value____str=%(r|z)%&text_value____str_____matching_pattern=not_similar_to', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?text_value____str=str&text_value____str=(r|z)%&text_value____str_____matching_pattern=not_similar_to', headers=headers) assert response.status_code == 200 # try find the data by primary key but false by uuid def test_get_by_primary_key_with_false_uuid_query_param(): # In operator response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa6&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afb6', headers=headers) assert response.status_code == 404 # not In operator response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa6&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list_____comparison_operator=Not_in', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afb6&uuid_value____list_____comparison_operator=Not_in', headers=headers) assert response.status_code == 200 # Equal operator response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa6&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list_____comparison_operator=Equal', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afb6&uuid_value____list_____comparison_operator=Equal', headers=headers) assert response.status_code == 404 # not Equal operator response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa6&uuid_value____list_____comparison_operator=Not_equal', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afb6&uuid_value____list_____comparison_operator=Not_equal', headers=headers) assert response.status_code == 200 # try find the data by primary key but false by varchar def test_get_by_primary_key_with_false_varchar_query_param(): response = client.get(f'/test/{sample_primary_key}?varchar_value____list=string1&varchar_value____list=string2', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?varchar_value____list=string&varchar_value____list=string1&', headers=headers) assert response.status_code == 200 # Like operator response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string1&varchar_value____str=%tri%&varchar_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string1&varchar_value____str=%tsri%&varchar_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 404 # Ilike operator response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string1&varchar_value____str=%tRi%&varchar_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string1&varchar_value____str=%tsri%&varchar_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 404 # not like operator response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string2&varchar_value____str=%strg%&varchar_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string&varchar_value____str=%strin%&varchar_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 404 # not ilike operator response = client.get(f'/test/{sample_primary_key}?varchar_value____str=String2&varchar_value____str=%Strg%&varchar_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=STRING&varchar_value____str=%TRI%&varchar_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 404 # match regex with case sensitive operator response = client.get(f'/test/{sample_primary_key}?varchar_value____str=stri.*&varchar_value____stg=str&varchar_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=stg.*&varchar_value____str=stg&varchar_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) assert response.status_code == 404 # match regex with case insensitive operator response = client.get(f'/test/{sample_primary_key}?varchar_value____str=strI.*&varchar_value____str=STG&varchar_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=stG.*&varchar_value____str=STG&varchar_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) assert response.status_code == 404 # does_not_match_regex_with_case_insensitive response = client.get(f'/test/{sample_primary_key}?varchar_value____str=strI.*&varchar_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=stG.*&varchar_value____str=STG&varchar_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) assert response.status_code == 200 # dose not match regex with case sensitive operator response = client.get(f'/test/{sample_primary_key}?varchar_value____str=stri.*&varchar_value____stg=str&varchar_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=stg.*&varchar_value____str=stg&varchar_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) assert response.status_code == 200 # similar_to response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string&varchar_value____str=%(r|z)%&varchar_value____str_____matching_pattern=similar_to', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=str&varchar_value____str=(r|z)%&varchar_value____str_____matching_pattern=similar_to', headers=headers) assert response.status_code == 404 # not_similar_to response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string&varchar_value____str=%(r|z)%&varchar_value____str_____matching_pattern=not_similar_to', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=str&varchar_value____str=(r|z)%&varchar_value____str_____matching_pattern=not_similar_to', headers=headers) assert response.status_code == 200 # query by range of date field def test_get_by_primary_key_with_false_date_range_query_param(): # from response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-27', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?date_value____to=2021-07-24', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??date_value____from=2021-07-21&date_value____to=2021-07-24', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-24', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?date_value____to=2021-07-27', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-24&date_value____to=2021-07-27', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-26&date_value____to=2021-07-26&date_value____from_____comparison_operator=Greater_than_or_equal_to&date_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-25&date_value____to=2021-07-27&date_value____from_____comparison_operator=Greater_than&date_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-26&date_value____to=2021-07-26&date_value____from_____comparison_operator=Greater_than&date_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-27&date_value____to=2021-07-29&date_value____from_____comparison_operator=Greater_than_or_equal_to&date_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 def test_get_by_primary_key_with_false_time_range_query_param(): # from response = client.get(f'/test/{sample_primary_key}?time_value____from=19:18:18', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?time_value____to=17:18:18', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}?time_value____from=10:18:18&time_value____to=17:18:18', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?time_value____from=10:18:18', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?time_value____to=19:18:18', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?time_value____from=10:18:18&time_value____to=19:18:18', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?time_value____from=18:18:18&time_value____to=18:18:18&time_value____from_____comparison_operator=Greater_than_or_equal_to&time_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?time_value____from=18:18:17&time_value____to=18:18:19&time_value____from_____comparison_operator=Greater_than&time_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?time_value____from=18:18:18&time_value____to=18:18:18&time_value____from_____comparison_operator=Greater_than&time_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?time_value____from=19:18:18&time_value____to=19:19:18&time_value____from_____comparison_operator=Greater_than_or_equal_to&time_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 def test_get_by_primary_key_with_false_timestamp_range_query_param(): # "timestamp_value": "2021-07-26T02:17:46.846000", # from response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-27T02:17:46.846000', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?timestamp_value____to=2021-07-25T02:17:46.846000', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-20T02:17:46.846000×tamp_value____to=2021-07-25T02:17:46.846000', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-24T02:17:46.846000', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?timestamp_value____to=2021-07-28T02:17:46.846000', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-24T02:17:46.846000×tamp_value____to=2021-07-28T02:17:46.846000', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-26T02:17:46.846×tamp_value____to=2021-07-26T02:17:46.846Z×tampt_value____from_____comparison_operator=Greater_than_or_equal_to×tampt_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-26T02:17:46.746Z×tamp_value____to=2021-07-26T02:17:46.946Z×tampt_value____from_____comparison_operator=Greater_than×tampt_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-26T02:17:46.846Z×tamp_value____to=2021-07-26T02:17:46.946Z×tamp_value____from_____comparison_operator=Greater_than×tamp_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-26T02:17:46.856Z×tamp_value____to=2021-07-26T02:17:46.986Z×tamp_value____from_____comparison_operator=Greater_than_or_equal_to×tamp_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 def test_get_by_primary_key_with_false_timetz_range_query_param(): # from response = client.get(f'/test/{sample_primary_key}?timetz_value____from=19%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?timetz_value____to=17%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}?timetz_value____from=16%3A18%3A18%2B00%3A00&timetz_value____to=17%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?timetz_value____from=17%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?timetz_value____to=19%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?timetz_value____from=16%3A18%3A18%2B00%3A00&timetz_value____to=19%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timetz_value____from_____comparison_operator=Greater_than&timetz_value____to_____comparison_operator=Less_than&timetz_value____from=17%3A18%3A18%2B00&timetz_value____to=19%3A18%3A18%2B00', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timetz_value____from_____comparison_operator=Greater_than_or_equal_to&timetz_value____to_____comparison_operator=Less_than_or_equal_to&timetz_value____from=18%3A18%3A18%2B00&timetz_value____to=18%3A19%3A18%2B00', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timetz_value____from_____comparison_operator=Greater_than&timetz_value____to_____comparison_operator=Less_than&timetz_value____from=16%3A18%3A18%2B00&timetz_value____to=18%3A18%3A18%2B00', headers=headers) assert response.status_code == 404 # failure from - to with special operator response = client.get(f'/test/{sample_primary_key}?timetz_value____from_____comparison_operator=Greater_than_or_equal_to&timetz_value____to_____comparison_operator=Less_than_or_equal_to&timetz_value____from=16%3A18%3A18%2B00&timetz_value____to=17%3A19%3A18%2B00', headers=headers) assert response.status_code == 404 def test_get_by_primary_key_with_false_timestamptz_range_query_param(): # "timestamp_value": "2021-07-26T02:17:46.846000", # from response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-27T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?timestamptz_value____to=2021-07-25T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-27T02%3A17%3A46.846000%2B00%3A00×tamptz_value____to=2021-07-28T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-20T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?timestamptz_value____to=2021-07-29T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-20T02%3A17%3A46.846000%2B00%3A00×tamptz_value____to=2021-07-27T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-26T02%3A17%3A46.846Z×tamptz_value____to=2021-07-26T02%3A17%3A46.846Z×tamptz_value____from_____comparison_operator=Greater_than_or_equal_to×tamptz_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-26T02%3A17%3A46.800Z×tamptz_value____to=2021-07-26T02%3A17%3A46.946Z×tamptz_value____from_____comparison_operator=Greater_than×tamptz_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-26T02%3A17%3A46.846Z×tamptz_value____to=2021-07-26T02%3A17%3A46.900Z×tamptz_value____from_____comparison_operator=Greater_than×tamptz_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-26T02%3A17%3A46.847Z×tamptz_value____to=2021-07-26T02%3A17%3A46.946Z×tamptz_value____from_____comparison_operator=Greater_than_or_equal_to×tamptz_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/test_other_default_value.py ================================================ import json import os from copy import deepcopy from datetime import datetime, timezone, date, timedelta from http import HTTPStatus from urllib.parse import urlencode from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker from starlette.testclient import TestClient from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = async_session() yield db finally: db.close() class UUIDTable(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_default_value_sync' __table_args__ = ( UniqueConstraint('primary_key', 'int4_value', 'float4_value'), ) primary_key = Column(UUID(as_uuid=True), primary_key=True, info={'alias_name': 'primary_key'}, server_default=text("uuid_generate_v4()")) bool_value = Column(Boolean, nullable=False, default=False) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) UUIDTable.__table__.create(engine, checkfirst=True) route_1 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.FIND_MANY, CrudMethods.UPSERT_MANY, CrudMethods.UPDATE_ONE, CrudMethods.UPDATE_MANY, CrudMethods.PATCH_MANY, CrudMethods.PATCH_ONE, CrudMethods.DELETE_MANY, CrudMethods.DELETE_ONE, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) route_2 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.UPSERT_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_2", tags=["test"] ) route_3 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_3", tags=["test"] ) [app.include_router(i) for i in [route_1, route_2, route_3]] client = TestClient(app) def test_get_one_data_and_create_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() find_target = create_response['primary_key'] response = client.get(f'/test/{find_target}', headers=headers, data=data) assert response.status_code == 200 assert response.json() == create_response create_response.pop('primary_key') query_param = urlencode(create_response) response = client.get(f'/test/{find_target}?{query_param}', headers=headers, data=data) assert response.status_code == 200 def test_get_many_data_and_create_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '''{ "insert": [ { "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00","varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }, { "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] },{ "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] } ] }''' data_dict = json.loads(data)['insert'] response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_dict): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_update_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() created_primary_key = create_response['primary_key'] update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} query_param = urlencode(update_data) response = client.put(f'/test/{created_primary_key}?{query_param}', data=json.dumps(update_data)) update_data["bool_value"] = False response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_update_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test?{query_string}', data=json.dumps(update_data)) update_data["bool_value"] = False response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: assert k[i] == update_data[i] def test_patch_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) update_data = {"bool_value": False} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(params) update_data = {"char_value": "string_u "} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(params) update_data = {"date_value": "2022-07-24"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(params) update_data = {"char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) update_data['bool_value'] = False response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_patch_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value": True, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test?{query_string}', data=json.dumps(update_data)) update_data['bool_value'] = True response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_delete_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) response = client.delete(f'/test/{primary_key}?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_delete_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' response = client.delete(f'/test?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_post_redirect_get_data(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_3', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() response_data['bool_value'] = False assert 'primary_key' in response_data for k, v in response_data.items(): if k in change: if isinstance(v, str): v = v.strip() response_ = json.dumps(v).strip() request_ = json.dumps(change[k]).strip() assert request_ == response_ return response_data def test_upsert_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 10 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k, v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 # conflict upsert_data = deepcopy(updated_data) upsert_data['on_conflict'] = {'update_columns': ['numeric_value']} response = client.post('/test_2', headers=headers, data=json.dumps(dict(upsert_data, **json.loads(data)))) assert response.status_code == 201 # create response = client.post('/test_2', headers=headers, data=json.dumps(dict(updated_data, **json.loads(data)))) assert response.status_code == 409 ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/test_other_set_description.py ================================================ import json import os import uuid from copy import deepcopy from datetime import datetime, timezone, date, timedelta from http import HTTPStatus from urllib.parse import urlencode from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = async_session() yield db finally: db.close() class UUIDTable(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_default_value_sync' __table_args__ = ( UniqueConstraint('primary_key', 'int4_value', 'float4_value'), ) primary_key = Column(UUID(as_uuid=True), primary_key=True, comment='this is a primary_key', server_default=text("uuid_generate_v4()")) bool_value = Column(Boolean, nullable=False, default=False) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) UUIDTable.__table__.create(engine, checkfirst=True) route_1 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.FIND_MANY, CrudMethods.UPSERT_MANY, CrudMethods.UPDATE_ONE, CrudMethods.UPDATE_MANY, CrudMethods.PATCH_MANY, CrudMethods.PATCH_ONE, CrudMethods.DELETE_MANY, CrudMethods.DELETE_ONE, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) route_2 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.UPSERT_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_2", tags=["test"] ) route_3 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_3", tags=["test"] ) [app.include_router(i) for i in [route_1, route_2, route_3]] client = TestClient(app) def test_get_one_data_and_create_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() find_target = create_response['primary_key'] response = client.get(f'/test/{find_target}', headers=headers, data=data) assert response.status_code == 200 assert response.json() == create_response create_response.pop('primary_key') query_param = urlencode(create_response) response = client.get(f'/test/{find_target}?{query_param}', headers=headers, data=data) assert response.status_code == 200 def test_get_many_data_and_create_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '''{ "insert": [ { "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00","varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }, { "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] },{ "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] } ] }''' data_dict = json.loads(data)['insert'] response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_dict): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_update_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() created_primary_key = create_response['primary_key'] update_data = { "bool_value":False,"char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} query_param = urlencode(update_data) response = client.put(f'/test/{created_primary_key}?{query_param}', data=json.dumps(update_data)) update_data["bool_value"] = False response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_update_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, { "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params)+f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value":False,"char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test?{query_string}', data=json.dumps(update_data)) update_data["bool_value"] = False response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: assert k[i] == update_data[i] def test_patch_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) update_data = {"bool_value": False} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(params) update_data = {"char_value": "string_u "} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(params) update_data = {"date_value": "2022-07-24"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(params) update_data = {"char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) update_data['bool_value'] = False response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_patch_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, { "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value": True, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00","varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test?{query_string}', data=json.dumps(update_data)) update_data['bool_value'] = True response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_delete_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) response = client.delete(f'/test/{primary_key}?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_delete_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{ "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, { "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, { "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' response = client.delete(f'/test?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_post_redirect_get_data(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_3', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() response_data['bool_value'] = False assert 'primary_key' in response_data for k, v in response_data.items(): if k in change: if isinstance(v, str): v = v.strip() response_ = json.dumps(v).strip() request_ = json.dumps(change[k]).strip() assert request_ == response_ return response_data def test_upsert_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 10 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k,v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 # conflict upsert_data = deepcopy(updated_data) upsert_data['on_conflict'] = {'update_columns':['numeric_value']} response = client.post('/test_2', headers=headers, data=json.dumps(dict(upsert_data, **json.loads(data)))) assert response.status_code == 201 # create response = client.post('/test_2', headers=headers, data=json.dumps(dict(updated_data, **json.loads(data)))) assert response.status_code == 409 test_post_redirect_get_data() ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/test_other_single_unique.py ================================================ import json import os import uuid from copy import deepcopy from datetime import datetime, timezone, date, timedelta from http import HTTPStatus from urllib.parse import urlencode from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = async_session() yield db finally: db.close() class UUIDTable(Base): __tablename__ = 'test_single_unique_table_model' id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("uuid_generate_v4()")) bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False,unique=True) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=True) int4_value = Column(Integer, nullable=True) int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) def setup_module(module): UUIDTable.__table__.create(engine) route_1 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.FIND_MANY, CrudMethods.UPSERT_MANY, CrudMethods.UPDATE_ONE, CrudMethods.UPDATE_MANY, CrudMethods.PATCH_MANY, CrudMethods.PATCH_ONE, CrudMethods.DELETE_MANY, CrudMethods.DELETE_ONE, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) route_2 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.UPSERT_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_2", tags=["test"] ) route_3 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_3", tags=["test"] ) [app.include_router(i) for i in [route_1, route_2, route_3]] client = TestClient(app) def test_get_one_data_and_create_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0.443}' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() find_target = create_response['id'] response = client.get(f'/test/{find_target}', headers=headers, data=data) assert response.status_code == 200 assert response.json() == create_response create_response.pop('id') query_param = urlencode(create_response) response = client.get(f'/test/{find_target}?{query_param}', headers=headers, data=data) assert response.status_code == 200 def test_get_many_data_and_create_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '''{ "insert": [ { "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0.12, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00","varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }, { "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 1.2, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] },{ "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 9.3, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] } ] }''' data_dict = json.loads(data)['insert'] response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_dict): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_update_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0.98}' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() created_primary_key = create_response['id'] update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 12.7, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} query_param = urlencode(update_data) response = client.put(f'/test/{created_primary_key}?{query_param}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_update_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 3.5, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 3.6, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 3.7, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['id'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 200, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params)+f'&id____list={primary_key_list[0]}&id____list={primary_key_list[1]}&id____list={primary_key_list[2]}&float4_value____list=3.5&float4_value____list=3.6&float4_value____list=3.7' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.58, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test?{query_string}', data=json.dumps(update_data)) # FIXME: update the unique column will conflict, it may not a issue, because it should input all columns, you can use the patch assert response.status_code == 409 # response_data = response.json() # assert len(response_data) == 3 # for k in response_data: # for i in update_data: # assert k[i] == update_data[i] def test_patch_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 5.78, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['id'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 500, "float4_value____list": 5.78, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) update_data = {"bool_value": False} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(params) update_data = {"char_value": "string_u "} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(params) update_data = {"date_value": "2022-07-24"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(params) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 1.70, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_patch_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.91, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.92, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.93, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['id'] for i in insert_response_data] params = { "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 500, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&id____list={primary_key_list[0]}&id____list={primary_key_list[1]}&id____list={primary_key_list[2]}&float4_value____list=0.91&float4_value____list=0.92&float4_value____list=0.93' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00","varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_delete_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 2.54, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['id'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 500, "float4_value____list": 2.54, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) response = client.delete(f'/test/{primary_key}?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_delete_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.875, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.876, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.877, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['id'] for i in insert_response_data] params = { "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 500, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&id____list={primary_key_list[0]}&id____list={primary_key_list[1]}&id____list={primary_key_list[2]}&float4_value____list=0.875&float4_value____list=0.876&&float4_value____list=0.877' response = client.delete(f'/test?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_post_redirect_get_data(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} bool_value_change = False char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 55.7 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_3', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() assert 'id' in response_data for k, v in response_data.items(): if k in change: if isinstance(v, str): v = v.strip() response_ = json.dumps(v).strip() request_ = json.dumps(change[k]).strip() assert request_ == response_ return response_data def test_upsert_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 12.784}' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k,v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 # conflict upsert_data = deepcopy(updated_data) upsert_data['on_conflict'] = {'update_columns':['numeric_value']} response = client.post('/test_2', headers=headers, data=json.dumps(dict(upsert_data, **json.loads(data)))) assert response.status_code == 201 # create response = client.post('/test_2', headers=headers, data=json.dumps(dict(updated_data, **json.loads(data)))) assert response.status_code == 409 def teardown_module(module): UUIDTable.__table__.drop(engine, checkfirst=True) ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/test_other_uuid_primary.py ================================================ import json import os import uuid from copy import deepcopy from datetime import datetime, timezone, date, timedelta from http import HTTPStatus from urllib.parse import urlencode from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = async_session() yield db finally: db.close() class UUIDTable(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_uuid_primary_sync' __table_args__ = ( UniqueConstraint('primary_key', 'int4_value', 'float4_value'), ) primary_key = Column(UUID(as_uuid=True), primary_key=True, info={'alias_name': 'primary_key'}, server_default=text("uuid_generate_v4()")) bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) UUIDTable.__table__.create(engine, checkfirst=True) route_1 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.FIND_MANY, CrudMethods.UPSERT_MANY, CrudMethods.UPDATE_ONE, CrudMethods.UPDATE_MANY, CrudMethods.PATCH_MANY, CrudMethods.PATCH_ONE, CrudMethods.DELETE_MANY, CrudMethods.DELETE_ONE, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) route_2 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.UPSERT_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_2", tags=["test"] ) route_3 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_3", tags=["test"] ) [app.include_router(i) for i in [route_1, route_2, route_3]] client = TestClient(app) def test_get_one_data_and_create_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() find_target = create_response['primary_key'] response = client.get(f'/test/{find_target}', headers=headers, data=data) assert response.status_code == 200 assert response.json() == create_response create_response.pop('primary_key') query_param = urlencode(create_response) response = client.get(f'/test/{find_target}?{query_param}', headers=headers, data=data) assert response.status_code == 200 def test_get_many_data_and_create_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '''{ "insert": [ { "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00","varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }, { "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] },{ "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] } ] }''' data_dict = json.loads(data)['insert'] response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_dict): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_update_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() created_primary_key = create_response['primary_key'] update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} query_param = urlencode(update_data) response = client.put(f'/test/{created_primary_key}?{query_param}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_update_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params)+f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: assert k[i] == update_data[i] def test_patch_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) update_data = {"bool_value": False} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(params) update_data = {"char_value": "string_u "} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(params) update_data = {"date_value": "2022-07-24"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(params) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_patch_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00","varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_delete_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) response = client.delete(f'/test/{primary_key}?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_delete_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' response = client.delete(f'/test?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_post_redirect_get_data(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} bool_value_change = False char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_3', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() assert 'primary_key' in response_data for k, v in response_data.items(): if k in change: if isinstance(v, str): v = v.strip() response_ = json.dumps(v).strip() request_ = json.dumps(change[k]).strip() assert request_ == response_ return response_data def test_upsert_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 10 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k,v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 # conflict upsert_data = deepcopy(updated_data) upsert_data['on_conflict'] = {'update_columns':['numeric_value']} response = client.post('/test_2', headers=headers, data=json.dumps(dict(upsert_data, **json.loads(data)))) assert response.status_code == 201 # create response = client.post('/test_2', headers=headers, data=json.dumps(dict(updated_data, **json.loads(data)))) assert response.status_code == 409 ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/test_patch_many_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy.api_test import get_transaction_session, app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # create_one_model = api_model[CrudMethods.UPSERT_ONE].__dict__ # assert create_one_model['requestModel'] or create_one_model['responseModel'] # create_one_request_model = deepcopy(create_one_model['requestModel'].__dict__['__fields__']) # create_one_response_model = deepcopy(create_one_model['responseModel'].__dict__['__fields__']) # Request Test # assert create_one_request_model.pop('on_conflict', False) # for k, v in create_one_request_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Response Test # for k, v in create_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_one", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # create_many_model = api_model[CrudMethods.UPSERT_MANY].__dict__ # assert create_many_model['requestModel'] or create_many_model['responseModel'] # create_many_request_model = deepcopy(create_many_model['requestModel'].__dict__['__fields__']) # create_many_response_model = deepcopy(create_many_model['responseModel'].__dict__['__fields__']) # # # Request Model Test # assert create_many_request_model.pop('on_conflict', None) # insert_many_model = create_many_request_model['insert'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in insert_many_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # # # Response Model Test # for k, v in create_many_response_model.items(): # create_many_response_model_item = v.type_.__dict__['__fields__'] # for k, v in create_many_response_model_item.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", tags=["test"] ) # Response Mode Test # response_many = create_many_response_model['__root__'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in response_many.items(): # assert not v.required UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # post_redirect_get_model = api_model[CrudMethods.POST_REDIRECT_GET].__dict__ # assert post_redirect_get_model['requestModel'] or post_redirect_get_model['responseModel'] # post_redirect_get_request_model = deepcopy(post_redirect_get_model['requestModel'].__dict__['__fields__']) # post_redirect_get_response_model = deepcopy(post_redirect_get_model['responseModel'].__dict__['__fields__']) # Request Model Test # for k, v in post_redirect_get_request_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Response Model Test # for k, v in post_redirect_get_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # for k, v in post_redirect_get_response_model.items(): # assert v.required test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # # FIXME some thing may not require # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.PATCH_MANY ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # # FIXME some thing may not require # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_patch_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_patch_many", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_patch_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def test_create_many_and_patch_many(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = { "insert": [ { "bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ], "time_value": "18:18:18" , "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] } response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list":True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = { "bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "interval_value": 3600, "json_value": {'test':'hello'}, "jsonb_value": {'test':'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", "array_value": [ 1,2,3,4,5 ], "array_str__value": [ "test" ], "time_value": "18:19:18" , "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test_patch_many?{query_string}', data= json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/test_patch_one_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy.api_test import get_transaction_session, app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # create_one_model = api_model[CrudMethods.UPSERT_ONE].__dict__ # assert create_one_model['requestModel'] or create_one_model['responseModel'] # create_one_request_model = deepcopy(create_one_model['requestModel'].__dict__['__fields__']) # create_one_response_model = deepcopy(create_one_model['responseModel'].__dict__['__fields__']) # Request Test # assert create_one_request_model.pop('on_conflict', False) # for k, v in create_one_request_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Response Test # for k, v in create_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_one", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # create_many_model = api_model[CrudMethods.UPSERT_MANY].__dict__ # assert create_many_model['requestModel'] or create_many_model['responseModel'] # create_many_request_model = deepcopy(create_many_model['requestModel'].__dict__['__fields__']) # create_many_response_model = deepcopy(create_many_model['responseModel'].__dict__['__fields__']) # # # Request Model Test # assert create_many_request_model.pop('on_conflict', None) # insert_many_model = create_many_request_model['insert'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in insert_many_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # # # Response Model Test # for k, v in create_many_response_model.items(): # create_many_response_model_item = v.type_.__dict__['__fields__'] # for k, v in create_many_response_model_item.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", tags=["test"] ) # Response Mode Test # response_many = create_many_response_model['__root__'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in response_many.items(): # assert not v.required UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # post_redirect_get_model = api_model[CrudMethods.POST_REDIRECT_GET].__dict__ # assert post_redirect_get_model['requestModel'] or post_redirect_get_model['responseModel'] # post_redirect_get_request_model = deepcopy(post_redirect_get_model['requestModel'].__dict__['__fields__']) # post_redirect_get_response_model = deepcopy(post_redirect_get_model['responseModel'].__dict__['__fields__']) # Request Model Test # for k, v in post_redirect_get_request_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Response Model Test # for k, v in post_redirect_get_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # for k, v in post_redirect_get_response_model.items(): # assert v.required test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # # FIXME some thing may not require # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.PATCH_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # # FIXME some thing may not require # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_update_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_patch_one", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_update_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def test_create_one_and_patch_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key ,= [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False} response = client.patch(f'/test_patch_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(OrderedDict(**params)) update_data = { "char_value": "string_u "} response = client.patch(f'/test_patch_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(OrderedDict(**params)) update_data = {"date_value": "2022-07-24"} # update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, # "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, # "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, # "text_value": "string_update", # "timestamp_value": "2022-07-24T02:54:53.285000", # "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", # "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", # "array_value": [1, 2, 3, 4, 5], # "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test_patch_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test_patch_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] test_create_one_and_patch_one() ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/test_post_redirect_get_api.py ================================================ import json import uuid from datetime import date, timedelta, datetime, timezone from http import HTTPStatus from starlette.testclient import TestClient from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy.api_test import get_transaction_session, app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # post_redirect_get_model = api_model[CrudMethods.POST_REDIRECT_GET].__dict__ # assert post_redirect_get_model['requestModel'] or post_redirect_get_model['responseModel'] # post_redirect_get_request_model = deepcopy(post_redirect_get_model['requestModel'].__dict__['__fields__']) # post_redirect_get_response_model = deepcopy(post_redirect_get_model['responseModel'].__dict__['__fields__']) # Request Model Test # for k, v in post_redirect_get_request_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Response Model Test # for k, v in post_redirect_get_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # for k, v in post_redirect_get_response_model.items(): # assert v.required test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_post_and_redirect_get_without_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get_without_get", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_get_data, test_post_and_redirect_get_without_get]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields # Post Redirect Get API Test def test_create_one_but_no_follow_redirect(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } data = '{ "bool_value": true, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }' response = client.post('/test_post_direct_get', headers=headers, data=data, allow_redirects=False) assert response.status_code == HTTPStatus.SEE_OTHER def test_create_one_with_redirect(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} bool_value_change = False char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' uuid_value_change = str(uuid.uuid4()) varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['uuid_value'] = uuid_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_post_direct_get', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() assert primary_key_name in response_data for k, v in response_data.items(): if k in change: if isinstance(v, str): v = v.strip() response_ = json.dumps(v).strip() request_ = json.dumps(change[k]).strip() assert request_ == response_ return response_data def test_create_but_conflict(): data = test_create_one_with_redirect() headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.post('/test_post_direct_get', headers=headers, data=json.dumps(data), allow_redirects=True) assert response.status_code == HTTPStatus.CONFLICT def test_create_but_not_found_get_api(): change = {} bool_value_change = False char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' uuid_value_change = str(uuid.uuid4()) varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['uuid_value'] = uuid_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data = json.dumps(change) headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.post('/test_post_direct_get_without_get', headers=headers, data=data, allow_redirects=True) assert response.status_code == HTTPStatus.NOT_FOUND ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/test_put_many_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy.api_test import get_transaction_session, app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # create_one_model = api_model[CrudMethods.UPSERT_ONE].__dict__ # assert create_one_model['requestModel'] or create_one_model['responseModel'] # create_one_request_model = deepcopy(create_one_model['requestModel'].__dict__['__fields__']) # create_one_response_model = deepcopy(create_one_model['responseModel'].__dict__['__fields__']) # Request Test # assert create_one_request_model.pop('on_conflict', False) # for k, v in create_one_request_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Response Test # for k, v in create_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_one", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # create_many_model = api_model[CrudMethods.UPSERT_MANY].__dict__ # assert create_many_model['requestModel'] or create_many_model['responseModel'] # create_many_request_model = deepcopy(create_many_model['requestModel'].__dict__['__fields__']) # create_many_response_model = deepcopy(create_many_model['responseModel'].__dict__['__fields__']) # # # Request Model Test # assert create_many_request_model.pop('on_conflict', None) # insert_many_model = create_many_request_model['insert'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in insert_many_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # # # Response Model Test # for k, v in create_many_response_model.items(): # create_many_response_model_item = v.type_.__dict__['__fields__'] # for k, v in create_many_response_model_item.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", tags=["test"] ) # Response Mode Test # response_many = create_many_response_model['__root__'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in response_many.items(): # assert not v.required UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # post_redirect_get_model = api_model[CrudMethods.POST_REDIRECT_GET].__dict__ # assert post_redirect_get_model['requestModel'] or post_redirect_get_model['responseModel'] # post_redirect_get_request_model = deepcopy(post_redirect_get_model['requestModel'].__dict__['__fields__']) # post_redirect_get_response_model = deepcopy(post_redirect_get_model['responseModel'].__dict__['__fields__']) # Request Model Test # for k, v in post_redirect_get_request_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Response Model Test # for k, v in post_redirect_get_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # for k, v in post_redirect_get_response_model.items(): # assert v.required test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # # FIXME some thing may not require # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPDATE_MANY ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # # FIXME some thing may not require # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_update_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_update_many", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_update_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def test_create_many_and_update_many(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = { "insert": [ { "bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ], "time_value": "18:18:18" , "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] } response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list":True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = { "bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test':'hello'}, "jsonb_value": {'test':'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", "array_value": [ 1,2,3,4,5 ], "array_str__value": [ "test" ], "time_value": "18:19:18" , "timetz_value": "18:19:18+00:00"} response = client.put(f'/test_update_many?{query_string}', data= json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_create_many_and_update_many_but_not_found(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = { "insert": [ { "bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ], "time_value": "18:18:18" , "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] } response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list":True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '10:18:18', "time_value____to": '12:18:18', "time_value____list": '10:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "timez_value____from": '18:18:18+00:00', "timez_value____to": '18:18:18+00:00', "timez_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = { "bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test':'hello'}, "jsonb_value": {'test':'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", "array_value": [ 1,2,3,4,5 ], "array_str__value": [ "test" ], "time_value": "18:19:18" , "timetz_value": "18:19:18+00:00"} response = client.put(f'/test_update_many?{query_string}', data= json.dumps(update_data)) # response_data = response.json() # assert len(response_data) == 3 # for k in response_data: # for i in update_data: # print(i) # print(k[i]) # assert k[i] == update_data[i] assert response.status_code == 204 ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test/test_put_one_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy.api_test import get_transaction_session, app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # create_one_model = api_model[CrudMethods.UPSERT_ONE].__dict__ # assert create_one_model['requestModel'] or create_one_model['responseModel'] # create_one_request_model = deepcopy(create_one_model['requestModel'].__dict__['__fields__']) # create_one_response_model = deepcopy(create_one_model['responseModel'].__dict__['__fields__']) # Request Test # assert create_one_request_model.pop('on_conflict', False) # for k, v in create_one_request_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Response Test # for k, v in create_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_one", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPDATE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_update_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_update_one", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_update_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def test_create_one_and_update_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key ,= [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test_update_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_create_one_and_update_one_but_not_found(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key ,= [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '10:18:18', "time_value____to": '12:18:18', "time_value____list": '10:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_valuez____from": '18:18:18+00:00', "time_valuez____to": '18:18:18+00:00', "time_valuez____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test_update_one/{primary_key}?{query_string}', data=json.dumps(update_data)) # response_data = response.json() response.status_code = 404 # assert response_data # for i in update_data: # assert response_data[i] == update_data[i] ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test_async/__init__.py ================================================ import asyncio import os from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_ASYNC_URL', 'postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_ASYNC_URL', 'postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres') # client = AsyncIOMotorClient()?? # client.get_io_loop = asyncio.get_event_loop # engine = AIOEngine(motor_client=client) engine = create_async_engine(TEST_DATABASE_URL, echo=True, future=True) async_session = sessionmaker( engine, class_=AsyncSession, expire_on_commit=False ) async def get_transaction_session() -> AsyncSession: async with async_session() as session: yield session class UntitledTable256(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_build_myself_async' __table_args__ = ( UniqueConstraint('primary_key', 'int4_value', 'float4_value'), ) primary_key = Column(Integer, primary_key=True, info={'alias_name': 'primary_key'},autoincrement=True,server_default="nextval('test_build_myself_id_seq'::regclass)") bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) # xml_value = Column(NullType) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) # box_valaue = Column(NullType) async def create_table(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) loop = asyncio.get_event_loop() loop.run_until_complete(create_table()) # loop.close() ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test_async/test_create_many_api.py ================================================ import json import uuid from datetime import date, timedelta, datetime, timezone from starlette.testclient import TestClient from src.fastapi_quickcrud.misc.exceptions import ConflictColumnsCannotHit from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy.api_test_async import get_transaction_session, app, UntitledTable256 # Create Many API Test test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_creation_many", async_mode=True, tags=["test"] ) [app.include_router(i) for i in [test_create_many]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def create_example_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{ "insert": [ { "bool_value": true, "char_value": "string", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963", "timestamptz_value": "2021-07-23T02:38:24.963Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }, { "bool_value": true, "char_value": "string", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963", "timestamptz_value": "2021-07-23T02:38:24.963Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }, { "bool_value": true, "char_value": "string", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963", "timestamptz_value": "2021-07-23T02:38:24.963Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] } ] }' response = client.post('/test_creation_many', headers=headers, data=data) assert response.status_code == 201 return response.json() def test_try_only_input_required_fields(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{ "insert": [ { "float4_value": 1, "int2_value": 1, "int4_value": 1 },{ "float4_value": 2, "int2_value": 2, "int4_value": 2 },{ "float4_value": 3, "int2_value": 3, "int4_value": 3 } ] }' data_ = json.loads(data)['insert'] response = client.post('/test_creation_many', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_try_input_with_conflict_but_conflict_columns_not_hit(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"on_conflict": {"update_columns": ["bool_value", "float8_value", "varchar_value", "interval_value", "time_value", "int8_value", "jsonb_value", "timetz_value", "array_str__value", "text_value", "char_value", "uuid_value", "array_value", "numeric_value", "timestamp_value", "int2_value", "date_value", "json_value", "timestamptz_value"]}} insert_data = [] for i in sample_data: _ = {} for k, v in i.items(): _[k] = v for k, v in {"float4_value": 99, "int2_value": 99, "int4_value": 99}.items(): _[k] = v insert_data.append(_) data['insert'] = insert_data try: _ = json.dumps(data) response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) except ConflictColumnsCannotHit as e: pass assert response.status_code == 409 def test_try_input_with_conflict(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"on_conflict": {"update_columns": ["bool_value", "float8_value", "varchar_value", "interval_value", "time_value", "int8_value", "jsonb_value", "timetz_value", "array_str__value", "text_value", "char_value", "uuid_value", "array_value", "numeric_value", "timestamp_value", "int2_value", "date_value", "json_value", "timestamptz_value"]}} insert_data = [] for i in sample_data: _ = {} for k, v in i.items(): _[k] = v for k, v in {"float8_value": 0.7}.items(): _[k] = v insert_data.append(_) data['insert'] = insert_data response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data['insert']): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == value[k] def test_try_input_without_conflict(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {} insert_data = [] for i in sample_data: _ = {} for k, v in i.items(): _[k] = v for k, v in {"float4_value": 99, "int2_value": 99, "int4_value": 99}.items(): _[k] = v insert_data.append(_) data['insert'] = insert_data response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 409 def test_update_specific_columns_when_conflict(): def update_all_fields(): headers = { 'accept': 'application/json', } response_data = create_example_data() # create the data update_column_on_conflict = { "update_columns": [ "int8_value", "numeric_value", "varchar_value", "json_value", "float8_value", "time_value", "timestamp_value", "timestamptz_value", "array_value", "bool_value", "array_str__value", "int2_value", "text_value", "uuid_value", "char_value", "jsonb_value", "interval_value", "date_value", "timetz_value" ] } tmp = {} tmp['on_conflict'] = update_column_on_conflict bool_value_change = not response_data[0]['bool_value'] char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' uuid_value_change = str(uuid.uuid4()) varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change = {} change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['uuid_value'] = uuid_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change for i in response_data: for k, v in change.items(): i[k] = v tmp['insert'] = response_data response = client.post('/test_creation_many', headers=headers, data=json.dumps(tmp)) assert response.status_code == 201 response_result = response.json() for i in response_result: for k, v in i.items(): if k in change: if isinstance(v, str): v = v.strip() assert json.dumps(change[k]).strip() == json.dumps(v).strip() def update_partial_fields_1(): headers = { 'accept': 'application/json', } response_data = create_example_data() # create the data update_column_on_conflict = { "update_columns": [ "int8_value", "numeric_value", "varchar_value", "json_value", "float8_value", "time_value", "timestamp_value", "timestamptz_value", "array_value", "bool_value", "array_str__value", ] } tmp = {} tmp['on_conflict'] = update_column_on_conflict bool_value_change = not response_data[0]['bool_value'] float8_value_change = 0.1 int8_value_change = 100 json_value_change = {"hello": "world"} numeric_value_change = 19 time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) uuid_value_change = str(uuid.uuid4()) varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change = {} change['int8_value'] = int8_value_change change['numeric_value'] = numeric_value_change change['varchar_value'] = varchar_value_change change['json_value'] = json_value_change change['float8_value'] = float8_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['array_value'] = array_value_change change['bool_value'] = bool_value_change change['array_str__value'] = array_str__value_change for i in response_data: for k, v in change.items(): i[k] = v tmp['insert'] = response_data response = client.post('/test_creation_many', headers=headers, data=json.dumps(tmp)) assert response.status_code == 201 response_result = response.json() for i in response_result: for k, v in i.items(): if k in change: if isinstance(v, str): v = v.strip() assert json.dumps(change[k]).strip() == json.dumps(v).strip() def update_partial_fields_2(): headers = { 'accept': 'application/json', } response_data = create_example_data() # create the data update_column_on_conflict = { "update_columns": [ "int2_value", "text_value", "uuid_value", "char_value", "jsonb_value", "interval_value", "date_value", "timetz_value" ] } tmp = {} tmp['on_conflict'] = update_column_on_conflict char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) int2_value_change = 100 interval_value_change = float(5400) jsonb_value_change = {"hello": "world"} text_value_change = 'hello world' timetz_value_change = '18:18:18+00:00' uuid_value_change = str(uuid.uuid4()) change = {} change['int2_value'] = int2_value_change change['text_value'] = text_value_change change['uuid_value'] = uuid_value_change change['char_value'] = char_value_change change['jsonb_value'] = jsonb_value_change change['interval_value'] = interval_value_change change['date_value'] = date_value_change change['timetz_value'] = timetz_value_change for i in response_data: for k, v in change.items(): i[k] = v tmp['insert'] = response_data response = client.post('/test_creation_many', headers=headers, data=json.dumps(tmp)) assert response.status_code == 201 response_result = response.json() for i in response_result: for k, v in i.items(): if k in change: if isinstance(v, str): v = v.strip() assert json.dumps(change[k]).strip() == json.dumps(v).strip() update_all_fields() update_partial_fields_1() update_partial_fields_2() ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test_async/test_create_one_api.py ================================================ import json import random import uuid from datetime import date, timedelta, datetime, timezone from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.exceptions import ConflictColumnsCannotHit, UpdateColumnEmptyException, UnknownColumn from src.fastapi_quickcrud.misc.type import CrudMethods from tests.test_implementations.test_sqlalchemy.api_test_async import get_transaction_session, app, UntitledTable256 test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_creation_one", async_mode=True, tags=["test"] ) test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_creation_many", async_mode=True, tags=["test"] ) # Response Mode Test # response_many = create_many_response_model['__root__'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in response_many.items(): # assert not v.required # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # post_redirect_get_model = api_model[CrudMethods.POST_REDIRECT_GET].__dict__ # assert post_redirect_get_model['requestModel'] or post_redirect_get_model['responseModel'] # post_redirect_get_request_model = deepcopy(post_redirect_get_model['requestModel'].__dict__['__fields__']) # post_redirect_get_response_model = deepcopy(post_redirect_get_model['responseModel'].__dict__['__fields__']) # Request Model Test # for k, v in post_redirect_get_request_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Response Model Test # for k, v in post_redirect_get_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # for k, v in post_redirect_get_response_model.items(): # assert v.required test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_post_direct_get", async_mode=True, tags=["test"] ) test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", async_mode=True, tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields # Create One API Test def create_example_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_creation_one', headers=headers, data=data) assert response.status_code == 201 return response.json() def test_try_only_input_required_fields(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"float4_value": 0.0, "int2_value": 0, "int4_value": 0, 'uuid_value': '3fa85f64-5717-4562-b3fc-2c963f66afa6'} response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) assert response.status_code == 201 response_result = response.json() for k, v in data.items(): assert response_result[k] == v def test_try_input_with_conflict_but_conflict_columns_not_hit(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"on_conflict": {"update_columns": ["bool_value", "float8_value", "varchar_value", "interval_value", "time_value", "int8_value", "jsonb_value", "timetz_value", "array_str__value", "text_value", "char_value", "uuid_value", "array_value", "numeric_value", "timestamp_value", "int2_value", "date_value", "json_value", "timestamptz_value"]}} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 99, "int2_value": 99, "int4_value": 99}.items(): data[k] = v # for k, v in {"float4_value": 99.9, "int2_value": 99, "int4_value": 99}.items(): # data[k] = v try: _ = json.dumps(data) response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) except ConflictColumnsCannotHit as e: pass assert response.status_code == 409 def test_try_input_with_conflict(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"on_conflict": {"update_columns": ["bool_value", "float8_value", "varchar_value", "interval_value", "time_value", "int8_value", "jsonb_value", "timetz_value", "array_str__value", "text_value", "char_value", "uuid_value", "array_value", "numeric_value", "timestamp_value", "int2_value", "date_value", "json_value", "timestamptz_value"]}} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 0.0, "int2_value": 99, "int4_value": 0}.items(): data[k] = v response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) assert response.status_code == 201 response_result = response.json() for k, v in response_result.items(): if k in data: if isinstance(v, str): v = v.strip() assert json.dumps(data[k]).strip() == json.dumps(v).strip() def test_try_input_without_conflict(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 0.0, "int2_value": 99, "int4_value": 0}.items(): data[k] = v # data['on_conflict'] = {'update_columns': []} response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) assert response.status_code == 409 def test_update_specific_columns_when_conflict(): def update_all_fields(): headers = { 'accept': 'application/json', } sample_data = create_example_data() response = client.get(f'/test/{sample_data[primary_key_name]}', headers=headers) assert response.status_code == 200 response_data = response.json() # create the data update_column_on_conflict = { "update_columns": [ "int8_value", "numeric_value", "varchar_value", "json_value", "float8_value", "time_value", "timestamp_value", "timestamptz_value", "array_value", "bool_value", "array_str__value", "int2_value", "text_value", "uuid_value", "char_value", "jsonb_value", "interval_value", "date_value", "timetz_value" ] } response_data['on_conflict'] = update_column_on_conflict ran_num = random.randint(5, 100) bool_value_change = not response_data['bool_value'] char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' uuid_value_change = str(uuid.uuid4()) varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change = {} change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['uuid_value'] = uuid_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change for k, v in change.items(): response_data[k] = v response = client.post('/test_creation_one', headers=headers, data=json.dumps(response_data)) assert response.status_code == 201 response_result = response.json() for k, v in response_result.items(): if k in change: if isinstance(v, str): v = v.strip() assert json.dumps(change[k]).strip() == json.dumps(v).strip() def update_partial_fields(): headers = { 'accept': 'application/json', } sample_data = create_example_data() response = client.get(f'/test/{sample_data[primary_key_name]}', headers=headers) assert response.status_code == 200 response_data = response.json() # create the data update_column_on_conflict = { "update_columns": [ "varchar_value", "json_value", "float8_value", "time_value", "timestamp_value", "timestamptz_value", "array_value", "bool_value", "array_str__value", "char_value", "jsonb_value", "interval_value", "date_value", "timetz_value" ] } response_data['on_conflict'] = update_column_on_conflict ran_num = random.randint(5, 100) bool_value_change = not response_data['bool_value'] char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change = {} change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change for k, v in change.items(): response_data[k] = v response = client.post('/test_creation_one', headers=headers, data=json.dumps(response_data)) assert response.status_code == 201 response_result = response.json() for k, v in response_result.items(): if k in change: if isinstance(v, str): v = v.strip() assert json.dumps(change[k]).strip() == json.dumps(v).strip() update_all_fields() update_partial_fields() def test_try_input_with_conflict_but_missing_update_columns(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 0.0, "int2_value": 99, "int4_value": 0}.items(): data[k] = v data['on_conflict'] = {'update_columns': []} try: response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) except UpdateColumnEmptyException as e: assert True return assert False def test_try_input_with_conflict_but_unknown_update_columns(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 0.0, "int2_value": 99, "int4_value": 0}.items(): data[k] = v data['on_conflict'] = {'update_columns': ['testsetsetset']} try: response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) except UnknownColumn as e: assert True return assert False ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test_async/test_delete_many_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods from tests.test_implementations.test_sqlalchemy.api_test_async import get_transaction_session, app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_one", async_mode=True, tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", async_mode=True, tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", async_mode=True, tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", async_mode=True, tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.DELETE_MANY ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_delete_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_delete_many", async_mode=True, tags=["test"] ) for i in [test_post_and_redirect_get, test_delete_data, test_create_one, test_create_many, test_get_data]: app.include_router(i) client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def test_create_many_and_delete_many(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) response = client.delete(f'/test_delete_many?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_create_many_and_delete_many_but_not_found(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = { "insert": [ { "bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ], "time_value": "18:18:18" , "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] } response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list":True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '10:18:18', "time_value____to": '12:18:18', "time_value____list": '12:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "timez_value____from": '18:18:18+00:00', "timez_value____to": '18:18:18+00:00', "timez_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) response = client.delete(f'/test_delete_many?{query_string}') assert response.status_code == 204 ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test_async/test_delete_one_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods from tests.test_implementations.test_sqlalchemy.api_test_async import get_transaction_session, app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # create_one_model = api_model[CrudMethods.UPSERT_ONE].__dict__ # assert create_one_model['requestModel'] or create_one_model['responseModel'] # create_one_request_model = deepcopy(create_one_model['requestModel'].__dict__['__fields__']) # create_one_response_model = deepcopy(create_one_model['responseModel'].__dict__['__fields__']) # Request Test # assert create_one_request_model.pop('on_conflict', False) # for k, v in create_one_request_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Response Test # for k, v in create_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_one", async_mode=True, tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # create_many_model = api_model[CrudMethods.UPSERT_MANY].__dict__ # assert create_many_model['requestModel'] or create_many_model['responseModel'] # create_many_request_model = deepcopy(create_many_model['requestModel'].__dict__['__fields__']) # create_many_response_model = deepcopy(create_many_model['responseModel'].__dict__['__fields__']) # # # Request Model Test # assert create_many_request_model.pop('on_conflict', None) # insert_many_model = create_many_request_model['insert'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in insert_many_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # # # Response Model Test # for k, v in create_many_response_model.items(): # create_many_response_model_item = v.type_.__dict__['__fields__'] # for k, v in create_many_response_model_item.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", async_mode=True, tags=["test"] ) # Response Mode Test # response_many = create_many_response_model['__root__'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in response_many.items(): # assert not v.required UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # post_redirect_get_model = api_model[CrudMethods.POST_REDIRECT_GET].__dict__ # assert post_redirect_get_model['requestModel'] or post_redirect_get_model['responseModel'] # post_redirect_get_request_model = deepcopy(post_redirect_get_model['requestModel'].__dict__['__fields__']) # post_redirect_get_response_model = deepcopy(post_redirect_get_model['responseModel'].__dict__['__fields__']) # Request Model Test # for k, v in post_redirect_get_request_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Response Model Test # for k, v in post_redirect_get_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # for k, v in post_redirect_get_response_model.items(): # assert v.required test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", async_mode=True, tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # # FIXME some thing may not require # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", async_mode=True, tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.DELETE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # # FIXME some thing may not require # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_delete_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_delete_one", async_mode=True, tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_delete_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def test_create_one_and_delete_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) response = client.delete(f'/test_delete_one/{primary_key}?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_create_one_and_delete_one_but_not_found(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key ,= [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '10:18:18', "time_value____to": '12:18:18', "time_value____list": '10:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "timez_value____from": '18:18:18+00:00', "timez_value____to": '18:18:18+00:00', "timez_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False} response = client.delete(f'/test_delete_one/{primary_key}?{query_string}') assert response.status_code == 404 ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test_async/test_get_many_api.py ================================================ import json from collections import OrderedDict from urllib.parse import urlencode from starlette.testclient import TestClient from src.fastapi_quickcrud.misc.exceptions import UnknownOrderType, UnknownColumn from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods from src.fastapi_quickcrud.misc.utils import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy.api_test_async import get_transaction_session, app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # create_many_model = api_model[CrudMethods.UPSERT_MANY].__dict__ # assert create_many_model['requestModel'] or create_many_model['responseModel'] # create_many_request_model = deepcopy(create_many_model['requestModel'].__dict__['__fields__']) # create_many_response_model = deepcopy(create_many_model['responseModel'].__dict__['__fields__']) # # # Request Model Test # assert create_many_request_model.pop('on_conflict', None) # insert_many_model = create_many_request_model['insert'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in insert_many_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # # # Response Model Test # for k, v in create_many_response_model.items(): # create_many_response_model_item = v.type_.__dict__['__fields__'] # for k, v in create_many_response_model_item.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Create Many API Test test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", async_mode=True, tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_find_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_get_many", async_mode=True, tags=["test"] ) [app.include_router(i) for i in [test_create_many, test_find_many]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields # test create many def create_example_data(num=1, **kwargs): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } insert_sample_item = {"bool_value": kwargs.get('bool_value', True), "char_value": kwargs.get('char_value', 'string'), "date_value": kwargs.get('date_value', "2021-07-23"), "float4_value": kwargs.get('float4_value', 0.6), "float8_value": kwargs.get('float8_value', 0.8), "int2_value": kwargs.get('int2_value', 11), "int4_value": kwargs.get('int4_value', 1), "int8_value": kwargs.get('int8_value', 3), "interval_value": kwargs.get('interval_value', 5), "json_value": kwargs.get('json_value', {}), "jsonb_value": kwargs.get('jsonb_value', {}), "numeric_value": kwargs.get('numeric_value', 110), "text_value": kwargs.get('text_value', 'string'), "timestamp_value": kwargs.get('timestamp_value', "2021-07-23T02:38:24.963"), "timestamptz_value": kwargs.get('timestamptz_value', "2021-07-23T02:38:24.963Z"), "uuid_value": kwargs.get('uuid_value', "3fa85f64-5717-4562-b3fc-2c963f66afa6"), "varchar_value": kwargs.get('varchar_value', 'string'), "array_value": kwargs.get('array_value', [1, 2, 3, 4]), "array_str__value": kwargs.get('array_str__value', ["string", "string1"])} data = {'insert': [insert_sample_item for i in range(num)]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 response_result = response.json() for i in response_result: assert primary_key_name in i assert i[primary_key_name] return response_result # test pagination by offset and limit and ordering def test_pagination_and_ording(): sample_data = create_example_data(5 * 10) assert len(sample_data) == 5 * 10 limit = 5 seem = [] for num in range(0, 5 * 10, 5): response = client.get( f'/test_get_many?limit={limit}&offset={num}&order_by_columns=primary_key%20%3A%20DESC%20') response.headers['x-total-count'] == limit assert response.status_code == 200 _ = response.json() for i in _: assert i not in seem seem.append(i) assert i in sample_data # test create a new data and get by primary key def test_create_new_data_and_get_by_primary_key(): sample_data = create_example_data(10) primary_key_list = [i[primary_key_name] for i in sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key} from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in response_data: assert i['primary_key'] in primary_key_list params = {"primary_key____from": min_key, "primary_key____to": max_key, "primary_key____from_____comparison_operator": 'Greater_than', "primary_key____to_____comparison_operator": 'Less_than'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 8 for i in response_data: assert i['primary_key'] in primary_key_list # test create a more than one data which value is TRUE of boolean type, and get many def test_create_a_more_than_one_data_which_value_is_TRUE_of_boolean_type_and_get_many(): bool_false_sample_data = create_example_data(5, bool_value=False) bool_true_sample_data = create_example_data(5, bool_value=True) primary_key_list = [i[primary_key_name] for i in bool_false_sample_data] + \ [i[primary_key_name] for i in bool_true_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "In", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) + f"&bool_value____list=False" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "In", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i not in response.json() for i in bool_true_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "In", "bool_value____list": False} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Equal", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) + f"&bool_value____list=False" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Equal", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i not in response.json() for i in bool_true_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Equal", "bool_value____list": False} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i not in response.json() # params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_in", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) + f"&bool_value____list=False" response = client.get(f'/test_get_many?{query_string}') response.status_code = 204 params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_in", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_in", "bool_value____list": False} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i not in response.json() for i in bool_true_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_equal", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) + f"&bool_value____list=False" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_equal", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_equal", "bool_value____list": False} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i not in response.json() for i in bool_true_sample_data: assert i in response.json() # test create a more than one data of char/text/varchar type, and get many def test_create_a_more_than_one_data_and_get_many_1(): char_str_sample_data = create_example_data(5, char_value='string') char_test_sample_data = create_example_data(5, char_value='test') primary_key_list = [i[primary_key_name] for i in char_str_sample_data] + \ [i[primary_key_name] for i in char_test_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) # match_regex_with_case_sensitive/ dose not match_regex_with_case_sensitive def match_regex_with_case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "char_value____str": 'str.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "char_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_match_regex_with_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "char_value____str": 'str.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "char_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "char_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "char_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "char_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "char_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def match_regex_with_case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "char_value____str": 'STR.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "char_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # does_not_match_regex_with_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "char_value____str": 'STR.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "char_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "char_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=STR.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "char_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=STR.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'case_sensitive', "char_value____str": 'string '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'case_sensitive', "char_value____str": 'test '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_sensitive', "char_value____str": 'string '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_sensitive', "char_value____str": 'test '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_sensitive', "char_value____str": 'test '} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=string " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_insensitive', "char_value____str": 'test '} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=string " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'case_insensitive', "char_value____str": 'STRING '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'case_insensitive', "char_value____str": 'TEST '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_insensitive', "char_value____str": 'STRING '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_insensitive', "char_value____str": 'TEST '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_insensitive', "char_value____str": 'TEST '} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=STRING " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_sensitive', "char_value____str": 'TEST '} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=STRING " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def similar_to(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'similar_to', "char_value____str": 'string%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'similar_to', "char_value____str": 'test%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_similar_to', "char_value____str": 'string%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_similar_to', "char_value____str": 'test%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'similar_to'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str%&char_value____str=_es%" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'similar_to'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str%&char_value____str=_es%" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() match_regex_with_case_sensitive() match_regex_with_case_insensitive() case_sensitive() case_insensitive() similar_to() # Varchar char_str_sample_data = create_example_data(5, varchar_value='string') char_test_sample_data = create_example_data(5, varchar_value='test') primary_key_list = [i[primary_key_name] for i in char_str_sample_data] + \ [i[primary_key_name] for i in char_test_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) # match_regex_with_case_sensitive/ dose not match_regex_with_case_sensitive def match_regex_with_case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "varchar_value____str": 'str.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "varchar_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_match_regex_with_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "varchar_value____str": 'str.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "varchar_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "varchar_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "varchar_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "varchar_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "varchar_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def match_regex_with_case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "varchar_value____str": 'STR.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "varchar_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # does_not_match_regex_with_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "varchar_value____str": 'STR.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "varchar_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "varchar_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=STR.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "varchar_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=STR.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_sensitive', "varchar_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_sensitive', "varchar_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_sensitive', "varchar_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=string " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_insensitive', "varchar_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=string " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'case_insensitive', "varchar_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'case_insensitive', "varchar_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_insensitive', "varchar_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_insensitive', "varchar_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_insensitive', "varchar_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_sensitive', "varchar_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def similar_to(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'similar_to', "varchar_value____str": 'string%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'similar_to', "varchar_value____str": 'test%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_similar_to', "varchar_value____str": 'string%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_similar_to', "varchar_value____str": 'test%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'similar_to'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str%&varchar_value____str=_es%" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'similar_to'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str%&varchar_value____str=_es%" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() match_regex_with_case_sensitive() match_regex_with_case_insensitive() case_sensitive() case_insensitive() similar_to() # Text char_str_sample_data = create_example_data(5, text_value='string') char_test_sample_data = create_example_data(5, text_value='test') primary_key_list = [i[primary_key_name] for i in char_str_sample_data] + \ [i[primary_key_name] for i in char_test_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) # match_regex_with_case_sensitive/ dose not match_regex_with_case_sensitive def match_regex_with_case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "text_value____str": 'str.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "text_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_match_regex_with_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "text_value____str": 'str.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "text_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "text_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "text_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "text_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "text_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def match_regex_with_case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "text_value____str": 'STR.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "text_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # does_not_match_regex_with_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "text_value____str": 'STR.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "text_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "text_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=STR.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "text_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=STR.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'case_sensitive', "text_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'case_sensitive', "text_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_sensitive', "text_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_sensitive', "text_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_sensitive', "text_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=string " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_insensitive', "text_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=string " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'case_insensitive', "text_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'case_insensitive', "text_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_insensitive', "text_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_insensitive', "text_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_insensitive', "text_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_sensitive', "text_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def similar_to(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'similar_to', "text_value____str": 'string%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'similar_to', "text_value____str": 'test%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_similar_to', "text_value____str": 'string%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_similar_to', "text_value____str": 'test%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'similar_to'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str%&text_value____str=_es%" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'similar_to'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str%&text_value____str=_es%" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() match_regex_with_case_sensitive() match_regex_with_case_insensitive() case_sensitive() case_insensitive() similar_to() # test create a more than one data of float4/text/varchar type, and get many def test_create_a_more_than_one_data_and_get_many_2(): float_one = 5.5 float_two = 10.7 # float 4 <= will round down to the odd floating even # data = 0.4 # <= 0.4 # result = [] # data = 0.4 # <= 0.5 # result = [0.4] num_one_sample_data = create_example_data(5, float4_value=float_one) num_two_sample_data = create_example_data(5, float4_value=float_two) primary_key_list = [i[primary_key_name] for i in num_one_sample_data] + \ [i[primary_key_name] for i in num_two_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) def greater_than_or_equal_to_Less_than_or_equal_to(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "float4_value____from_____comparison_operator": 'Greater_than_or_equal_to', "float4_value____to_____comparison_operator": 'Less_than_or_equal_to', "float4_value____from": float_one, "float4_value____to": float_two} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in num_one_sample_data: assert i in response.json() for i in num_two_sample_data: assert i in response.json() # data = 10.7 # < 10.7 # still got 10.7 but if data is 10.6 def less_than_or_equal_to_less_than(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "float4_value____from_____comparison_operator": 'Greater_than', "float4_value____to_____comparison_operator": 'Less_than', "float4_value____from": float_one, "float4_value____to": float_two + 0.1} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in num_one_sample_data: assert i not in response.json() for i in num_two_sample_data: assert i in response.json() greater_than_or_equal_to_Less_than_or_equal_to() less_than_or_equal_to_less_than() # float 4 < will round down to the odd floating odd # data = 0.3 # <= 0.4 # result = [] # data = 0.4 # <= 0.5 # result = [0.4] float_one = 5.5 float_two = 10.6 num_one_sample_data = create_example_data(5, float8_value=float_one) num_two_sample_data = create_example_data(5, float8_value=float_two) primary_key_list = [i[primary_key_name] for i in num_one_sample_data] + \ [i[primary_key_name] for i in num_two_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) def greater_than_or_equal_to_Less_than_or_equal_to(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "float8_value____from_____comparison_operator": 'Greater_than_or_equal_to', "float8_value____to_____comparison_operator": 'Less_than_or_equal_to', "float8_value____from": float_one, "float8_value____to": float_two} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in num_one_sample_data: assert i in response.json() for i in num_two_sample_data: assert i in response.json() def less_than_or_equal_to_less_than(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "float8_value____from_____comparison_operator": 'Greater_than', "float8_value____to_____comparison_operator": 'Less_than', "float8_value____from": float_one, "float8_value____to": float_two + 0.1} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in num_one_sample_data: assert i not in response.json() for i in num_two_sample_data: assert i in response.json() greater_than_or_equal_to_Less_than_or_equal_to() less_than_or_equal_to_less_than() # test order_by_columns regex validation def test_get_many_with_ordering_unknown_column(): try: response = client.get(f'/test_get_many?order_by_columns=testestset') except UnknownColumn as e: assert str(e) == "column testestset is not exited" return assert False def test_get_many_with_ordering_with_default_order(): response = client.get(f'/test_get_many?order_by_columns=primary_key&limit=10&offset=0') a = response.json() init = 0 for i in a: assert i['primary_key'] >= init init = i['primary_key'] def test_get_many_with_ordering_with_ASC(): response = client.get(f'/test_get_many?order_by_columns=primary_key:ASC&limit=10&offset=0') a = response.json() init = 0 for i in a: assert i['primary_key'] >= init init = i['primary_key'] def test_get_many_with_ordering_with_DESC(): response = client.get(f'/test_get_many?order_by_columns=primary_key:DESC&limit=10&offset=10') a = response.json() init = a[0]['primary_key'] for i in a: assert i['primary_key'] == init init -= 1 def test_get_many_with_unknown_order_tyoe(): try: response = client.get(f'/test_get_many?order_by_columns=primary_key:DESCSS&limit=10&offset=0') except UnknownOrderType as e: assert str(e) == 'Unknown order type DESCSS, only accept DESC or ASC' return assert False def test_get_many_with_ordering_with_empty_input_list(): try: response = client.get(f'/test_get_many?order_by_columns=') except Exception as e: assert False assert True ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test_async/test_get_one_api.py ================================================ import json import os from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession from sqlalchemy.orm import sessionmaker from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods from tests.test_implementations.test_sqlalchemy.api_test_async import app, UntitledTable256 TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_ASYNC_URL', 'postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres') engine = create_async_engine(TEST_DATABASE_URL, echo=True, future=True) async_session = sessionmaker( engine, class_=AsyncSession, expire_on_commit=False ) async def get_transaction_session() -> AsyncSession: async with async_session() as session: yield session UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", async_mode=True, tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", async_mode=True, tags=["test"] ) [app.include_router(i) for i in [test_get_data, test_create_one]] client = TestClient(app) # create a sample data headers = { 'accept': '*/*', 'Content-Type': 'application/json', } data = '{ "bool_value": true, "char_value": "string", "date_value": "2021-07-26", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-26T02:17:46.846", "timestamptz_value": "2021-07-26T02:17:46.846Z", "timetz_value": "18:18:18+00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }' response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_data = response.json() dict_data = json.loads(data) sample_primary_key = response_data['primary_key'] ''' { "primary_key": 1013, "interval_value": 0, <- querying not supported "json_value": {},<- querying not supported "jsonb_value": {},<- querying not supported "array_value": [ 0 ], "array_str__value": [ "string" ] } ''' # try find the data by primary key def test_get_by_primary_key_without_any_query_param(): response = client.get(f'/test/{sample_primary_key}', headers=headers) assert response.status_code == 200 assert response.json()['primary_key'] == sample_primary_key # "bool_value": true # try find the data by primary key but false by bool def test_get_by_primary_key_with_false_bool_query_param(): response = client.get(f'/test/{sample_primary_key}?bool_value____list=false', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?bool_value____list=true', headers=headers) assert response.status_code == 200 # "char_value": "string ", # try find the data by primary key but false by char def test_get_by_primary_key_with_false_char_query_param(): response = client.get(f'/test/{sample_primary_key}?char_value____list=string1&char_value____list=string2', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?char_value____list=string&char_value____list=string1&', headers=headers) assert response.status_code == 200 # Like operator response = client.get( f'/test/{sample_primary_key}?char_value____str=string1&char_value____str=%tri%&char_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=string1&char_value____str=%tsri%&char_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 404 # Ilike operator response = client.get( f'/test/{sample_primary_key}?char_value____str=string1&char_value____str=%tRi%&char_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=string1&char_value____str=%tsri%&char_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 404 # not like operator response = client.get( f'/test/{sample_primary_key}?char_value____str=string2&char_value____str=%strg%&char_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=string%&char_value____str=%strin%&char_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 404 # not ilike operator response = client.get( f'/test/{sample_primary_key}?char_value____str=String2&char_value____str=%Strg%&char_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=STRING%&char_value____str=%TRI%&char_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 404 # match regex with case sensitive operator response = client.get( f'/test/{sample_primary_key}?char_value____str=stri.*&varchar_value____stg=str&char_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=stg.*&char_value____str=stg&char_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) assert response.status_code == 404 # match regex with case insensitive operator response = client.get( f'/test/{sample_primary_key}?char_value____str=strI.*&char_value____str=STG&char_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=stG.*&char_value____str=STG&char_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) assert response.status_code == 404 # does_not_match_regex_with_case_insensitive response = client.get( f'/test/{sample_primary_key}?char_value____str=strI.*&char_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?char_value____str=stG.*&char_value____str=STG&char_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) assert response.status_code == 200 # dose not match regex with case sensitive operator response = client.get( f'/test/{sample_primary_key}?char_value____str=stri.*&varchar_value____stg=str&char_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?char_value____str=stg.*&char_value____str=stg&char_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) assert response.status_code == 200 # similar_to response = client.get( f'/test/{sample_primary_key}?char_value____str=string&char_value____str=%(r|z)%&char_value____str_____matching_pattern=similar_to', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=str&char_value____str=(r|z)%&char_value____str_____matching_pattern=similar_to', headers=headers) assert response.status_code == 404 # not_similar_to response = client.get( f'/test/{sample_primary_key}?char_value____str=string%&char_value____str=%(r|z)%&char_value____str_____matching_pattern=not_similar_to', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?char_value____str=str&char_value____str=(r|z)%&char_value____str_____matching_pattern=not_similar_to', headers=headers) assert response.status_code == 200 # "float4_value": 0, # try find the data by primary key but false by float4 def test_get_by_primary_key_with_false_float4_query_param(): # from response = client.get(f'/test/{sample_primary_key}?float4_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?float4_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??float4_value____from=-2&float4_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?float4_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?float4_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?float4_value____from=0&float4_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?float4_value____from=0&float4_value____to=0&float4_value____from_____comparison_operator=Greater_than_or_equal_to&float4_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?float4_value____from=-1&float4_value____to=2&float4_value____from_____comparison_operator=Greater_than&float4_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?float4_value____from=1&float4_value____to=2&float4_value____from_____comparison_operator=Greater_than&float4_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?float4_value____from=1&float4_value____to=2&float4_value____from_____comparison_operator=Greater_than_or_equal_to&float4_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # "float8_value": 0, # try find the data by primary key but false by float8 def test_get_by_primary_key_with_false_float8_query_param(): # from response = client.get(f'/test/{sample_primary_key}?float8_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?float8_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??float8_value____from=-2&float8_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?float8_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?float8_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?float8_value____from=0&float8_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?float8_value____from=0&float8_value____to=0&float8_value____from_____comparison_operator=Greater_than_or_equal_to&float8_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?float8_value____from=-1&float8_value____to=2&float8_value____from_____comparison_operator=Greater_than&float8_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?float8_value____from=1&float8_value____to=2&float8_value____from_____comparison_operator=Greater_than&float8_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?float8_value____from=1&float8_value____to=2&float8_value____from_____comparison_operator=Greater_than_or_equal_to&float8_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by int2 # int2 0 def test_get_by_primary_key_with_false_int2_query_param(): # from response = client.get(f'/test/{sample_primary_key}?int2_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?int2_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??int2_value____from=-2&int2_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?int2_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?int2_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?int2_value____from=0&int2_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int2_value____from=0&int2_value____to=0&int2_value____from_____comparison_operator=Greater_than_or_equal_to&int2_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int2_value____from=-1&int2_value____to=2&int2_value____from_____comparison_operator=Greater_than&int2_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int2_value____from=1&int2_value____to=2&int2_value____from_____comparison_operator=Greater_than&int2_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int2_value____from=1&int2_value____to=2&int2_value____from_____comparison_operator=Greater_than_or_equal_to&int2_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by int4 # int 4 0 def test_get_by_primary_key_with_false_int4_query_param(): # from response = client.get(f'/test/{sample_primary_key}?int4_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?int4_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??int4_value____from=-2&int4_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?int4_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?int4_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?int4_value____from=0&int4_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int4_value____from=0&int4_value____to=0&int4_value____from_____comparison_operator=Greater_than_or_equal_to&int4_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int4_value____from=-1&int4_value____to=2&int4_value____from_____comparison_operator=Greater_than&int4_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int4_value____from=1&int4_value____to=2&int4_value____from_____comparison_operator=Greater_than&int4_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int4_value____from=1&int4_value____to=2&int4_value____from_____comparison_operator=Greater_than_or_equal_to&int4_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by int8 # int 8 0 def test_get_by_primary_key_with_false_int8_query_param(): # from response = client.get(f'/test/{sample_primary_key}?int8_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?int8_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??int8_value____from=-2&int8_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?int8_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?int8_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?int8_value____from=0&int8_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int8_value____from=0&int8_value____to=0&int8_value____from_____comparison_operator=Greater_than_or_equal_to&int8_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int8_value____from=-1&int8_value____to=2&int8_value____from_____comparison_operator=Greater_than&int8_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int8_value____from=1&int8_value____to=2&int8_value____from_____comparison_operator=Greater_than&int8_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int8_value____from=1&int8_value____to=2&int8_value____from_____comparison_operator=Greater_than_or_equal_to&int8_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by numeric # numeric 0 def test_get_by_primary_key_with_false_numeric_query_param(): # from response = client.get(f'/test/{sample_primary_key}?numeric_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?numeric_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??numeric_value____from=-2&numeric_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?numeric_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?numeric_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?numeric_value____from=0&numeric_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?numeric_value____from=0&numeric_value____to=0&numeric_value____from_____comparison_operator=Greater_than_or_equal_to&numeric_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?numeric_value____from=-1&numeric_value____to=2&numeric_value____from_____comparison_operator=Greater_than&numeric_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?numeric_value____from=1&numeric_value____to=2&numeric_value____from_____comparison_operator=Greater_than&numeric_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?numeric_value____from=1&numeric_value____to=2&numeric_value____from_____comparison_operator=Greater_than_or_equal_to&numeric_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by text # "text_value": "string", def test_get_by_primary_key_with_false_text_query_param(): response = client.get(f'/test/{sample_primary_key}?text_value____list=string1&text_value____list=string2', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?text_value____list=string&text_value____list=string1&', headers=headers) assert response.status_code == 200 # Like operator response = client.get( f'/test/{sample_primary_key}?text_value____str=string1&text_value____str=%tri%&text_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?text_value____str=string1&text_value____str=%tsri%&text_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 404 # Ilike operator response = client.get( f'/test/{sample_primary_key}?text_value____str=string1&text_value____str=%tRi%&text_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?text_value____str=string1&text_value____str=%tsri%&text_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 404 # not like operator response = client.get( f'/test/{sample_primary_key}?text_value____str=string2&text_value____str=%strg%&text_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?text_value____str=string&text_value____str=%strin%&text_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 404 # not ilike operator response = client.get( f'/test/{sample_primary_key}?text_value____str=String2&text_value____str=%Strg%&text_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?text_value____str=STRING&text_value____str=%TRI%&text_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 404 # match regex with case sensitive operator response = client.get( f'/test/{sample_primary_key}?text_value____str=stri.*&varchar_value____stg=str&text_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?text_value____str=stg.*&text_value____str=stg&text_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) assert response.status_code == 404 # match regex with case insensitive operator response = client.get( f'/test/{sample_primary_key}?text_value____str=strI.*&text_value____str=STG&text_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?text_value____str=stG.*&text_value____str=STG&text_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) assert response.status_code == 404 # does_not_match_regex_with_case_insensitive response = client.get( f'/test/{sample_primary_key}?text_value____str=strI.*&text_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?text_value____str=stG.*&text_value____str=STG&text_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) assert response.status_code == 200 # dose not match regex with case sensitive operator response = client.get( f'/test/{sample_primary_key}?text_value____str=stri.*&varchar_value____stg=str&text_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?text_value____str=stg.*&text_value____str=stg&text_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) assert response.status_code == 200 # similar_to response = client.get( f'/test/{sample_primary_key}?text_value____str=string&text_value____str=%(r|z)%&text_value____str_____matching_pattern=similar_to', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?text_value____str=str&text_value____str=(r|z)%&text_value____str_____matching_pattern=similar_to', headers=headers) assert response.status_code == 404 # not_similar_to response = client.get( f'/test/{sample_primary_key}?text_value____str=string&text_value____str=%(r|z)%&text_value____str_____matching_pattern=not_similar_to', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?text_value____str=str&text_value____str=(r|z)%&text_value____str_____matching_pattern=not_similar_to', headers=headers) assert response.status_code == 200 # try find the data by primary key but false by uuid def test_get_by_primary_key_with_false_uuid_query_param(): # In operator response = client.get( f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa6&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afb6', headers=headers) assert response.status_code == 404 # not In operator response = client.get( f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa6&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list_____comparison_operator=Not_in', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afb6&uuid_value____list_____comparison_operator=Not_in', headers=headers) assert response.status_code == 200 # Equal operator response = client.get( f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa6&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list_____comparison_operator=Equal', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afb6&uuid_value____list_____comparison_operator=Equal', headers=headers) assert response.status_code == 404 # not Equal operator response = client.get( f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa6&uuid_value____list_____comparison_operator=Not_equal', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afb6&uuid_value____list_____comparison_operator=Not_equal', headers=headers) assert response.status_code == 200 # try find the data by primary key but false by varchar def test_get_by_primary_key_with_false_varchar_query_param(): response = client.get(f'/test/{sample_primary_key}?varchar_value____list=string1&varchar_value____list=string2', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?varchar_value____list=string&varchar_value____list=string1&', headers=headers) assert response.status_code == 200 # Like operator response = client.get( f'/test/{sample_primary_key}?varchar_value____str=string1&varchar_value____str=%tri%&varchar_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?varchar_value____str=string1&varchar_value____str=%tsri%&varchar_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 404 # Ilike operator response = client.get( f'/test/{sample_primary_key}?varchar_value____str=string1&varchar_value____str=%tRi%&varchar_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?varchar_value____str=string1&varchar_value____str=%tsri%&varchar_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 404 # not like operator response = client.get( f'/test/{sample_primary_key}?varchar_value____str=string2&varchar_value____str=%strg%&varchar_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?varchar_value____str=string&varchar_value____str=%strin%&varchar_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 404 # not ilike operator response = client.get( f'/test/{sample_primary_key}?varchar_value____str=String2&varchar_value____str=%Strg%&varchar_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?varchar_value____str=STRING&varchar_value____str=%TRI%&varchar_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 404 # match regex with case sensitive operator response = client.get( f'/test/{sample_primary_key}?varchar_value____str=stri.*&varchar_value____stg=str&varchar_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?varchar_value____str=stg.*&varchar_value____str=stg&varchar_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) assert response.status_code == 404 # match regex with case insensitive operator response = client.get( f'/test/{sample_primary_key}?varchar_value____str=strI.*&varchar_value____str=STG&varchar_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?varchar_value____str=stG.*&varchar_value____str=STG&varchar_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) assert response.status_code == 404 # does_not_match_regex_with_case_insensitive response = client.get( f'/test/{sample_primary_key}?varchar_value____str=strI.*&varchar_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?varchar_value____str=stG.*&varchar_value____str=STG&varchar_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) assert response.status_code == 200 # dose not match regex with case sensitive operator response = client.get( f'/test/{sample_primary_key}?varchar_value____str=stri.*&varchar_value____stg=str&varchar_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?varchar_value____str=stg.*&varchar_value____str=stg&varchar_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) assert response.status_code == 200 # similar_to response = client.get( f'/test/{sample_primary_key}?varchar_value____str=string&varchar_value____str=%(r|z)%&varchar_value____str_____matching_pattern=similar_to', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?varchar_value____str=str&varchar_value____str=(r|z)%&varchar_value____str_____matching_pattern=similar_to', headers=headers) assert response.status_code == 404 # not_similar_to response = client.get( f'/test/{sample_primary_key}?varchar_value____str=string&varchar_value____str=%(r|z)%&varchar_value____str_____matching_pattern=not_similar_to', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?varchar_value____str=str&varchar_value____str=(r|z)%&varchar_value____str_____matching_pattern=not_similar_to', headers=headers) assert response.status_code == 200 # query by range of date field def test_get_by_primary_key_with_false_date_range_query_param(): # from response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-27', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?date_value____to=2021-07-24', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??date_value____from=2021-07-21&date_value____to=2021-07-24', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-24', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?date_value____to=2021-07-27', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-24&date_value____to=2021-07-27', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?date_value____from=2021-07-26&date_value____to=2021-07-26&date_value____from_____comparison_operator=Greater_than_or_equal_to&date_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?date_value____from=2021-07-25&date_value____to=2021-07-27&date_value____from_____comparison_operator=Greater_than&date_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?date_value____from=2021-07-26&date_value____to=2021-07-26&date_value____from_____comparison_operator=Greater_than&date_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?date_value____from=2021-07-27&date_value____to=2021-07-29&date_value____from_____comparison_operator=Greater_than_or_equal_to&date_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 def test_get_by_primary_key_with_false_time_range_query_param(): # from response = client.get(f'/test/{sample_primary_key}?time_value____from=19:18:18', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?time_value____to=17:18:18', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}?time_value____from=10:18:18&time_value____to=17:18:18', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?time_value____from=10:18:18', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?time_value____to=19:18:18', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?time_value____from=10:18:18&time_value____to=19:18:18', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?time_value____from=18:18:18&time_value____to=18:18:18&time_value____from_____comparison_operator=Greater_than_or_equal_to&time_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?time_value____from=18:18:17&time_value____to=18:18:19&time_value____from_____comparison_operator=Greater_than&time_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?time_value____from=18:18:18&time_value____to=18:18:18&time_value____from_____comparison_operator=Greater_than&time_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?time_value____from=19:18:18&time_value____to=19:19:18&time_value____from_____comparison_operator=Greater_than_or_equal_to&time_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 def test_get_by_primary_key_with_false_timestamp_range_query_param(): # "timestamp_value": "2021-07-26T02:17:46.846000", # from response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-27T02:17:46.846000', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?timestamp_value____to=2021-07-25T02:17:46.846000', headers=headers) assert response.status_code == 404 # from - to response = client.get( f'/test/{sample_primary_key}?timestamp_value____from=2021-07-20T02:17:46.846000×tamp_value____to=2021-07-25T02:17:46.846000', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-24T02:17:46.846000', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?timestamp_value____to=2021-07-28T02:17:46.846000', headers=headers) assert response.status_code == 200 # success from - to response = client.get( f'/test/{sample_primary_key}?timestamp_value____from=2021-07-24T02:17:46.846000×tamp_value____to=2021-07-28T02:17:46.846000', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?timestamp_value____from=2021-07-26T02:17:46.846×tamp_value____to=2021-07-26T02:17:46.846×tampt_value____from_____comparison_operator=Greater_than_or_equal_to×tampt_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?timestamp_value____from=2021-07-26T02:17:46.746×tamp_value____to=2021-07-26T02:17:46.946×tampt_value____from_____comparison_operator=Greater_than×tampt_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?timestamp_value____from=2021-07-26T02:17:46.846×tamp_value____to=2021-07-26T02:17:46.946×tamp_value____from_____comparison_operator=Greater_than×tamp_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?timestamp_value____from=2021-07-26T02:17:46.856×tamp_value____to=2021-07-26T02:17:46.986×tamp_value____from_____comparison_operator=Greater_than_or_equal_to×tamp_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 def test_get_by_primary_key_with_false_timetz_range_query_param(): # from response = client.get(f'/test/{sample_primary_key}?timetz_value____from=19%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?timetz_value____to=17%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 404 # from - to response = client.get( f'/test/{sample_primary_key}?timetz_value____from=16%3A18%3A18%2B00%3A00&timetz_value____to=17%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?timetz_value____from=17%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?timetz_value____to=19%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 200 # success from - to response = client.get( f'/test/{sample_primary_key}?timetz_value____from=16%3A18%3A18%2B00%3A00&timetz_value____to=19%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?timetz_value____from_____comparison_operator=Greater_than&timetz_value____to_____comparison_operator=Less_than&timetz_value____from=17%3A18%3A18%2B00&timetz_value____to=19%3A18%3A18%2B00', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?timetz_value____from_____comparison_operator=Greater_than_or_equal_to&timetz_value____to_____comparison_operator=Less_than_or_equal_to&timetz_value____from=18%3A18%3A18%2B00&timetz_value____to=18%3A19%3A18%2B00', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?timetz_value____from_____comparison_operator=Greater_than&timetz_value____to_____comparison_operator=Less_than&timetz_value____from=16%3A18%3A18%2B00&timetz_value____to=18%3A18%3A18%2B00', headers=headers) assert response.status_code == 404 # failure from - to with special operator response = client.get( f'/test/{sample_primary_key}?timetz_value____from_____comparison_operator=Greater_than_or_equal_to&timetz_value____to_____comparison_operator=Less_than_or_equal_to&timetz_value____from=16%3A18%3A18%2B00&timetz_value____to=17%3A19%3A18%2B00', headers=headers) assert response.status_code == 404 def test_get_by_primary_key_with_false_timestamptz_range_query_param(): # "timestamp_value": "2021-07-26T02:17:46.846000", # from response = client.get( f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-27T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 404 # to response = client.get( f'/test/{sample_primary_key}?timestamptz_value____to=2021-07-25T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 404 # from - to response = client.get( f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-27T02%3A17%3A46.846000%2B00%3A00×tamptz_value____to=2021-07-28T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 404 # success from response = client.get( f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-20T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 200 # success to response = client.get( f'/test/{sample_primary_key}?timestamptz_value____to=2021-07-29T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 200 # success from - to response = client.get( f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-20T02%3A17%3A46.846000%2B00%3A00×tamptz_value____to=2021-07-27T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-26T02%3A17%3A46.846Z×tamptz_value____to=2021-07-26T02%3A17%3A46.846Z×tamptz_value____from_____comparison_operator=Greater_than_or_equal_to×tamptz_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-26T02%3A17%3A46.800Z×tamptz_value____to=2021-07-26T02%3A17%3A46.946Z×tamptz_value____from_____comparison_operator=Greater_than×tamptz_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-26T02%3A17%3A46.846Z×tamptz_value____to=2021-07-26T02%3A17%3A46.900Z×tamptz_value____from_____comparison_operator=Greater_than×tamptz_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-26T02%3A17%3A46.847Z×tamptz_value____to=2021-07-26T02%3A17%3A46.946Z×tamptz_value____from_____comparison_operator=Greater_than_or_equal_to×tamptz_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test_async/test_other_default_value.py ================================================ import asyncio import json import os import uuid from copy import deepcopy from datetime import datetime, timezone, date, timedelta from http import HTTPStatus from urllib.parse import urlencode from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_ASYNC_URL', 'postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession engine = create_async_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(autocommit=False, autoflush=False, bind=engine, class_=AsyncSession) async def get_transaction_session() -> AsyncSession: async with async_session() as session: yield session class UUIDTable(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_default_value_sync' __table_args__ = ( UniqueConstraint('primary_key', 'int4_value', 'float4_value'), ) primary_key = Column(UUID(as_uuid=True), primary_key=True, info={'alias_name': 'primary_key'}, server_default=text("uuid_generate_v4()")) bool_value = Column(Boolean, nullable=False, default=False) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) def setup_module(module): async def create_table(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) loop = asyncio.get_event_loop() loop.run_until_complete(create_table()) route_1 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.FIND_MANY, CrudMethods.UPSERT_MANY, CrudMethods.UPDATE_ONE, CrudMethods.UPDATE_MANY, CrudMethods.PATCH_MANY, CrudMethods.PATCH_ONE, CrudMethods.DELETE_MANY, CrudMethods.DELETE_ONE, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) route_2 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.UPSERT_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_2", tags=["test"] ) route_3 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_3", tags=["test"] ) [app.include_router(i) for i in [route_1, route_2, route_3]] client = TestClient(app) def test_get_one_data_and_create_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() find_target = create_response['primary_key'] response = client.get(f'/test/{find_target}', headers=headers, data=data) assert response.status_code == 200 assert response.json() == create_response create_response.pop('primary_key') query_param = urlencode(create_response) response = client.get(f'/test/{find_target}?{query_param}', headers=headers, data=data) assert response.status_code == 200 def test_get_many_data_and_create_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '''{ "insert": [ { "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00","varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }, { "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] },{ "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] } ] }''' data_dict = json.loads(data)['insert'] response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_dict): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_update_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() created_primary_key = create_response['primary_key'] update_data = { "bool_value":False,"char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} query_param = urlencode(update_data) response = client.put(f'/test/{created_primary_key}?{query_param}', data=json.dumps(update_data)) update_data["bool_value"] = False response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_update_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, { "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params)+f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value":False,"char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test?{query_string}', data=json.dumps(update_data)) update_data["bool_value"] = False response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: assert k[i] == update_data[i] def test_patch_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) update_data = {"bool_value": False} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(params) update_data = {"char_value": "string_u "} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(params) update_data = {"date_value": "2022-07-24"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(params) update_data = {"char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) update_data['bool_value'] = False response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_patch_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, { "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value": True, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00","varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test?{query_string}', data=json.dumps(update_data)) update_data['bool_value'] = True response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_delete_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) response = client.delete(f'/test/{primary_key}?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_delete_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{ "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, { "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, { "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' response = client.delete(f'/test?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_post_redirect_get_data(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_3', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() response_data['bool_value'] = False assert 'primary_key' in response_data for k, v in response_data.items(): if k in change: if isinstance(v, str): v = v.strip() response_ = json.dumps(v).strip() request_ = json.dumps(change[k]).strip() assert request_ == response_ return response_data def test_upsert_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 10 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k,v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 # conflict upsert_data = deepcopy(updated_data) upsert_data['on_conflict'] = {'update_columns':['numeric_value']} response = client.post('/test_2', headers=headers, data=json.dumps(dict(upsert_data, **json.loads(data)))) assert response.status_code == 201 # create response = client.post('/test_2', headers=headers, data=json.dumps(dict(updated_data, **json.loads(data)))) assert response.status_code == 409 def test_upsert_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 12.784 ,"int2_value": 0, "int4_value": 10 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k,v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 # conflict upsert_data = deepcopy(updated_data) upsert_data['on_conflict'] = {'update_columns':['numeric_value']} response = client.post('/test_2', headers=headers, data=json.dumps(dict(upsert_data, **json.loads(data)))) assert response.status_code == 201 # create response = client.post('/test_2', headers=headers, data=json.dumps(dict(updated_data, **json.loads(data)))) assert response.status_code == 409 def teardown_module(module): async def create_table(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.drop_all) loop = asyncio.get_event_loop() loop.run_until_complete(create_table()) ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test_async/test_other_single_unique.py ================================================ import asyncio import json import os import uuid from copy import deepcopy from datetime import datetime, timezone, date, timedelta from http import HTTPStatus from urllib.parse import urlencode from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_ASYNC_URL', 'postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession engine = create_async_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(autocommit=False, autoflush=False, bind=engine, class_=AsyncSession) async def get_transaction_session() -> AsyncSession: async with async_session() as session: yield session class UUIDTable(Base): __tablename__ = 'test_single_unique_table_async' id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("uuid_generate_v4()")) bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False,unique=True) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=True) int4_value = Column(Integer, nullable=True) int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) def setup_module(module): async def create_table(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) loop = asyncio.get_event_loop() loop.run_until_complete(create_table()) route_1 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.FIND_MANY, CrudMethods.UPSERT_MANY, CrudMethods.UPDATE_ONE, CrudMethods.UPDATE_MANY, CrudMethods.PATCH_MANY, CrudMethods.PATCH_ONE, CrudMethods.DELETE_MANY, CrudMethods.DELETE_ONE, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test", tags=["test"] ) route_2 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.UPSERT_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test_2", tags=["test"] ) route_3 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test_3", tags=["test"] ) [app.include_router(i) for i in [route_1, route_2, route_3]] client = TestClient(app) def test_get_one_data_and_create_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0.443}' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() find_target = create_response['id'] response = client.get(f'/test/{find_target}', headers=headers, data=data) assert response.status_code == 200 assert response.json() == create_response create_response.pop('id') query_param = urlencode(create_response) response = client.get(f'/test/{find_target}?{query_param}', headers=headers, data=data) assert response.status_code == 200 def test_get_many_data_and_create_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '''{ "insert": [ { "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0.12, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00","varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }, { "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 1.2, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] },{ "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 9.3, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] } ] }''' data_dict = json.loads(data)['insert'] response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_dict): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_update_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0.98}' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() created_primary_key = create_response['id'] update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 12.7, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} query_param = urlencode(update_data) response = client.put(f'/test/{created_primary_key}?{query_param}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_update_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 3.5, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 3.6, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 3.7, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['id'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 200, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params)+f'&id____list={primary_key_list[0]}&id____list={primary_key_list[1]}&id____list={primary_key_list[2]}&float4_value____list=3.5&float4_value____list=3.6&float4_value____list=3.7' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.58, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test?{query_string}', data=json.dumps(update_data)) # FIXME: update the unique column will conflict, it may not a issue, because it should input all columns, you can use the patch assert response.status_code == 409 # response_data = response.json() # assert len(response_data) == 3 # for k in response_data: # for i in update_data: # assert k[i] == update_data[i] def test_patch_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 5.78, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['id'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 500, "float4_value____list": 5.78, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) update_data = {"bool_value": False} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(params) update_data = {"char_value": "string_u "} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(params) update_data = {"date_value": "2022-07-24"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(params) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 1.70, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_patch_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.91, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.92, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.93, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['id'] for i in insert_response_data] params = { "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 500, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&id____list={primary_key_list[0]}&id____list={primary_key_list[1]}&id____list={primary_key_list[2]}&float4_value____list=0.91&float4_value____list=0.92&float4_value____list=0.93' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00","varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_delete_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 2.54, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['id'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 500, "float4_value____list": 2.54, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) response = client.delete(f'/test/{primary_key}?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_delete_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.875, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.876, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.877, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['id'] for i in insert_response_data] params = { "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 500, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&id____list={primary_key_list[0]}&id____list={primary_key_list[1]}&id____list={primary_key_list[2]}&float4_value____list=0.875&float4_value____list=0.876&&float4_value____list=0.877' response = client.delete(f'/test?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_post_redirect_get_data(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} bool_value_change = False char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 55.7 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_3', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() assert 'id' in response_data for k, v in response_data.items(): if k in change: if isinstance(v, str): v = v.strip() response_ = json.dumps(v).strip() request_ = json.dumps(change[k]).strip() assert request_ == response_ return response_data def test_upsert_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 12.784}' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k,v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 # conflict upsert_data = deepcopy(updated_data) upsert_data['on_conflict'] = {'update_columns':['numeric_value']} response = client.post('/test_2', headers=headers, data=json.dumps(dict(upsert_data, **json.loads(data)))) assert response.status_code == 201 # create response = client.post('/test_2', headers=headers, data=json.dumps(dict(updated_data, **json.loads(data)))) assert response.status_code == 409 def teardown_module(module): async def create_table(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.drop_all) loop = asyncio.get_event_loop() loop.run_until_complete(create_table()) ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test_async/test_other_uuid_primary.py ================================================ import asyncio import json import os import uuid from copy import deepcopy from datetime import datetime, timezone, date, timedelta from http import HTTPStatus from urllib.parse import urlencode from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_ASYNC_URL', 'postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession engine = create_async_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(autocommit=False, autoflush=False, bind=engine, class_=AsyncSession) async def get_transaction_session() -> AsyncSession: async with async_session() as session: yield session class UUIDTable(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_uuid_primary_async' __table_args__ = ( UniqueConstraint('primary_key', 'int4_value', 'float4_value'), ) primary_key = Column(UUID(as_uuid=True), primary_key=True, server_default=text("uuid_generate_v4()")) bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) async def create_table(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) loop = asyncio.get_event_loop() loop.run_until_complete(create_table()) route_1 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.FIND_MANY, CrudMethods.UPSERT_MANY, CrudMethods.UPDATE_ONE, CrudMethods.UPDATE_MANY, CrudMethods.PATCH_MANY, CrudMethods.PATCH_ONE, CrudMethods.DELETE_MANY, CrudMethods.DELETE_ONE, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test", tags=["test"] ) route_2 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, async_mode=True, crud_methods=[ CrudMethods.UPSERT_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_2", tags=["test"] ) route_3 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test_3", tags=["test"] ) [app.include_router(i) for i in [route_1, route_2, route_3]] client = TestClient(app) def test_get_one_data_and_create_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() find_target = create_response['primary_key'] response = client.get(f'/test/{find_target}', headers=headers, data=data) assert response.status_code == 200 assert response.json() == create_response create_response.pop('primary_key') query_param = urlencode(create_response) response = client.get(f'/test/{find_target}?{query_param}', headers=headers, data=data) assert response.status_code == 200 def test_get_many_data_and_create_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '''{ "insert": [ { "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00","varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }, { "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] },{ "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] } ] }''' data_dict = json.loads(data)['insert'] response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_dict): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_update_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() created_primary_key = create_response['primary_key'] update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} query_param = urlencode(update_data) response = client.put(f'/test/{created_primary_key}?{query_param}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_update_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params)+f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: assert k[i] == update_data[i] def test_patch_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) update_data = {"bool_value": False} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(params) update_data = {"char_value": "string_u "} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(params) update_data = {"date_value": "2022-07-24"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(params) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_patch_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00","varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_delete_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) response = client.delete(f'/test/{primary_key}?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_delete_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' response = client.delete(f'/test?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_post_redirect_get_data(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} bool_value_change = False char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_3', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() assert 'primary_key' in response_data for k, v in response_data.items(): if k in change: if isinstance(v, str): v = v.strip() response_ = json.dumps(v).strip() request_ = json.dumps(change[k]).strip() assert request_ == response_ return response_data def test_upsert_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 10 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k,v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 # conflict upsert_data = deepcopy(updated_data) upsert_data['on_conflict'] = {'update_columns':['numeric_value']} response = client.post('/test_2', headers=headers, data=json.dumps(dict(upsert_data, **json.loads(data)))) assert response.status_code == 201 # create response = client.post('/test_2', headers=headers, data=json.dumps(dict(updated_data, **json.loads(data)))) assert response.status_code == 409 ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test_async/test_patch_many_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy.api_test_async import get_transaction_session, app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # create_one_model = api_model[CrudMethods.UPSERT_ONE].__dict__ # assert create_one_model['requestModel'] or create_one_model['responseModel'] # create_one_request_model = deepcopy(create_one_model['requestModel'].__dict__['__fields__']) # create_one_response_model = deepcopy(create_one_model['responseModel'].__dict__['__fields__']) # Request Test # assert create_one_request_model.pop('on_conflict', False) # for k, v in create_one_request_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Response Test # for k, v in create_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_one", async_mode=True, tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # create_many_model = api_model[CrudMethods.UPSERT_MANY].__dict__ # assert create_many_model['requestModel'] or create_many_model['responseModel'] # create_many_request_model = deepcopy(create_many_model['requestModel'].__dict__['__fields__']) # create_many_response_model = deepcopy(create_many_model['responseModel'].__dict__['__fields__']) # # # Request Model Test # assert create_many_request_model.pop('on_conflict', None) # insert_many_model = create_many_request_model['insert'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in insert_many_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # # # Response Model Test # for k, v in create_many_response_model.items(): # create_many_response_model_item = v.type_.__dict__['__fields__'] # for k, v in create_many_response_model_item.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", async_mode=True, tags=["test"] ) # Response Mode Test # response_many = create_many_response_model['__root__'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in response_many.items(): # assert not v.required UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # post_redirect_get_model = api_model[CrudMethods.POST_REDIRECT_GET].__dict__ # assert post_redirect_get_model['requestModel'] or post_redirect_get_model['responseModel'] # post_redirect_get_request_model = deepcopy(post_redirect_get_model['requestModel'].__dict__['__fields__']) # post_redirect_get_response_model = deepcopy(post_redirect_get_model['responseModel'].__dict__['__fields__']) # Request Model Test # for k, v in post_redirect_get_request_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Response Model Test # for k, v in post_redirect_get_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # for k, v in post_redirect_get_response_model.items(): # assert v.required test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", async_mode=True, tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # # FIXME some thing may not require # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", async_mode=True, tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.PATCH_MANY ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # # FIXME some thing may not require # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_patch_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_patch_many", async_mode=True, tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_patch_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def test_create_many_and_patch_many(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test_patch_many?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test_async/test_patch_one_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy.api_test_async import get_transaction_session, app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # create_one_model = api_model[CrudMethods.UPSERT_ONE].__dict__ # assert create_one_model['requestModel'] or create_one_model['responseModel'] # create_one_request_model = deepcopy(create_one_model['requestModel'].__dict__['__fields__']) # create_one_response_model = deepcopy(create_one_model['responseModel'].__dict__['__fields__']) # Request Test # assert create_one_request_model.pop('on_conflict', False) # for k, v in create_one_request_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Response Test # for k, v in create_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_one", async_mode=True, tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # create_many_model = api_model[CrudMethods.UPSERT_MANY].__dict__ # assert create_many_model['requestModel'] or create_many_model['responseModel'] # create_many_request_model = deepcopy(create_many_model['requestModel'].__dict__['__fields__']) # create_many_response_model = deepcopy(create_many_model['responseModel'].__dict__['__fields__']) # # # Request Model Test # assert create_many_request_model.pop('on_conflict', None) # insert_many_model = create_many_request_model['insert'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in insert_many_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # # # Response Model Test # for k, v in create_many_response_model.items(): # create_many_response_model_item = v.type_.__dict__['__fields__'] # for k, v in create_many_response_model_item.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", async_mode=True, tags=["test"] ) # Response Mode Test # response_many = create_many_response_model['__root__'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in response_many.items(): # assert not v.required UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # post_redirect_get_model = api_model[CrudMethods.POST_REDIRECT_GET].__dict__ # assert post_redirect_get_model['requestModel'] or post_redirect_get_model['responseModel'] # post_redirect_get_request_model = deepcopy(post_redirect_get_model['requestModel'].__dict__['__fields__']) # post_redirect_get_response_model = deepcopy(post_redirect_get_model['responseModel'].__dict__['__fields__']) # Request Model Test # for k, v in post_redirect_get_request_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Response Model Test # for k, v in post_redirect_get_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # for k, v in post_redirect_get_response_model.items(): # assert v.required test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", async_mode=True, tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # # FIXME some thing may not require # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, async_mode=True, prefix="/test", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.PATCH_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # # FIXME some thing may not require # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_update_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_patch_one", async_mode=True, tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_update_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def test_create_one_and_patch_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False} response = client.patch(f'/test_patch_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(OrderedDict(**params)) update_data = {"char_value": "string_u "} response = client.patch(f'/test_patch_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(OrderedDict(**params)) update_data = {"date_value": "2022-07-24"} # update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, # "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, # "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, # "text_value": "string_update", # "timestamp_value": "2022-07-24T02:54:53.285000", # "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", # "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", # "array_value": [1, 2, 3, 4, 5], # "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test_patch_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test_patch_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test_async/test_post_redirect_get_api.py ================================================ import json import os import uuid from datetime import date, timedelta, datetime, timezone from http import HTTPStatus from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession from sqlalchemy.orm import sessionmaker from starlette.testclient import TestClient from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy.api_test_async import app, UntitledTable256 TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_ASYNC_URL', 'postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres') engine = create_async_engine(TEST_DATABASE_URL, echo=True, future=True) async_session = sessionmaker( engine, class_=AsyncSession, expire_on_commit=False ) async def get_transaction_session() -> AsyncSession: async with async_session() as session: yield session UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", async_mode=True, tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_post_and_redirect_get_without_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get_without_get", async_mode=True, tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", async_mode=True, tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_get_data, test_post_and_redirect_get_without_get]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields # Post Redirect Get API Test def test_create_one_but_no_follow_redirect(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } data = '{ "bool_value": true, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }' response = client.post('/test_post_direct_get', headers=headers, data=data, allow_redirects=False) assert response.status_code == HTTPStatus.SEE_OTHER def test_create_one_with_redirect(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} bool_value_change = False char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' uuid_value_change = str(uuid.uuid4()) varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['uuid_value'] = uuid_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_post_direct_get', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() assert primary_key_name in response_data for k, v in response_data.items(): if k in change: if isinstance(v, str): v = v.strip() response_ = json.dumps(v).strip() request_ = json.dumps(change[k]).strip() assert request_ == response_ return response_data def test_create_but_conflict(): data = test_create_one_with_redirect() headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.post('/test_post_direct_get', headers=headers, data=json.dumps(data), allow_redirects=True) assert response.status_code == HTTPStatus.CONFLICT def test_create_but_not_found_get_api(): change = {} bool_value_change = False char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' uuid_value_change = str(uuid.uuid4()) varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['uuid_value'] = uuid_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data = json.dumps(change) headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.post('/test_post_direct_get_without_get', headers=headers, data=data, allow_redirects=True) assert response.status_code == HTTPStatus.NOT_FOUND test_create_but_not_found_get_api() ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test_async/test_put_many_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy.api_test_async import get_transaction_session, app, UntitledTable256 UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # create_one_model = api_model[CrudMethods.UPSERT_ONE].__dict__ # assert create_one_model['requestModel'] or create_one_model['responseModel'] # create_one_request_model = deepcopy(create_one_model['requestModel'].__dict__['__fields__']) # create_one_response_model = deepcopy(create_one_model['responseModel'].__dict__['__fields__']) # Request Test # assert create_one_request_model.pop('on_conflict', False) # for k, v in create_one_request_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Response Test # for k, v in create_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_one", async_mode=True, tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # create_many_model = api_model[CrudMethods.UPSERT_MANY].__dict__ # assert create_many_model['requestModel'] or create_many_model['responseModel'] # create_many_request_model = deepcopy(create_many_model['requestModel'].__dict__['__fields__']) # create_many_response_model = deepcopy(create_many_model['responseModel'].__dict__['__fields__']) # # # Request Model Test # assert create_many_request_model.pop('on_conflict', None) # insert_many_model = create_many_request_model['insert'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in insert_many_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # # # Response Model Test # for k, v in create_many_response_model.items(): # create_many_response_model_item = v.type_.__dict__['__fields__'] # for k, v in create_many_response_model_item.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", async_mode=True, tags=["test"] ) # Response Mode Test # response_many = create_many_response_model['__root__'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in response_many.items(): # assert not v.required UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # post_redirect_get_model = api_model[CrudMethods.POST_REDIRECT_GET].__dict__ # assert post_redirect_get_model['requestModel'] or post_redirect_get_model['responseModel'] # post_redirect_get_request_model = deepcopy(post_redirect_get_model['requestModel'].__dict__['__fields__']) # post_redirect_get_response_model = deepcopy(post_redirect_get_model['responseModel'].__dict__['__fields__']) # Request Model Test # for k, v in post_redirect_get_request_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Response Model Test # for k, v in post_redirect_get_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # for k, v in post_redirect_get_response_model.items(): # assert v.required test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", async_mode=True, tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # # FIXME some thing may not require # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", async_mode=True, tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPDATE_MANY ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) # # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # # FIXME some thing may not require # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_update_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_update_many", async_mode=True, tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_update_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def test_create_many_and_update_many(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test_update_many?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_create_many_and_update_many_but_not_found(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '10:18:18', "time_value____to": '12:18:18', "time_value____list": '10:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "timez_value____from": '18:18:18+00:00', "timez_value____to": '18:18:18+00:00', "timez_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test_update_many?{query_string}', data=json.dumps(update_data)) # response_data = response.json() # assert len(response_data) == 3 # for k in response_data: # for i in update_data: # print(i) # print(k[i]) # assert k[i] == update_data[i] assert response.status_code == 204 ================================================ FILE: tests/test_implementations/test_sqlalchemy/api_test_async/test_put_one_api.py ================================================ import json import os from collections import OrderedDict from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession from sqlalchemy.orm import sessionmaker from starlette.testclient import TestClient from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy.api_test_async import app, UntitledTable256 TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_ASYNC_URL', 'postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres') engine = create_async_engine(TEST_DATABASE_URL, echo=True, future=True) async_session = sessionmaker( engine, class_=AsyncSession, expire_on_commit=False ) async def get_session() -> AsyncSession: async with async_session() as session: yield session UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_one = crud_router_builder(db_session=get_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_one", async_mode=True, tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_create_many = crud_router_builder(db_session=get_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_creation_many", async_mode=True, tags=["test"] ) # Response Mode Test # response_many = create_many_response_model['__root__'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in response_many.items(): # assert not v.required UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_post_and_redirect_get = crud_router_builder(db_session=get_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test_post_direct_get", async_mode=True, tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_get_data = crud_router_builder(db_session=get_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, prefix="/test", async_mode=True, tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPDATE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) test_update_data = crud_router_builder(db_session=get_session, db_model=UntitledTable256, crud_models=UntitledTable256Model, async_mode=True, prefix="/test_update_one", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_update_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = UntitledTable256.primary_key_of_table unique_fields = UntitledTable256.unique_fields def test_create_one_and_update_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test_update_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: print(i) print(response_data[i]) assert response_data[i] == update_data[i] def test_create_one_and_update_one_but_not_found(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key ,= [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '10:18:18', "time_value____to": '12:18:18', "time_value____list": '10:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_valuez____from": '18:18:18+00:00', "time_valuez____to": '18:18:18+00:00', "time_valuez____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test_update_one/{primary_key}?{query_string}', data=json.dumps(update_data)) # response_data = response.json() response.status_code = 404 # assert response_data # for i in update_data: # assert response_data[i] == update_data[i] ================================================ FILE: tests/test_implementations/test_sqlalchemy/error_test/__init__.py ================================================ ================================================ FILE: tests/test_implementations/test_sqlalchemy/error_test/test_create_null_type.py ================================================ from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, Numeric, SmallInteger, String, Text, Time, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods from src.fastapi_quickcrud.misc.exceptions import ColumnTypeNotSupportedException Base = declarative_base() metadata = Base.metadata class UntitledTable256(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_build_myself_async' primary_key = Column(Integer, info={'alias_name': 'primary_key'}, autoincrement=True, primary_key=True, server_default="nextval('test_build_myself_id_seq'::regclass)") bool_value = Column(Boolean, nullable=False, server_default=text("false")) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(None) from sqlalchemy.orm import sessionmaker import os from sqlalchemy import create_engine TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_ASYNC_URL', 'postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres') engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.PATCH_ONE, ], exclude_columns=['xml_value', 'box_valaue']) except ColumnTypeNotSupportedException as e: assert 'The type of column array_str__value (NULL) not supported yet' in str(e) ================================================ FILE: tests/test_implementations/test_sqlalchemy/error_test/test_create_specific_api_when_no_pk.py ================================================ from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, text, PrimaryKeyConstraint, Table, UniqueConstraint from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, synonym from src.fastapi_quickcrud.misc.utils import table_to_declarative_base from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods from src.fastapi_quickcrud.misc.exceptions import SchemaException, ColumnTypeNotSupportedException, PrimaryMissing Base = declarative_base() metadata = Base.metadata UntitledTable256 = Table( 'test_table', metadata, Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float, nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL), Column('json_value', JSON), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric), Column('text_value', Text), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('uuid_value', UUID), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), UniqueConstraint('interval_value', 'numeric_value', 'text_value'), ) UntitledTable256 = table_to_declarative_base(UntitledTable256) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.PATCH_ONE, ], exclude_columns=['xml_value', 'box_valaue','__id']) except PrimaryMissing as e: assert 'The generation of this API [PATCH_ONE] requires a primary key' in str(e) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE, ], exclude_columns=['xml_value', 'box_valaue','__id']) except PrimaryMissing as e: print(str(e)) assert 'The generation of this API [FIND_ONE] requires a primary key' in str(e) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.DELETE_ONE, ], exclude_columns=['xml_value', 'box_valaue','__id']) except PrimaryMissing as e: print(str(e)) assert 'The generation of this API [DELETE_ONE] requires a primary key' in str(e) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPDATE_ONE, ], exclude_columns=['xml_value', 'box_valaue','__id']) except PrimaryMissing as e: print(str(e)) assert 'The generation of this API [UPDATE_ONE] requires a primary key' in str(e) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['xml_value', 'box_valaue','__id']) except PrimaryMissing as e: print(str(e)) assert 'The generation of this API [POST_REDIRECT_GET] requires a primary key' in str(e) ================================================ FILE: tests/test_implementations/test_sqlalchemy/error_test/test_create_table_with_more_than_one_unique_but_no_use_composite.py ================================================ from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, text, PrimaryKeyConstraint, Table, UniqueConstraint from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, synonym from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud.misc.utils import table_to_declarative_base from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods from src.fastapi_quickcrud.misc.exceptions import SchemaException, ColumnTypeNotSupportedException, PrimaryMissing Base = declarative_base() metadata = Base.metadata UntitledTable256 = Table( 'test_table', metadata, Column('id', Integer, autoincrement=True, primary_key=True), Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float, nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL, unique=True), Column('json_value', JSON, unique=True), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric, unique=True), Column('text_value', Text), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('uuid_value', UUID), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), ) from sqlalchemy.orm import sessionmaker import os from sqlalchemy import create_engine TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_ASYNC_URL', 'postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres') engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() UntitledTable256 = table_to_declarative_base(UntitledTable256) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.PATCH_ONE, ], exclude_columns=['xml_value', 'box_valaue', '__id']) except SchemaException as e: assert 'nly support one unique constraint/ Use unique constraint and composite unique constraint at same time is not supported / Use composite unique constraint if there are more than one unique constraint' in str(e) ================================================ FILE: tests/test_implementations/test_sqlalchemy/error_test/test_use_blob_type_column.py ================================================ from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud import CrudMethods Base = declarative_base() class UntitledTable256(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_build_myself_async' primary_key = Column(Integer, info={'alias_name': 'primary_key'}, autoincrement=True, primary_key=True, server_default="nextval('test_build_myself_id_seq'::regclass)") bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) from sqlalchemy.orm import sessionmaker import os from sqlalchemy import create_engine TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_ASYNC_URL', 'postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres') engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.PATCH_ONE, ], exclude_columns=['xml_value', 'box_valaue']) except BaseException as e: assert 'The type of column bytea_value (BLOB) not supported yet' in str(e) ================================================ FILE: tests/test_implementations/test_sqlalchemy/error_test/test_use_composite_primary.py ================================================ from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, text, PrimaryKeyConstraint from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods from src.fastapi_quickcrud.misc.exceptions import SchemaException Base = declarative_base() class UntitledTable256(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_build_myself_async' __table_args__ = ( PrimaryKeyConstraint('primary_key', 'int4_value', 'float4_value'), ) primary_key = Column(Integer, info={'alias_name': 'primary_key'}, autoincrement=True, server_default="nextval('test_build_myself_id_seq'::regclass)") bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False, unique=True) int4_value = Column(Integer, nullable=False, unique=True) int8_value = Column(BigInteger, server_default=text("99"), unique=True) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) except SchemaException as e: print(e) 'multiple primary key / or composite not supported;' in str(e) ================================================ FILE: tests/test_implementations/test_sqlalchemy/error_test/test_use_more_than_one_pk.py ================================================ from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, text, PrimaryKeyConstraint from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods from src.fastapi_quickcrud.misc.exceptions import SchemaException Base = declarative_base() class UntitledTable256(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_build_myself_async' primary_key = Column(Integer,primary_key=True, info={'alias_name': 'primary_key'}, autoincrement=True, server_default="nextval('test_build_myself_id_seq'::regclass)") bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10),primary_key=True,) date_value = Column(Date, server_default=text("now()"),primary_key=True,) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False, unique=True) int4_value = Column(Integer, nullable=False, unique=True) int8_value = Column(BigInteger, server_default=text("99"), unique=True) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) except SchemaException as e: print(e) 'multiple primary key / or composite not supported;' in str(e) ================================================ FILE: tests/test_implementations/test_sqlalchemy/error_test/test_use_more_than_one_unique.py ================================================ from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods from src.fastapi_quickcrud.misc.exceptions import SchemaException, MultipleSingleUniqueNotSupportedException Base = declarative_base() class UntitledTable256(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_build_myself_async' primary_key = Column(Integer, primary_key=True, info={'alias_name': 'primary_key'},autoincrement=True,server_default="nextval('test_build_myself_id_seq'::regclass)") bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False, unique=True) int4_value = Column(Integer, nullable=False, unique=True) int8_value = Column(BigInteger, server_default=text("99"), unique=True) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) except SchemaException as e: str(e) == 'Only support one unique constraint/ Use unique constraint and composite unique constraint at same time is not supported / Use composite unique constraint if there are more than one unique constraint' ================================================ FILE: tests/test_implementations/test_sqlalchemy/error_test/test_use_unique_and_composite_unique.py ================================================ from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods from src.fastapi_quickcrud.misc.exceptions import SchemaException Base = declarative_base() class UntitledTable256(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_build_myself_async' __table_args__ = ( UniqueConstraint('primary_key', 'int4_value', 'float4_value'), ) primary_key = Column(Integer, primary_key=True, info={'alias_name': 'primary_key'},autoincrement=True,server_default="nextval('test_build_myself_id_seq'::regclass)") bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99"), unique=True) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) except SchemaException as e: str(e) == 'Only support one unique constraint/ Use unique constraint and composite unique constraint at same time is not supported / Use composite unique constraint if there are more than one unique constraint' ================================================ FILE: tests/test_implementations/test_sqlalchemy/error_test/test_use_unsupported_type_pk.py ================================================ from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, text, PrimaryKeyConstraint from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, synonym from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods from src.fastapi_quickcrud.misc.exceptions import SchemaException, ColumnTypeNotSupportedException Base = declarative_base() class UntitledTable256(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_build_myself_async' primary_key = Column(LargeBinary, primary_key = True, info={'alias_name': 'primary_key'}, autoincrement=True, server_default="nextval('test_build_myself_id_seq'::regclass)") bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False, unique=True) int4_value = Column(Integer, nullable=False, unique=True) int8_value = Column(BigInteger, server_default=text("99"), unique=True) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) except ColumnTypeNotSupportedException as e: 'not supported yet' in str(e) ================================================ FILE: tests/test_implementations/test_sqlalchemy/error_test/test_use_unsupported_type_pk_2.py ================================================ from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, text, PrimaryKeyConstraint from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, synonym from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods from src.fastapi_quickcrud.misc.exceptions import SchemaException, ColumnTypeNotSupportedException Base = declarative_base() class UntitledTable256(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_build_myself_async' primary_key = Column(INTERVAL, primary_key = True, info={'alias_name': 'primary_key'}, autoincrement=True, server_default="nextval('test_build_myself_id_seq'::regclass)") bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False, unique=True) int4_value = Column(Integer, nullable=False, unique=True) int8_value = Column(BigInteger, server_default=text("99"), unique=True) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) except ColumnTypeNotSupportedException as e: 'not supported yet' in str(e) ================================================ FILE: tests/test_implementations/test_sqlalchemy/error_test/test_use_unsupported_type_pk_3.py ================================================ from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, text, PrimaryKeyConstraint from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, synonym from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods from src.fastapi_quickcrud.misc.exceptions import SchemaException, ColumnTypeNotSupportedException Base = declarative_base() class UntitledTable256(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_build_myself_async' primary_key = Column(JSON, primary_key = True, info={'alias_name': 'primary_key'}, autoincrement=True, server_default="nextval('test_build_myself_id_seq'::regclass)") bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False, unique=True) int4_value = Column(Integer, nullable=False, unique=True) int8_value = Column(BigInteger, server_default=text("99"), unique=True) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) except ColumnTypeNotSupportedException as e: 'not supported yet' in str(e) ================================================ FILE: tests/test_implementations/test_sqlalchemy/error_test/test_use_unsupported_type_pk_4.py ================================================ from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, text, PrimaryKeyConstraint from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, synonym from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods from src.fastapi_quickcrud.misc.exceptions import SchemaException, ColumnTypeNotSupportedException Base = declarative_base() class UntitledTable256(Base): primary_key_of_table = "primary_key" unique_fields = ['primary_key', 'int4_value', 'float4_value'] __tablename__ = 'test_build_myself_async' primary_key = Column(JSONB, primary_key = True, info={'alias_name': 'primary_key'}, autoincrement=True, server_default="nextval('test_build_myself_id_seq'::regclass)") bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False, unique=True) int4_value = Column(Integer, nullable=False, unique=True) int8_value = Column(BigInteger, server_default=text("99"), unique=True) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) except ColumnTypeNotSupportedException as e: 'not supported yet' in str(e) ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/__init__.py ================================================ ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test/__init__.py ================================================ import os from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR,Table, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = async_session() yield db finally: db.close() UntitledTable256 = Table( 'test_table', metadata, Column('primary_key', Integer, primary_key=True, nullable=False,autoincrement=True,info={'alias_name': 'primary_key'}), Column('bool_value', Boolean, nullable=False, server_default=text("false")), Column('bytea_value', LargeBinary), Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float, nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL), Column('json_value', JSON), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric), Column('text_value', Text), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('uuid_value', UUID), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), UniqueConstraint('primary_key', 'int4_value', 'float4_value'), ) UntitledTable256.create(engine, checkfirst=True) ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test/test_delete_many_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods from tests.test_implementations.test_sqlalchemy_table.api_test import get_transaction_session, app, UntitledTable256 test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, prefix="/test_creation_one", crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], tags=["test"] ) test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_creation_many", tags=["test"] ) test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, prefix="/test_post_direct_get", crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], tags=["test"] ) test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) test_delete_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.DELETE_MANY ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_delete_many", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_delete_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = 'primary_key' unique_fields = ['primary_key', 'int4_value', 'float4_value'] def test_create_many_and_delete_many(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) response = client.delete(f'/test_delete_many?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_create_many_and_delete_many_but_not_found(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '10:18:18', "time_value____to": '12:18:18', "time_value____list": '12:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "timez_value____from": '18:18:18+00:00', "timez_value____to": '18:18:18+00:00', "timez_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) response = client.delete(f'/test_delete_many?{query_string}') assert response.status_code == 204 ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test/test_delete_one_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods from tests.test_implementations.test_sqlalchemy_table.api_test import get_transaction_session, app, UntitledTable256 test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_creation_one", tags=["test"] ) test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_creation_many", tags=["test"] ) test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_post_direct_get", tags=["test"] ) test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) test_delete_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.DELETE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_delete_one", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_delete_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = 'primary_key' unique_fields = ['primary_key', 'int4_value', 'float4_value'] def test_create_one_and_delete_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False} response = client.delete(f'/test_delete_one/{primary_key}?{query_string}') response_data = response.json() assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_create_one_and_delete_one_but_not_found(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key ,= [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '10:18:18', "time_value____to": '12:18:18', "time_value____list": '10:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "timez_value____from": '18:18:18+00:00', "timez_value____to": '18:18:18+00:00', "timez_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False} response = client.delete(f'/test_delete_one/{primary_key}?{query_string}') assert response.status_code == 404 ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test/test_get_many_api.py ================================================ import json from collections import OrderedDict from urllib.parse import urlencode from starlette.testclient import TestClient from src.fastapi_quickcrud.misc.exceptions import UnknownColumn, UnknownOrderType from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods from src.fastapi_quickcrud.misc.utils import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy_table.api_test import get_transaction_session, app, UntitledTable256 test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_creation_many", tags=["test"] ) test_find_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.FIND_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_get_many", tags=["test"] ) [app.include_router(i) for i in [test_create_many, test_find_many]] client = TestClient(app) primary_key_name = 'primary_key' unique_fields = ['primary_key', 'int4_value', 'float4_value'] # test create many def create_example_data(num=1, **kwargs): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } insert_sample_item = {"bool_value": kwargs.get('bool_value', True), "char_value": kwargs.get('char_value', 'string'), "date_value": kwargs.get('date_value', "2021-07-23"), "float4_value": kwargs.get('float4_value', 0.6), "float8_value": kwargs.get('float8_value', 0.8), "int2_value": kwargs.get('int2_value', 11), "int4_value": kwargs.get('int4_value', 1), "int8_value": kwargs.get('int8_value', 3), "interval_value": kwargs.get('interval_value', 5), "json_value": kwargs.get('json_value', {}), "jsonb_value": kwargs.get('jsonb_value', {}), "numeric_value": kwargs.get('numeric_value', 110), "text_value": kwargs.get('text_value', 'string'), "timestamp_value": kwargs.get('timestamp_value', "2021-07-23T02:38:24.963Z"), "timestamptz_value": kwargs.get('timestamptz_value', "2021-07-23T02:38:24.963Z"), "uuid_value": kwargs.get('uuid_value', "3fa85f64-5717-4562-b3fc-2c963f66afa6"), "varchar_value": kwargs.get('varchar_value', 'string'), "array_value": kwargs.get('array_value', [1, 2, 3, 4]), "array_str__value": kwargs.get('array_str__value', ["string", "string1"])} data = {'insert': [insert_sample_item for i in range(num)]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 response_result = response.json() for i in response_result: assert primary_key_name in i assert i[primary_key_name] return response_result # test pagination by offset and limit and ordering def test_pagination_and_ording(): sample_data = create_example_data(5 * 10) assert len(sample_data) == 5 * 10 limit = 5 seem = [] for num in range(0, 5 * 10, 5): response = client.get( f'/test_get_many?limit={limit}&offset={num}&order_by_columns=primary_key%20%3A%20DESC%20') response.headers['x-total-count'] == limit assert response.status_code == 200 _ = response.json() for i in _: assert i not in seem seem.append(i) assert i in sample_data # test create a new data and get by primary key def test_create_new_data_and_get_by_primary_key(): sample_data = create_example_data(10) primary_key_list = [i[primary_key_name] for i in sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key} from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in response_data: assert i['primary_key'] in primary_key_list params = {"primary_key____from": min_key, "primary_key____to": max_key, "primary_key____from_____comparison_operator": 'Greater_than', "primary_key____to_____comparison_operator": 'Less_than'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 8 for i in response_data: assert i['primary_key'] in primary_key_list # test create a more than one data which value is TRUE of boolean type, and get many def test_create_a_more_than_one_data_which_value_is_TRUE_of_boolean_type_and_get_many(): bool_false_sample_data = create_example_data(5, bool_value=False) bool_true_sample_data = create_example_data(5, bool_value=True) primary_key_list = [i[primary_key_name] for i in bool_false_sample_data] + \ [i[primary_key_name] for i in bool_true_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "In", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) + f"&bool_value____list=False" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "In", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i not in response.json() for i in bool_true_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "In", "bool_value____list": False} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Equal", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) + f"&bool_value____list=False" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Equal", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i not in response.json() for i in bool_true_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Equal", "bool_value____list": False} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i not in response.json() # params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_in", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) + f"&bool_value____list=False" response = client.get(f'/test_get_many?{query_string}') assert response.status_code == 204 params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_in", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_in", "bool_value____list": False} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i not in response.json() for i in bool_true_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_equal", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) + f"&bool_value____list=False" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_equal", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_equal", "bool_value____list": False} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i not in response.json() for i in bool_true_sample_data: assert i in response.json() # test create a more than one data of char/text/varchar type, and get many def test_create_a_more_than_one_data_and_get_many_1(): char_str_sample_data = create_example_data(5, char_value='string') char_test_sample_data = create_example_data(5, char_value='test') primary_key_list = [i[primary_key_name] for i in char_str_sample_data] + \ [i[primary_key_name] for i in char_test_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) # match_regex_with_case_sensitive/ dose not match_regex_with_case_sensitive def match_regex_with_case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "char_value____str": 'str.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "char_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_match_regex_with_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "char_value____str": 'str.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "char_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "char_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "char_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "char_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "char_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def match_regex_with_case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "char_value____str": 'STR.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "char_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # does_not_match_regex_with_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "char_value____str": 'STR.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "char_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "char_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=STR.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "char_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=STR.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'case_sensitive', "char_value____str": 'string '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'case_sensitive', "char_value____str": 'test '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_sensitive', "char_value____str": 'string '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_sensitive', "char_value____str": 'test '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_sensitive', "char_value____str": 'test '} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=string " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_insensitive', "char_value____str": 'test '} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=string " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'case_insensitive', "char_value____str": 'STRING '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'case_insensitive', "char_value____str": 'TEST '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_insensitive', "char_value____str": 'STRING '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_insensitive', "char_value____str": 'TEST '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_insensitive', "char_value____str": 'TEST '} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=STRING " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_sensitive', "char_value____str": 'TEST '} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=STRING " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def similar_to(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'similar_to', "char_value____str": 'string%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'similar_to', "char_value____str": 'test%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_similar_to', "char_value____str": 'string%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_similar_to', "char_value____str": 'test%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'similar_to'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str%&char_value____str=_es%" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'similar_to'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str%&char_value____str=_es%" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() match_regex_with_case_sensitive() match_regex_with_case_insensitive() case_sensitive() case_insensitive() similar_to() # Varchar char_str_sample_data = create_example_data(5, varchar_value='string') char_test_sample_data = create_example_data(5, varchar_value='test') primary_key_list = [i[primary_key_name] for i in char_str_sample_data] + \ [i[primary_key_name] for i in char_test_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) # match_regex_with_case_sensitive/ dose not match_regex_with_case_sensitive def match_regex_with_case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "varchar_value____str": 'str.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "varchar_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_match_regex_with_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "varchar_value____str": 'str.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "varchar_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "varchar_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "varchar_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "varchar_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "varchar_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def match_regex_with_case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "varchar_value____str": 'STR.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "varchar_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # does_not_match_regex_with_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "varchar_value____str": 'STR.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "varchar_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "varchar_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=STR.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "varchar_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=STR.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_sensitive', "varchar_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_sensitive', "varchar_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_sensitive', "varchar_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=string " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_insensitive', "varchar_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=string " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'case_insensitive', "varchar_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'case_insensitive', "varchar_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_insensitive', "varchar_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_insensitive', "varchar_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_insensitive', "varchar_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_sensitive', "varchar_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def similar_to(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'similar_to', "varchar_value____str": 'string%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'similar_to', "varchar_value____str": 'test%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_similar_to', "varchar_value____str": 'string%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_similar_to', "varchar_value____str": 'test%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'similar_to'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str%&varchar_value____str=_es%" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'similar_to'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str%&varchar_value____str=_es%" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() match_regex_with_case_sensitive() match_regex_with_case_insensitive() case_sensitive() case_insensitive() similar_to() # Text char_str_sample_data = create_example_data(5, text_value='string') char_test_sample_data = create_example_data(5, text_value='test') primary_key_list = [i[primary_key_name] for i in char_str_sample_data] + \ [i[primary_key_name] for i in char_test_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) # match_regex_with_case_sensitive/ dose not match_regex_with_case_sensitive def match_regex_with_case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "text_value____str": 'str.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "text_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_match_regex_with_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "text_value____str": 'str.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "text_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "text_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "text_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "text_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "text_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def match_regex_with_case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "text_value____str": 'STR.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "text_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # does_not_match_regex_with_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "text_value____str": 'STR.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "text_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "text_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=STR.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "text_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=STR.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'case_sensitive', "text_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'case_sensitive', "text_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_sensitive', "text_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_sensitive', "text_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_sensitive', "text_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=string " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_insensitive', "text_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=string " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'case_insensitive', "text_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'case_insensitive', "text_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_insensitive', "text_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_insensitive', "text_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_insensitive', "text_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_sensitive', "text_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def similar_to(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'similar_to', "text_value____str": 'string%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'similar_to', "text_value____str": 'test%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_similar_to', "text_value____str": 'string%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_similar_to', "text_value____str": 'test%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'similar_to'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str%&text_value____str=_es%" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'similar_to'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str%&text_value____str=_es%" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() match_regex_with_case_sensitive() match_regex_with_case_insensitive() case_sensitive() case_insensitive() similar_to() # test create a more than one data of float4/text/varchar type, and get many def test_create_a_more_than_one_data_and_get_many_2(): float_one = 5.5 float_two = 10.7 # float 4 <= will round down to the odd floating even # data = 0.4 # <= 0.4 # result = [] # data = 0.4 # <= 0.5 # result = [0.4] num_one_sample_data = create_example_data(5, float4_value=float_one) num_two_sample_data = create_example_data(5, float4_value=float_two) primary_key_list = [i[primary_key_name] for i in num_one_sample_data] + \ [i[primary_key_name] for i in num_two_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) def greater_than_or_equal_to_Less_than_or_equal_to(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "float4_value____from_____comparison_operator": 'Greater_than_or_equal_to', "float4_value____to_____comparison_operator": 'Less_than_or_equal_to', "float4_value____from": float_one, "float4_value____to": float_two} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in num_one_sample_data: assert i in response.json() for i in num_two_sample_data: assert i in response.json() # data = 10.7 # < 10.7 # still got 10.7 but if data is 10.6 def less_than_or_equal_to_less_than(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "float4_value____from_____comparison_operator": 'Greater_than', "float4_value____to_____comparison_operator": 'Less_than', "float4_value____from": float_one, "float4_value____to": float_two + 0.1} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in num_one_sample_data: assert i not in response.json() for i in num_two_sample_data: assert i in response.json() greater_than_or_equal_to_Less_than_or_equal_to() less_than_or_equal_to_less_than() # float 4 < will round down to the odd floating odd # data = 0.3 # <= 0.4 # result = [] # data = 0.4 # <= 0.5 # result = [0.4] float_one = 5.5 float_two = 10.6 num_one_sample_data = create_example_data(5, float8_value=float_one) num_two_sample_data = create_example_data(5, float8_value=float_two) primary_key_list = [i[primary_key_name] for i in num_one_sample_data] + \ [i[primary_key_name] for i in num_two_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) def greater_than_or_equal_to_Less_than_or_equal_to(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "float8_value____from_____comparison_operator": 'Greater_than_or_equal_to', "float8_value____to_____comparison_operator": 'Less_than_or_equal_to', "float8_value____from": float_one, "float8_value____to": float_two} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in num_one_sample_data: assert i in response.json() for i in num_two_sample_data: assert i in response.json() def less_than_or_equal_to_less_than(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "float8_value____from_____comparison_operator": 'Greater_than', "float8_value____to_____comparison_operator": 'Less_than', "float8_value____from": float_one, "float8_value____to": float_two + 0.1} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in num_one_sample_data: assert i not in response.json() for i in num_two_sample_data: assert i in response.json() greater_than_or_equal_to_Less_than_or_equal_to() less_than_or_equal_to_less_than() def test_get_many_with_ordering_unknown_column(): try: response = client.get(f'/test_get_many?order_by_columns=testestset') except UnknownColumn as e: assert str(e) == "column testestset is not exited" return assert False def test_get_many_with_ordering_with_default_order(): response = client.get(f'/test_get_many?order_by_columns=primary_key&limit=10&offset=0') a = response.json() init = 0 for i in a: assert i['primary_key'] > init init = i['primary_key'] def test_get_many_with_ordering_with_ASC(): response = client.get(f'/test_get_many?order_by_columns=primary_key:ASC&limit=10&offset=0') a = response.json() init = 0 for i in a: assert i['primary_key'] > init init = i['primary_key'] def test_get_many_with_ordering_with_DESC(): response = client.get(f'/test_get_many?order_by_columns=primary_key:DESC&limit=10&offset=10') a = response.json() init = a[0]['primary_key'] for i in a: assert i['primary_key'] == init init -= 1 def test_get_many_with_unknown_order_tyoe(): try: response = client.get(f'/test_get_many?order_by_columns=primary_key:DESCSS&limit=10&offset=0') except UnknownOrderType as e: assert str(e) == 'Unknown order type DESCSS, only accept DESC or ASC' return assert False def test_get_many_with_ordering_with_empty_input_list(): try: response = client.get(f'/test_get_many?order_by_columns=') except Exception as e: assert False assert True ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test/test_get_one_api.py ================================================ import json from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods from tests.test_implementations.test_sqlalchemy_table.api_test import get_transaction_session, app, UntitledTable256 test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) [app.include_router(i) for i in [test_get_data, test_create_one]] client = TestClient(app) # create a sample data headers = { 'accept': '*/*', 'Content-Type': 'application/json', } data = '{ "bool_value": true, "char_value": "string", "date_value": "2021-07-26", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-26T02:17:46.846Z", "timestamptz_value": "2021-07-26T02:17:46.846Z", "timetz_value": "18:18:18+00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }' response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_data = response.json() dict_data = json.loads(data) sample_primary_key = response_data['primary_key'] ''' { "primary_key": 1013, "interval_value": 0, <- querying not supported "json_value": {},<- querying not supported "jsonb_value": {},<- querying not supported "array_value": [ 0 ], "array_str__value": [ "string" ] } ''' # try find the data by primary key def test_get_by_primary_key_without_any_query_param(): response = client.get(f'/test/{sample_primary_key}', headers=headers) assert response.status_code == 200 assert response.json()['primary_key'] == sample_primary_key # "bool_value": true # try find the data by primary key but false by bool def test_get_by_primary_key_with_false_bool_query_param(): response = client.get(f'/test/{sample_primary_key}?bool_value____list=false', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?bool_value____list=true', headers=headers) assert response.status_code == 200 # "char_value": "string ", # try find the data by primary key but false by char def test_get_by_primary_key_with_false_char_query_param(): response = client.get(f'/test/{sample_primary_key}?char_value____list=string1&char_value____list=string2', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?char_value____list=string&char_value____list=string1&', headers=headers) assert response.status_code == 200 # Like operator response = client.get( f'/test/{sample_primary_key}?char_value____str=string1&char_value____str=%tri%&char_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=string1&char_value____str=%tsri%&char_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 404 # Ilike operator response = client.get( f'/test/{sample_primary_key}?char_value____str=string1&char_value____str=%tRi%&char_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=string1&char_value____str=%tsri%&char_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 404 # not like operator response = client.get( f'/test/{sample_primary_key}?char_value____str=string2&char_value____str=%strg%&char_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=string%&char_value____str=%strin%&char_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 404 # not ilike operator response = client.get( f'/test/{sample_primary_key}?char_value____str=String2&char_value____str=%Strg%&char_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=STRING%&char_value____str=%TRI%&char_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 404 # match regex with case sensitive operator response = client.get( f'/test/{sample_primary_key}?char_value____str=stri.*&varchar_value____stg=str&char_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=stg.*&char_value____str=stg&char_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) assert response.status_code == 404 # match regex with case insensitive operator response = client.get( f'/test/{sample_primary_key}?char_value____str=strI.*&char_value____str=STG&char_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=stG.*&char_value____str=STG&char_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) assert response.status_code == 404 # does_not_match_regex_with_case_insensitive response = client.get( f'/test/{sample_primary_key}?char_value____str=strI.*&char_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?char_value____str=stG.*&char_value____str=STG&char_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) assert response.status_code == 200 # dose not match regex with case sensitive operator response = client.get( f'/test/{sample_primary_key}?char_value____str=stri.*&varchar_value____stg=str&char_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?char_value____str=stg.*&char_value____str=stg&char_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) assert response.status_code == 200 # similar_to response = client.get( f'/test/{sample_primary_key}?char_value____str=string&char_value____str=%(r|z)%&char_value____str_____matching_pattern=similar_to', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=str&char_value____str=(r|z)%&char_value____str_____matching_pattern=similar_to', headers=headers) assert response.status_code == 404 # not_similar_to response = client.get( f'/test/{sample_primary_key}?char_value____str=string%&char_value____str=%(r|z)%&char_value____str_____matching_pattern=not_similar_to', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?char_value____str=str&char_value____str=(r|z)%&char_value____str_____matching_pattern=not_similar_to', headers=headers) assert response.status_code == 200 # "float4_value": 0, # try find the data by primary key but false by float4 def test_get_by_primary_key_with_false_float4_query_param(): # from response = client.get(f'/test/{sample_primary_key}?float4_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?float4_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??float4_value____from=-2&float4_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?float4_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?float4_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?float4_value____from=0&float4_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?float4_value____from=0&float4_value____to=0&float4_value____from_____comparison_operator=Greater_than_or_equal_to&float4_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?float4_value____from=-1&float4_value____to=2&float4_value____from_____comparison_operator=Greater_than&float4_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?float4_value____from=1&float4_value____to=2&float4_value____from_____comparison_operator=Greater_than&float4_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?float4_value____from=1&float4_value____to=2&float4_value____from_____comparison_operator=Greater_than_or_equal_to&float4_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # "float8_value": 0, # try find the data by primary key but false by float8 def test_get_by_primary_key_with_false_float8_query_param(): # from response = client.get(f'/test/{sample_primary_key}?float8_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?float8_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??float8_value____from=-2&float8_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?float8_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?float8_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?float8_value____from=0&float8_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?float8_value____from=0&float8_value____to=0&float8_value____from_____comparison_operator=Greater_than_or_equal_to&float8_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?float8_value____from=-1&float8_value____to=2&float8_value____from_____comparison_operator=Greater_than&float8_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?float8_value____from=1&float8_value____to=2&float8_value____from_____comparison_operator=Greater_than&float8_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?float8_value____from=1&float8_value____to=2&float8_value____from_____comparison_operator=Greater_than_or_equal_to&float8_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by int2 # int2 0 def test_get_by_primary_key_with_false_int2_query_param(): # from response = client.get(f'/test/{sample_primary_key}?int2_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?int2_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??int2_value____from=-2&int2_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?int2_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?int2_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?int2_value____from=0&int2_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int2_value____from=0&int2_value____to=0&int2_value____from_____comparison_operator=Greater_than_or_equal_to&int2_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int2_value____from=-1&int2_value____to=2&int2_value____from_____comparison_operator=Greater_than&int2_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int2_value____from=1&int2_value____to=2&int2_value____from_____comparison_operator=Greater_than&int2_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int2_value____from=1&int2_value____to=2&int2_value____from_____comparison_operator=Greater_than_or_equal_to&int2_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by int4 # int 4 0 def test_get_by_primary_key_with_false_int4_query_param(): # from response = client.get(f'/test/{sample_primary_key}?int4_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?int4_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??int4_value____from=-2&int4_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?int4_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?int4_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?int4_value____from=0&int4_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int4_value____from=0&int4_value____to=0&int4_value____from_____comparison_operator=Greater_than_or_equal_to&int4_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int4_value____from=-1&int4_value____to=2&int4_value____from_____comparison_operator=Greater_than&int4_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int4_value____from=1&int4_value____to=2&int4_value____from_____comparison_operator=Greater_than&int4_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int4_value____from=1&int4_value____to=2&int4_value____from_____comparison_operator=Greater_than_or_equal_to&int4_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by int8 # int 8 0 def test_get_by_primary_key_with_false_int8_query_param(): # from response = client.get(f'/test/{sample_primary_key}?int8_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?int8_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??int8_value____from=-2&int8_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?int8_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?int8_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?int8_value____from=0&int8_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int8_value____from=0&int8_value____to=0&int8_value____from_____comparison_operator=Greater_than_or_equal_to&int8_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int8_value____from=-1&int8_value____to=2&int8_value____from_____comparison_operator=Greater_than&int8_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int8_value____from=1&int8_value____to=2&int8_value____from_____comparison_operator=Greater_than&int8_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int8_value____from=1&int8_value____to=2&int8_value____from_____comparison_operator=Greater_than_or_equal_to&int8_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by numeric # numeric 0 def test_get_by_primary_key_with_false_numeric_query_param(): # from response = client.get(f'/test/{sample_primary_key}?numeric_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?numeric_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??numeric_value____from=-2&numeric_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?numeric_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?numeric_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?numeric_value____from=0&numeric_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?numeric_value____from=0&numeric_value____to=0&numeric_value____from_____comparison_operator=Greater_than_or_equal_to&numeric_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?numeric_value____from=-1&numeric_value____to=2&numeric_value____from_____comparison_operator=Greater_than&numeric_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?numeric_value____from=1&numeric_value____to=2&numeric_value____from_____comparison_operator=Greater_than&numeric_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?numeric_value____from=1&numeric_value____to=2&numeric_value____from_____comparison_operator=Greater_than_or_equal_to&numeric_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by text # "text_value": "string", def test_get_by_primary_key_with_false_text_query_param(): response = client.get(f'/test/{sample_primary_key}?text_value____list=string1&text_value____list=string2', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?text_value____list=string&text_value____list=string1&', headers=headers) assert response.status_code == 200 # Like operator response = client.get( f'/test/{sample_primary_key}?text_value____str=string1&text_value____str=%tri%&text_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?text_value____str=string1&text_value____str=%tsri%&text_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 404 # Ilike operator response = client.get( f'/test/{sample_primary_key}?text_value____str=string1&text_value____str=%tRi%&text_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?text_value____str=string1&text_value____str=%tsri%&text_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 404 # not like operator response = client.get( f'/test/{sample_primary_key}?text_value____str=string2&text_value____str=%strg%&text_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?text_value____str=string&text_value____str=%strin%&text_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 404 # not ilike operator response = client.get( f'/test/{sample_primary_key}?text_value____str=String2&text_value____str=%Strg%&text_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?text_value____str=STRING&text_value____str=%TRI%&text_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 404 # match regex with case sensitive operator response = client.get( f'/test/{sample_primary_key}?text_value____str=stri.*&varchar_value____stg=str&text_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?text_value____str=stg.*&text_value____str=stg&text_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) assert response.status_code == 404 # match regex with case insensitive operator response = client.get( f'/test/{sample_primary_key}?text_value____str=strI.*&text_value____str=STG&text_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?text_value____str=stG.*&text_value____str=STG&text_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) assert response.status_code == 404 # does_not_match_regex_with_case_insensitive response = client.get( f'/test/{sample_primary_key}?text_value____str=strI.*&text_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?text_value____str=stG.*&text_value____str=STG&text_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) assert response.status_code == 200 # dose not match regex with case sensitive operator response = client.get( f'/test/{sample_primary_key}?text_value____str=stri.*&varchar_value____stg=str&text_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?text_value____str=stg.*&text_value____str=stg&text_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) assert response.status_code == 200 # similar_to response = client.get( f'/test/{sample_primary_key}?text_value____str=string&text_value____str=%(r|z)%&text_value____str_____matching_pattern=similar_to', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?text_value____str=str&text_value____str=(r|z)%&text_value____str_____matching_pattern=similar_to', headers=headers) assert response.status_code == 404 # not_similar_to response = client.get( f'/test/{sample_primary_key}?text_value____str=string&text_value____str=%(r|z)%&text_value____str_____matching_pattern=not_similar_to', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?text_value____str=str&text_value____str=(r|z)%&text_value____str_____matching_pattern=not_similar_to', headers=headers) assert response.status_code == 200 # try find the data by primary key but false by uuid def test_get_by_primary_key_with_false_uuid_query_param(): # In operator response = client.get( f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa6&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afb6', headers=headers) assert response.status_code == 404 # not In operator response = client.get( f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa6&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list_____comparison_operator=Not_in', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afb6&uuid_value____list_____comparison_operator=Not_in', headers=headers) assert response.status_code == 200 # Equal operator response = client.get( f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa6&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list_____comparison_operator=Equal', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afb6&uuid_value____list_____comparison_operator=Equal', headers=headers) assert response.status_code == 404 # not Equal operator response = client.get( f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa6&uuid_value____list_____comparison_operator=Not_equal', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afb6&uuid_value____list_____comparison_operator=Not_equal', headers=headers) assert response.status_code == 200 # try find the data by primary key but false by varchar def test_get_by_primary_key_with_false_varchar_query_param(): response = client.get(f'/test/{sample_primary_key}?varchar_value____list=string1&varchar_value____list=string2', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?varchar_value____list=string&varchar_value____list=string1&', headers=headers) assert response.status_code == 200 # Like operator response = client.get( f'/test/{sample_primary_key}?varchar_value____str=string1&varchar_value____str=%tri%&varchar_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?varchar_value____str=string1&varchar_value____str=%tsri%&varchar_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 404 # Ilike operator response = client.get( f'/test/{sample_primary_key}?varchar_value____str=string1&varchar_value____str=%tRi%&varchar_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?varchar_value____str=string1&varchar_value____str=%tsri%&varchar_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 404 # not like operator response = client.get( f'/test/{sample_primary_key}?varchar_value____str=string2&varchar_value____str=%strg%&varchar_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?varchar_value____str=string&varchar_value____str=%strin%&varchar_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 404 # not ilike operator response = client.get( f'/test/{sample_primary_key}?varchar_value____str=String2&varchar_value____str=%Strg%&varchar_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?varchar_value____str=STRING&varchar_value____str=%TRI%&varchar_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 404 # match regex with case sensitive operator response = client.get( f'/test/{sample_primary_key}?varchar_value____str=stri.*&varchar_value____stg=str&varchar_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?varchar_value____str=stg.*&varchar_value____str=stg&varchar_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) assert response.status_code == 404 # match regex with case insensitive operator response = client.get( f'/test/{sample_primary_key}?varchar_value____str=strI.*&varchar_value____str=STG&varchar_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?varchar_value____str=stG.*&varchar_value____str=STG&varchar_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) assert response.status_code == 404 # does_not_match_regex_with_case_insensitive response = client.get( f'/test/{sample_primary_key}?varchar_value____str=strI.*&varchar_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?varchar_value____str=stG.*&varchar_value____str=STG&varchar_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) assert response.status_code == 200 # dose not match regex with case sensitive operator response = client.get( f'/test/{sample_primary_key}?varchar_value____str=stri.*&varchar_value____stg=str&varchar_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?varchar_value____str=stg.*&varchar_value____str=stg&varchar_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) assert response.status_code == 200 # similar_to response = client.get( f'/test/{sample_primary_key}?varchar_value____str=string&varchar_value____str=%(r|z)%&varchar_value____str_____matching_pattern=similar_to', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?varchar_value____str=str&varchar_value____str=(r|z)%&varchar_value____str_____matching_pattern=similar_to', headers=headers) assert response.status_code == 404 # not_similar_to response = client.get( f'/test/{sample_primary_key}?varchar_value____str=string&varchar_value____str=%(r|z)%&varchar_value____str_____matching_pattern=not_similar_to', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?varchar_value____str=str&varchar_value____str=(r|z)%&varchar_value____str_____matching_pattern=not_similar_to', headers=headers) assert response.status_code == 200 # query by range of date field def test_get_by_primary_key_with_false_date_range_query_param(): # from response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-27', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?date_value____to=2021-07-24', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??date_value____from=2021-07-21&date_value____to=2021-07-24', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-24', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?date_value____to=2021-07-27', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-24&date_value____to=2021-07-27', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?date_value____from=2021-07-26&date_value____to=2021-07-26&date_value____from_____comparison_operator=Greater_than_or_equal_to&date_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?date_value____from=2021-07-25&date_value____to=2021-07-27&date_value____from_____comparison_operator=Greater_than&date_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?date_value____from=2021-07-26&date_value____to=2021-07-26&date_value____from_____comparison_operator=Greater_than&date_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?date_value____from=2021-07-27&date_value____to=2021-07-29&date_value____from_____comparison_operator=Greater_than_or_equal_to&date_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 def test_get_by_primary_key_with_false_time_range_query_param(): # from response = client.get(f'/test/{sample_primary_key}?time_value____from=19:18:18', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?time_value____to=17:18:18', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}?time_value____from=10:18:18&time_value____to=17:18:18', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?time_value____from=10:18:18', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?time_value____to=19:18:18', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?time_value____from=10:18:18&time_value____to=19:18:18', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?time_value____from=18:18:18&time_value____to=18:18:18&time_value____from_____comparison_operator=Greater_than_or_equal_to&time_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?time_value____from=18:18:17&time_value____to=18:18:19&time_value____from_____comparison_operator=Greater_than&time_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?time_value____from=18:18:18&time_value____to=18:18:18&time_value____from_____comparison_operator=Greater_than&time_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?time_value____from=19:18:18&time_value____to=19:19:18&time_value____from_____comparison_operator=Greater_than_or_equal_to&time_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 def test_get_by_primary_key_with_false_timestamp_range_query_param(): # "timestamp_value": "2021-07-26T02:17:46.846000", # from response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-27T02:17:46.846000', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?timestamp_value____to=2021-07-25T02:17:46.846000', headers=headers) assert response.status_code == 404 # from - to response = client.get( f'/test/{sample_primary_key}?timestamp_value____from=2021-07-20T02:17:46.846000×tamp_value____to=2021-07-25T02:17:46.846000', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-24T02:17:46.846000', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?timestamp_value____to=2021-07-28T02:17:46.846000', headers=headers) assert response.status_code == 200 # success from - to response = client.get( f'/test/{sample_primary_key}?timestamp_value____from=2021-07-24T02:17:46.846000×tamp_value____to=2021-07-28T02:17:46.846000', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?timestamp_value____from=2021-07-26T02:17:46.846×tamp_value____to=2021-07-26T02:17:46.846Z×tampt_value____from_____comparison_operator=Greater_than_or_equal_to×tampt_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?timestamp_value____from=2021-07-26T02:17:46.746Z×tamp_value____to=2021-07-26T02:17:46.946Z×tampt_value____from_____comparison_operator=Greater_than×tampt_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?timestamp_value____from=2021-07-26T02:17:46.846Z×tamp_value____to=2021-07-26T02:17:46.946Z×tamp_value____from_____comparison_operator=Greater_than×tamp_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?timestamp_value____from=2021-07-26T02:17:46.856Z×tamp_value____to=2021-07-26T02:17:46.986Z×tamp_value____from_____comparison_operator=Greater_than_or_equal_to×tamp_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 def test_get_by_primary_key_with_false_timetz_range_query_param(): # from response = client.get(f'/test/{sample_primary_key}?timetz_value____from=19%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?timetz_value____to=17%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 404 # from - to response = client.get( f'/test/{sample_primary_key}?timetz_value____from=16%3A18%3A18%2B00%3A00&timetz_value____to=17%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?timetz_value____from=17%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?timetz_value____to=19%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 200 # success from - to response = client.get( f'/test/{sample_primary_key}?timetz_value____from=16%3A18%3A18%2B00%3A00&timetz_value____to=19%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?timetz_value____from_____comparison_operator=Greater_than&timetz_value____to_____comparison_operator=Less_than&timetz_value____from=17%3A18%3A18%2B00&timetz_value____to=19%3A18%3A18%2B00', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?timetz_value____from_____comparison_operator=Greater_than_or_equal_to&timetz_value____to_____comparison_operator=Less_than_or_equal_to&timetz_value____from=18%3A18%3A18%2B00&timetz_value____to=18%3A19%3A18%2B00', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?timetz_value____from_____comparison_operator=Greater_than&timetz_value____to_____comparison_operator=Less_than&timetz_value____from=16%3A18%3A18%2B00&timetz_value____to=18%3A18%3A18%2B00', headers=headers) assert response.status_code == 404 # failure from - to with special operator response = client.get( f'/test/{sample_primary_key}?timetz_value____from_____comparison_operator=Greater_than_or_equal_to&timetz_value____to_____comparison_operator=Less_than_or_equal_to&timetz_value____from=16%3A18%3A18%2B00&timetz_value____to=17%3A19%3A18%2B00', headers=headers) assert response.status_code == 404 def test_get_by_primary_key_with_false_timestamptz_range_query_param(): # "timestamp_value": "2021-07-26T02:17:46.846000", # from response = client.get( f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-27T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 404 # to response = client.get( f'/test/{sample_primary_key}?timestamptz_value____to=2021-07-25T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 404 # from - to response = client.get( f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-27T02%3A17%3A46.846000%2B00%3A00×tamptz_value____to=2021-07-28T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 404 # success from response = client.get( f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-20T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 200 # success to response = client.get( f'/test/{sample_primary_key}?timestamptz_value____to=2021-07-29T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 200 # success from - to response = client.get( f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-20T02%3A17%3A46.846000%2B00%3A00×tamptz_value____to=2021-07-27T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-26T02%3A17%3A46.846Z×tamptz_value____to=2021-07-26T02%3A17%3A46.846Z×tamptz_value____from_____comparison_operator=Greater_than_or_equal_to×tamptz_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-26T02%3A17%3A46.800Z×tamptz_value____to=2021-07-26T02%3A17%3A46.946Z×tamptz_value____from_____comparison_operator=Greater_than×tamptz_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-26T02%3A17%3A46.846Z×tamptz_value____to=2021-07-26T02%3A17%3A46.900Z×tamptz_value____from_____comparison_operator=Greater_than×tamptz_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-26T02%3A17%3A46.847Z×tamptz_value____to=2021-07-26T02%3A17%3A46.946Z×tamptz_value____from_____comparison_operator=Greater_than_or_equal_to×tamptz_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test/test_other_no_alias.py ================================================ import json import os from copy import deepcopy from datetime import datetime, timezone, date, timedelta from http import HTTPStatus from urllib.parse import urlencode from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, Table, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = async_session() yield db finally: db.close() UUIDTable = Table( 'test_no_alias', metadata, Column('id', UUID, primary_key=True, server_default=text("uuid_generate_v4()")), Column('bool_value', Boolean, nullable=False, server_default=text("false")), Column('bytea_value', LargeBinary), Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float(53), nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL), Column('json_value', JSON), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric), Column('text_value', Text), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), UniqueConstraint('id', 'int4_value', 'float4_value') ) UUIDTable.create(engine, checkfirst=True) route_1 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.FIND_MANY, CrudMethods.UPSERT_MANY, CrudMethods.UPDATE_ONE, CrudMethods.UPDATE_MANY, CrudMethods.PATCH_MANY, CrudMethods.PATCH_ONE, CrudMethods.DELETE_MANY, CrudMethods.DELETE_ONE, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) route_2 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.UPSERT_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_2", tags=["test"] ) route_3 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_3", tags=["test"] ) [app.include_router(i) for i in [route_1, route_2, route_3]] client = TestClient(app) def test_get_one_data_and_create_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() find_target = create_response['id'] response = client.get(f'/test/{find_target}', headers=headers, data=data) assert response.status_code == 200 assert response.json() == create_response create_response.pop('id') query_param = urlencode(create_response) response = client.get(f'/test/{find_target}?{query_param}', headers=headers, data=data) assert response.status_code == 200 def test_get_many_data_and_create_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '''{ "insert": [ { "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00","varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }, { "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] },{ "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] } ] }''' data_dict = json.loads(data)['insert'] response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_dict): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_update_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() created_primary_key = create_response['id'] update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} query_param = urlencode(update_data) response = client.put(f'/test/{created_primary_key}?{query_param}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_update_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['id'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&id____list={primary_key_list[0]}&id____list={primary_key_list[1]}&id____list={primary_key_list[2]}' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: assert k[i] == update_data[i] def test_patch_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['id'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) update_data = {"bool_value": False} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(params) update_data = {"char_value": "string_u "} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(params) update_data = {"date_value": "2022-07-24"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(params) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_patch_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['id'] for i in insert_response_data] params = { "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&id____list={primary_key_list[0]}&id____list={primary_key_list[1]}&id____list={primary_key_list[2]}' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_delete_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['id'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) response = client.delete(f'/test/{primary_key}?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_delete_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['id'] for i in insert_response_data] params = { "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&id____list={primary_key_list[0]}&id____list={primary_key_list[1]}&id____list={primary_key_list[2]}' response = client.delete(f'/test?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_post_redirect_get_data(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} bool_value_change = False char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_3', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() assert 'id' in response_data for k, v in response_data.items(): if k in change: if isinstance(v, str): v = v.strip() response_ = json.dumps(v).strip() request_ = json.dumps(change[k]).strip() assert request_ == response_ return response_data def test_upsert_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 10 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k, v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 # conflict upsert_data = deepcopy(updated_data) upsert_data['on_conflict'] = {'update_columns': ['numeric_value']} response = client.post('/test_2', headers=headers, data=json.dumps(dict(upsert_data, **json.loads(data)))) assert response.status_code == 201 # create response = client.post('/test_2', headers=headers, data=json.dumps(dict(updated_data, **json.loads(data)))) assert response.status_code == 409 ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test/test_other_set_description.py ================================================ import json import os from copy import deepcopy from datetime import datetime, timezone, date, timedelta from http import HTTPStatus from urllib.parse import urlencode from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, Table, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = async_session() yield db finally: db.close() UUIDTable = Table( 'test_default_value', metadata, Column('primary_key', UUID, primary_key=True, server_default=text("uuid_generate_v4()"), comment='this is a primary_key'), Column('bool_value', Boolean, nullable=False, default=False), Column('bytea_value', LargeBinary), Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float(53), nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL), Column('json_value', JSON), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric), Column('text_value', Text), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), UniqueConstraint('primary_key', 'int4_value', 'float4_value') ) UUIDTable.create(engine, checkfirst=True) route_1 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.FIND_MANY, CrudMethods.UPSERT_MANY, CrudMethods.UPDATE_ONE, CrudMethods.UPDATE_MANY, CrudMethods.PATCH_MANY, CrudMethods.PATCH_ONE, CrudMethods.DELETE_MANY, CrudMethods.DELETE_ONE, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) route_2 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.UPSERT_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_2", tags=["test"] ) route_3 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_3", tags=["test"] ) [app.include_router(i) for i in [route_1, route_2, route_3]] client = TestClient(app) def test_get_one_data_and_create_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() find_target = create_response['primary_key'] response = client.get(f'/test/{find_target}', headers=headers, data=data) assert response.status_code == 200 assert response.json() == create_response create_response.pop('primary_key') query_param = urlencode(create_response) response = client.get(f'/test/{find_target}?{query_param}', headers=headers, data=data) assert response.status_code == 200 def test_get_many_data_and_create_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '''{ "insert": [ { "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00","varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }, { "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] },{ "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] } ] }''' data_dict = json.loads(data)['insert'] response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_dict): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_update_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() created_primary_key = create_response['primary_key'] update_data = { "bool_value":False,"char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} query_param = urlencode(update_data) response = client.put(f'/test/{created_primary_key}?{query_param}', data=json.dumps(update_data)) update_data["bool_value"] = False response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_update_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, { "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params)+f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value":False,"char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test?{query_string}', data=json.dumps(update_data)) update_data["bool_value"] = False response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: assert k[i] == update_data[i] def test_patch_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) update_data = {"bool_value": False} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(params) update_data = {"char_value": "string_u "} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(params) update_data = {"date_value": "2022-07-24"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(params) update_data = {"char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) update_data['bool_value'] = False response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_patch_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, { "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value": True, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00","varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test?{query_string}', data=json.dumps(update_data)) update_data['bool_value'] = True response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_delete_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) response = client.delete(f'/test/{primary_key}?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_delete_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{ "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, { "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, { "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' response = client.delete(f'/test?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_post_redirect_get_data(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_3', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() response_data['bool_value'] = False assert 'primary_key' in response_data for k, v in response_data.items(): if k in change: if isinstance(v, str): v = v.strip() response_ = json.dumps(v).strip() request_ = json.dumps(change[k]).strip() assert request_ == response_ return response_data def test_upsert_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 10 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k,v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 # conflict upsert_data = deepcopy(updated_data) upsert_data['on_conflict'] = {'update_columns':['numeric_value']} response = client.post('/test_2', headers=headers, data=json.dumps(dict(upsert_data, **json.loads(data)))) assert response.status_code == 201 # create response = client.post('/test_2', headers=headers, data=json.dumps(dict(updated_data, **json.loads(data)))) assert response.status_code == 409 def test_upsert_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 12.784 ,"int2_value": 0, "int4_value": 10 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k,v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 # conflict upsert_data = deepcopy(updated_data) upsert_data['on_conflict'] = {'update_columns':['numeric_value']} response = client.post('/test_2', headers=headers, data=json.dumps(dict(upsert_data, **json.loads(data)))) assert response.status_code == 201 # create response = client.post('/test_2', headers=headers, data=json.dumps(dict(updated_data, **json.loads(data)))) assert response.status_code == 409 ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test/test_other_single_unique.py ================================================ import json import os from copy import deepcopy from datetime import datetime, timezone, date, timedelta from http import HTTPStatus from urllib.parse import urlencode from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Table, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = async_session() yield db finally: db.close() UUIDTable = Table( 'test_single_unique_table', metadata, Column('id', UUID, primary_key=True, server_default=text("uuid_generate_v4()")), Column('bool_value', Boolean, nullable=False, server_default=text("false")), Column('bytea_value', LargeBinary), Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float(53), nullable=False, unique=True), Column('float8_value', Float(53), nullable=True, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=True), Column('int4_value', Integer, nullable=True), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL), Column('json_value', JSON), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric), Column('text_value', Text), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), ) UUIDTable.create(engine, checkfirst=True) route_1 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.FIND_MANY, CrudMethods.UPSERT_MANY, CrudMethods.UPDATE_ONE, CrudMethods.UPDATE_MANY, CrudMethods.PATCH_MANY, CrudMethods.PATCH_ONE, CrudMethods.DELETE_MANY, CrudMethods.DELETE_ONE, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) route_2 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.UPSERT_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'] , prefix="/test_2", tags=["test"] ) route_3 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_3", tags=["test"] ) [app.include_router(i) for i in [route_1, route_2, route_3]] client = TestClient(app) def test_get_one_data_and_create_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0.443}' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() find_target = create_response['id'] response = client.get(f'/test/{find_target}', headers=headers, data=data) assert response.status_code == 200 assert response.json() == create_response create_response.pop('id') query_param = urlencode(create_response) response = client.get(f'/test/{find_target}?{query_param}', headers=headers, data=data) assert response.status_code == 200 def test_get_many_data_and_create_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '''{ "insert": [ { "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0.12, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00","varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }, { "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 1.2, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] },{ "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 9.3, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] } ] }''' data_dict = json.loads(data)['insert'] response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_dict): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_update_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0.98}' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() created_primary_key = create_response['id'] update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 12.7, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} query_param = urlencode(update_data) response = client.put(f'/test/{created_primary_key}?{query_param}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_update_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 3.5, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 3.6, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 3.7, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['id'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 200, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&id____list={primary_key_list[0]}&id____list={primary_key_list[1]}&id____list={primary_key_list[2]}&float4_value____list=3.5&float4_value____list=3.6&float4_value____list=3.7' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.58, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test?{query_string}', data=json.dumps(update_data)) # FIXME: update the unique column will conflict, it may not a issue, because it should input all columns, you can use the patch assert response.status_code == 409 # response_data = response.json() # assert len(response_data) == 3 # for k in response_data: # for i in update_data: # assert k[i] == update_data[i] def test_patch_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 5.78, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['id'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 500, "float4_value____list": 5.78, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) update_data = {"bool_value": False} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(params) update_data = {"char_value": "string_u "} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(params) update_data = {"date_value": "2022-07-24"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(params) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 1.70, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_patch_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.91, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.92, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.93, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['id'] for i in insert_response_data] params = { "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 500, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&id____list={primary_key_list[0]}&id____list={primary_key_list[1]}&id____list={primary_key_list[2]}&float4_value____list=0.91&float4_value____list=0.92&float4_value____list=0.93' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_delete_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 2.54, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['id'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 500, "float4_value____list": 2.54, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) response = client.delete(f'/test/{primary_key}?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_delete_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.875, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.876, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.877, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['id'] for i in insert_response_data] params = { "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 500, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&id____list={primary_key_list[0]}&id____list={primary_key_list[1]}&id____list={primary_key_list[2]}&float4_value____list=0.875&float4_value____list=0.876&&float4_value____list=0.877' response = client.delete(f'/test?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_post_redirect_get_data(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} bool_value_change = False char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 55.7 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_3', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() assert 'id' in response_data for k, v in response_data.items(): if k in change: if isinstance(v, str): v = v.strip() response_ = json.dumps(v).strip() request_ = json.dumps(change[k]).strip() assert request_ == response_ return response_data def test_upsert_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 12.784}' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k, v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 # conflict upsert_data = deepcopy(updated_data) upsert_data['on_conflict'] = {'update_columns': ['numeric_value']} response = client.post('/test_2', headers=headers, data=json.dumps(dict(upsert_data, **json.loads(data)))) assert response.status_code == 201 # create response = client.post('/test_2', headers=headers, data=json.dumps(dict(updated_data, **json.loads(data)))) assert response.status_code == 409 def teardown_module(module): UUIDTable.drop(engine, checkfirst=True) ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test/test_other_user_default_value.py ================================================ import json import os from copy import deepcopy from datetime import datetime, timezone, date, timedelta from http import HTTPStatus from urllib.parse import urlencode from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, Table, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = async_session() yield db finally: db.close() UUIDTable = Table( 'test_default_value', metadata, Column('primary_key', UUID, primary_key=True, server_default=text("uuid_generate_v4()")), Column('bool_value', Boolean, nullable=False, default=False), Column('bytea_value', LargeBinary), Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float(53), nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL), Column('json_value', JSON), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric), Column('text_value', Text), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), UniqueConstraint('primary_key', 'int4_value', 'float4_value') ) UUIDTable.create(engine, checkfirst=True) route_1 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.FIND_MANY, CrudMethods.UPSERT_MANY, CrudMethods.UPDATE_ONE, CrudMethods.UPDATE_MANY, CrudMethods.PATCH_MANY, CrudMethods.PATCH_ONE, CrudMethods.DELETE_MANY, CrudMethods.DELETE_ONE, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) route_2 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.UPSERT_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_2", tags=["test"] ) route_3 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_3", tags=["test"] ) [app.include_router(i) for i in [route_1, route_2, route_3]] client = TestClient(app) def test_get_one_data_and_create_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() find_target = create_response['primary_key'] response = client.get(f'/test/{find_target}', headers=headers, data=data) assert response.status_code == 200 assert response.json() == create_response create_response.pop('primary_key') query_param = urlencode(create_response) response = client.get(f'/test/{find_target}?{query_param}', headers=headers, data=data) assert response.status_code == 200 def test_get_many_data_and_create_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '''{ "insert": [ { "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00","varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }, { "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] },{ "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] } ] }''' data_dict = json.loads(data)['insert'] response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_dict): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_update_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() created_primary_key = create_response['primary_key'] update_data = { "bool_value":False,"char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} query_param = urlencode(update_data) response = client.put(f'/test/{created_primary_key}?{query_param}', data=json.dumps(update_data)) update_data["bool_value"] = False response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_update_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, { "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params)+f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value":False,"char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test?{query_string}', data=json.dumps(update_data)) update_data["bool_value"] = False response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: assert k[i] == update_data[i] def test_patch_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) update_data = {"bool_value": False} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(params) update_data = {"char_value": "string_u "} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(params) update_data = {"date_value": "2022-07-24"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(params) update_data = {"char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) update_data['bool_value'] = False response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_patch_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, { "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value": True, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00","varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test?{query_string}', data=json.dumps(update_data)) update_data['bool_value'] = True response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_delete_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) response = client.delete(f'/test/{primary_key}?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_delete_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{ "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, { "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, { "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' response = client.delete(f'/test?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_post_redirect_get_data(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_3', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() response_data['bool_value'] = False assert 'primary_key' in response_data for k, v in response_data.items(): if k in change: if isinstance(v, str): v = v.strip() response_ = json.dumps(v).strip() request_ = json.dumps(change[k]).strip() assert request_ == response_ return response_data def test_upsert_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 10 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k,v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 # conflict upsert_data = deepcopy(updated_data) upsert_data['on_conflict'] = {'update_columns':['numeric_value']} response = client.post('/test_2', headers=headers, data=json.dumps(dict(upsert_data, **json.loads(data)))) assert response.status_code == 201 # create response = client.post('/test_2', headers=headers, data=json.dumps(dict(updated_data, **json.loads(data)))) assert response.status_code == 409 def test_upsert_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 12.784 ,"int2_value": 0, "int4_value": 10 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k,v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 # conflict upsert_data = deepcopy(updated_data) upsert_data['on_conflict'] = {'update_columns':['numeric_value']} response = client.post('/test_2', headers=headers, data=json.dumps(dict(upsert_data, **json.loads(data)))) assert response.status_code == 201 # create response = client.post('/test_2', headers=headers, data=json.dumps(dict(updated_data, **json.loads(data)))) assert response.status_code == 409 ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test/test_other_uuid_primary.py ================================================ import json import os from copy import deepcopy from datetime import datetime, timezone, date, timedelta from http import HTTPStatus from urllib.parse import urlencode from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Table, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = async_session() yield db finally: db.close() UUIDTable = Table( 'test_uuid_primary', metadata, Column('primary_key', UUID, primary_key=True, server_default=text("uuid_generate_v4()")), Column('bool_value', Boolean, nullable=False, server_default=text("false")), Column('bytea_value', LargeBinary), Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float(53), nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL), Column('json_value', JSON), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric), Column('text_value', Text), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), UniqueConstraint('primary_key', 'int4_value', 'float4_value') ) def setup_module(module): UUIDTable.create(engine, checkfirst=True) route_1 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.FIND_MANY, CrudMethods.UPSERT_MANY, CrudMethods.UPDATE_ONE, CrudMethods.UPDATE_MANY, CrudMethods.PATCH_MANY, CrudMethods.PATCH_ONE, CrudMethods.DELETE_MANY, CrudMethods.DELETE_ONE, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) route_2 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.UPSERT_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_2", tags=["test"] ) route_3 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_3", tags=["test"] ) [app.include_router(i) for i in [route_1, route_2, route_3]] client = TestClient(app) def test_get_one_data_and_create_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() find_target = create_response['primary_key'] response = client.get(f'/test/{find_target}', headers=headers, data=data) assert response.status_code == 200 assert response.json() == create_response create_response.pop('primary_key') query_param = urlencode(create_response) response = client.get(f'/test/{find_target}?{query_param}', headers=headers, data=data) assert response.status_code == 200 def test_get_many_data_and_create_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '''{ "insert": [ { "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00","varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }, { "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] },{ "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] } ] }''' data_dict = json.loads(data)['insert'] response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_dict): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_update_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() created_primary_key = create_response['primary_key'] update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} query_param = urlencode(update_data) response = client.put(f'/test/{created_primary_key}?{query_param}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_update_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: assert k[i] == update_data[i] def test_patch_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) update_data = {"bool_value": False} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(params) update_data = {"char_value": "string_u "} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(params) update_data = {"date_value": "2022-07-24"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(params) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_patch_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_delete_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) response = client.delete(f'/test/{primary_key}?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_delete_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' response = client.delete(f'/test?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_post_redirect_get_data(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} bool_value_change = False char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_3', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() assert 'primary_key' in response_data for k, v in response_data.items(): if k in change: if isinstance(v, str): v = v.strip() response_ = json.dumps(v).strip() request_ = json.dumps(change[k]).strip() assert request_ == response_ return response_data def test_upsert_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 10 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k, v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 # conflict upsert_data = deepcopy(updated_data) upsert_data['on_conflict'] = {'update_columns': ['numeric_value']} response = client.post('/test_2', headers=headers, data=json.dumps(dict(upsert_data, **json.loads(data)))) assert response.status_code == 201 # create response = client.post('/test_2', headers=headers, data=json.dumps(dict(updated_data, **json.loads(data)))) assert response.status_code == 409 ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test/test_patch_many_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy_table.api_test import get_transaction_session, app, UntitledTable256 test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_creation_one", tags=["test"] ) test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_creation_many", tags=["test"] ) test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_post_direct_get", tags=["test"] ) test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) test_patch_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.PATCH_MANY ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_patch_many", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_patch_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = 'primary_key' unique_fields = ['primary_key', 'int4_value', 'float4_value'] def test_create_many_and_patch_many(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = { "insert": [ { "bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ], "time_value": "18:18:18" , "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] } response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list":True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = { "bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "interval_value": 3600, "json_value": {'test':'hello'}, "jsonb_value": {'test':'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", "array_value": [ 1,2,3,4,5 ], "array_str__value": [ "test" ], "time_value": "18:19:18" , "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test_patch_many?{query_string}', data= json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test/test_patch_one_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy_table.api_test import get_transaction_session, app, UntitledTable256 test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_creation_one", tags=["test"] ) test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_creation_many", tags=["test"] ) test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_post_direct_get", tags=["test"] ) test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) test_update_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.PATCH_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_patch_one", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_update_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = 'primary_key' unique_fields = ['primary_key', 'int4_value', 'float4_value'] def test_create_one_and_patch_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key ,= [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False} response = client.patch(f'/test_patch_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(OrderedDict(**params)) update_data = { "char_value": "string_u "} response = client.patch(f'/test_patch_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(OrderedDict(**params)) update_data = {"date_value": "2022-07-24"} # update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, # "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, # "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, # "text_value": "string_update", # "timestamp_value": "2022-07-24T02:54:53.285000", # "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", # "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", # "array_value": [1, 2, 3, 4, 5], # "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test_patch_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test_patch_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test/test_post_redirect_get_api.py ================================================ import json import uuid from datetime import date, timedelta, datetime, timezone from http import HTTPStatus from starlette.testclient import TestClient from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy_table.api_test import get_transaction_session, app, UntitledTable256 test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_post_direct_get", tags=["test"] ) test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_post_direct_get", tags=["test"] ) test_post_and_redirect_get_without_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_post_direct_get_without_get", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get,test_post_and_redirect_get_without_get, test_get_data]] client = TestClient(app) primary_key_name = 'primary_key' unique_fields = ['primary_key', 'int4_value', 'float4_value'] # Post Redirect Get API Test def test_create_one_but_no_follow_redirect(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } data = '{ "bool_value": true, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }' response = client.post('/test_post_direct_get', headers=headers, data=data, allow_redirects=False) assert response.status_code == HTTPStatus.SEE_OTHER def test_create_one_with_redirect(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} bool_value_change = False char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' uuid_value_change = str(uuid.uuid4()) varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['uuid_value'] = uuid_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_post_direct_get', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() assert primary_key_name in response_data for k, v in response_data.items(): if k in change: if isinstance(v, str): v = v.strip() response_ = json.dumps(v).strip() request_ = json.dumps(change[k]).strip() assert request_ == response_ return response_data def test_create_but_conflict(): data = test_create_one_with_redirect() headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.post('/test_post_direct_get', headers=headers, data=json.dumps(data), allow_redirects=True) assert response.status_code == HTTPStatus.CONFLICT def test_create_but_not_found_get_api(): change = {} bool_value_change = False char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' uuid_value_change = str(uuid.uuid4()) varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['uuid_value'] = uuid_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data = json.dumps(change) headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.post('/test_post_direct_get_without_get', headers=headers, data=data, allow_redirects=True) assert response.status_code == HTTPStatus.NOT_FOUND ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test/test_put_many_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy_table.api_test import get_transaction_session, app, UntitledTable256 test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'] , prefix="/test_creation_one", tags=["test"] ) test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_creation_many", tags=["test"] ) test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_post_direct_get", tags=["test"] ) test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) test_update_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPDATE_MANY ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_update_many", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_update_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = 'primary_key' unique_fields = ['primary_key', 'int4_value', 'float4_value'] def test_create_many_and_update_many(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = { "insert": [ { "bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ], "time_value": "18:18:18" , "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] } response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list":True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = { "bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test':'hello'}, "jsonb_value": {'test':'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", "array_value": [ 1,2,3,4,5 ], "array_str__value": [ "test" ], "time_value": "18:19:18" , "timetz_value": "18:19:18+00:00"} response = client.put(f'/test_update_many?{query_string}', data= json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_create_many_and_update_many_but_not_found(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = { "insert": [ { "bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ], "time_value": "18:18:18" , "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] } response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list":True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '10:18:18', "time_value____to": '12:18:18', "time_value____list": '10:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "timez_value____from": '18:18:18+00:00', "timez_value____to": '18:18:18+00:00', "timez_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = { "bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test':'hello'}, "jsonb_value": {'test':'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", "array_value": [ 1,2,3,4,5 ], "array_str__value": [ "test" ], "time_value": "18:19:18" , "timetz_value": "18:19:18+00:00"} response = client.put(f'/test_update_many?{query_string}', data= json.dumps(update_data)) # response_data = response.json() # assert len(response_data) == 3 # for k in response_data: # for i in update_data: # print(i) # print(k[i]) # assert k[i] == update_data[i] assert response.status_code == 204 # test_create_many_and_update_many() ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test/test_put_one_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy_table.api_test import get_transaction_session, app, UntitledTable256 test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_creation_one", tags=["test"] ) test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_creation_many", tags=["test"] ) test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_post_direct_get", tags=["test"] ) test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) test_update_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPDATE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_update_one", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_update_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = 'primary_key' unique_fields = ['primary_key', 'int4_value', 'float4_value'] def test_create_one_and_update_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285Z", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key ,= [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test_update_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_create_one_and_update_one_but_not_found(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key ,= [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '10:18:18', "time_value____to": '12:18:18', "time_value____list": '10:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_valuez____from": '18:18:18+00:00', "time_valuez____to": '18:18:18+00:00', "time_valuez____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test_update_one/{primary_key}?{query_string}', data=json.dumps(update_data)) # response_data = response.json() response.status_code = 404 # assert response_data # for i in update_data: # assert response_data[i] == update_data[i] ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test/test_upsert_many_api.py ================================================ import json import uuid from datetime import date, timedelta, datetime, timezone from starlette.testclient import TestClient from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.misc.exceptions import ConflictColumnsCannotHit from tests.test_implementations.test_sqlalchemy_table.api_test import get_transaction_session, app, UntitledTable256 # Create Many API Test test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], crud_methods=[ CrudMethods.UPSERT_MANY, ], prefix="/test_creation_many", tags=["test"] ) [app.include_router(i) for i in [test_create_many]] client = TestClient(app) primary_key_name = 'primary_key' unique_fields = ['primary_key', 'int4_value', 'float4_value'] def create_example_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{ "insert": [ { "bool_value": true, "char_value": "string", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963Z", "timestamptz_value": "2021-07-23T02:38:24.963Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }, { "bool_value": true, "char_value": "string", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963Z", "timestamptz_value": "2021-07-23T02:38:24.963Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }, { "bool_value": true, "char_value": "string", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963Z", "timestamptz_value": "2021-07-23T02:38:24.963Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] } ] }' response = client.post('/test_creation_many', headers=headers, data=data) assert response.status_code == 201 return response.json() def test_try_only_input_required_fields(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{ "insert": [ { "float4_value": 1, "int2_value": 1, "int4_value": 1 },{ "float4_value": 2, "int2_value": 2, "int4_value": 2 },{ "float4_value": 3, "int2_value": 3, "int4_value": 3 } ] }' data_ = json.loads(data)['insert'] response = client.post('/test_creation_many', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_try_input_with_conflict_but_conflict_columns_not_hit(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"on_conflict": {"update_columns": ["bool_value", "float8_value", "varchar_value", "interval_value", "time_value", "int8_value", "jsonb_value", "timetz_value", "array_str__value", "text_value", "char_value", "uuid_value", "array_value", "numeric_value", "timestamp_value", "int2_value", "date_value", "json_value", "timestamptz_value"]}} insert_data = [] for i in sample_data: _ = {} for k, v in i.items(): _[k] = v for k, v in {"float4_value": 99, "int2_value": 99, "int4_value": 99}.items(): _[k] = v insert_data.append(_) data['insert'] = insert_data try: _ = json.dumps(data) response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) except ConflictColumnsCannotHit as e: pass assert response.status_code == 409 def test_try_input_with_conflict(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"on_conflict": {"update_columns": ["bool_value", "float8_value", "varchar_value", "interval_value", "time_value", "int8_value", "jsonb_value", "timetz_value", "array_str__value", "text_value", "char_value", "uuid_value", "array_value", "numeric_value", "timestamp_value", "int2_value", "date_value", "json_value", "timestamptz_value"]}} insert_data = [] for i in sample_data: _ = {} for k, v in i.items(): _[k] = v for k, v in {"float8_value": 0.7}.items(): _[k] = v insert_data.append(_) data['insert'] = insert_data response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data['insert']): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == value[k] def test_try_input_without_conflict(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {} insert_data = [] for i in sample_data: _ = {} for k, v in i.items(): _[k] = v for k, v in {"float4_value": 99, "int2_value": 99, "int4_value": 99}.items(): _[k] = v insert_data.append(_) data['insert'] = insert_data response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 409 def test_update_specific_columns_when_conflict(): def update_all_fields(): headers = { 'accept': 'application/json', } response_data = create_example_data() # create the data update_column_on_conflict = { "update_columns": [ "int8_value", "numeric_value", "varchar_value", "json_value", "float8_value", "time_value", "timestamp_value", "timestamptz_value", "array_value", "bool_value", "array_str__value", "int2_value", "text_value", "uuid_value", "char_value", "jsonb_value", "interval_value", "date_value", "timetz_value" ] } tmp = {} tmp['on_conflict'] = update_column_on_conflict bool_value_change = not response_data[0]['bool_value'] char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' uuid_value_change = str(uuid.uuid4()) varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change = {} change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['uuid_value'] = uuid_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change for i in response_data: for k, v in change.items(): i[k] = v tmp['insert'] = response_data response = client.post('/test_creation_many', headers=headers, data=json.dumps(tmp)) assert response.status_code == 201 response_result = response.json() for i in response_result: for k, v in i.items(): if k in change: if isinstance(v, str): v = v.strip() assert json.dumps(change[k]).strip() == json.dumps(v).strip() def update_partial_fields_1(): headers = { 'accept': 'application/json', } response_data = create_example_data() # create the data update_column_on_conflict = { "update_columns": [ "int8_value", "numeric_value", "varchar_value", "json_value", "float8_value", "time_value", "timestamp_value", "timestamptz_value", "array_value", "bool_value", "array_str__value", ] } tmp = {} tmp['on_conflict'] = update_column_on_conflict bool_value_change = not response_data[0]['bool_value'] float8_value_change = 0.1 int8_value_change = 100 json_value_change = {"hello": "world"} numeric_value_change = 19 time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) uuid_value_change = str(uuid.uuid4()) varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change = {} change['int8_value'] = int8_value_change change['numeric_value'] = numeric_value_change change['varchar_value'] = varchar_value_change change['json_value'] = json_value_change change['float8_value'] = float8_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['array_value'] = array_value_change change['bool_value'] = bool_value_change change['array_str__value'] = array_str__value_change for i in response_data: for k, v in change.items(): i[k] = v tmp['insert'] = response_data response = client.post('/test_creation_many', headers=headers, data=json.dumps(tmp)) assert response.status_code == 201 response_result = response.json() for i in response_result: for k, v in i.items(): if k in change: if isinstance(v, str): v = v.strip() assert json.dumps(change[k]).strip() == json.dumps(v).strip() def update_partial_fields_2(): headers = { 'accept': 'application/json', } response_data = create_example_data() # create the data update_column_on_conflict = { "update_columns": [ "int2_value", "text_value", "uuid_value", "char_value", "jsonb_value", "interval_value", "date_value", "timetz_value" ] } tmp = {} tmp['on_conflict'] = update_column_on_conflict char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) int2_value_change = 100 interval_value_change = float(5400) jsonb_value_change = {"hello": "world"} text_value_change = 'hello world' timetz_value_change = '18:18:18+00:00' uuid_value_change = str(uuid.uuid4()) change = {} change['int2_value'] = int2_value_change change['text_value'] = text_value_change change['uuid_value'] = uuid_value_change change['char_value'] = char_value_change change['jsonb_value'] = jsonb_value_change change['interval_value'] = interval_value_change change['date_value'] = date_value_change change['timetz_value'] = timetz_value_change for i in response_data: for k, v in change.items(): i[k] = v tmp['insert'] = response_data response = client.post('/test_creation_many', headers=headers, data=json.dumps(tmp)) assert response.status_code == 201 response_result = response.json() for i in response_result: for k, v in i.items(): if k in change: if isinstance(v, str): v = v.strip() assert json.dumps(change[k]).strip() == json.dumps(v).strip() update_all_fields() update_partial_fields_1() update_partial_fields_2() ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test/test_upsert_one_api.py ================================================ import json import random import uuid from datetime import date, timedelta, datetime, timezone from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.exceptions import ConflictColumnsCannotHit, UnknownColumn, UpdateColumnEmptyException from src.fastapi_quickcrud.misc.type import CrudMethods from tests.test_implementations.test_sqlalchemy_table.api_test import get_transaction_session, app, UntitledTable256 test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, prefix="/test_creation_one", tags=["test"], crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'] ) test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, prefix="/test_creation_many", tags=["test"], crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'] ) test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_post_direct_get", tags=["test"] ) test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, prefix="/test", tags=["test"], crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = 'primary_key' unique_fields = ['primary_key', 'int4_value', 'float4_value'] # Create One API Test def create_example_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_creation_one', headers=headers, data=data) assert response.status_code == 201 return response.json() def test_try_only_input_required_fields(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"float4_value": 0.0, "int2_value": 0, "int4_value": 0, 'uuid_value': '3fa85f64-5717-4562-b3fc-2c963f66afa6'} response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) assert response.status_code == 201 response_result = response.json() for k, v in data.items(): assert response_result[k] == v def test_try_input_with_conflict_but_conflict_columns_not_hit(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"on_conflict": {"update_columns": ["bool_value", "float8_value", "varchar_value", "interval_value", "time_value", "int8_value", "jsonb_value", "timetz_value", "array_str__value", "text_value", "char_value", "uuid_value", "array_value", "numeric_value", "timestamp_value", "int2_value", "date_value", "json_value", "timestamptz_value"]}} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 99, "int2_value": 99, "int4_value": 99}.items(): data[k] = v # for k, v in {"float4_value": 99.9, "int2_value": 99, "int4_value": 99}.items(): # data[k] = v try: _ = json.dumps(data) response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) except ConflictColumnsCannotHit as e: pass assert response.status_code == 409 def test_try_input_with_conflict(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"on_conflict": {"update_columns": ["bool_value", "float8_value", "varchar_value", "interval_value", "time_value", "int8_value", "jsonb_value", "timetz_value", "array_str__value", "text_value", "char_value", "uuid_value", "array_value", "numeric_value", "timestamp_value", "int2_value", "date_value", "json_value", "timestamptz_value"]}} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 0.0, "int2_value": 99, "int4_value": 0}.items(): data[k] = v response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) assert response.status_code == 201 response_result = response.json() for k, v in response_result.items(): if k in data: if isinstance(v, str): v = v.strip() assert json.dumps(data[k]).strip() == json.dumps(v).strip() def test_try_input_without_conflict(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 0.0, "int2_value": 99, "int4_value": 0}.items(): data[k] = v # data['on_conflict'] = {'update_columns': []} response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) assert response.status_code == 409 def test_update_specific_columns_when_conflict(): def update_all_fields(): headers = { 'accept': 'application/json', } sample_data = create_example_data() response = client.get(f'/test/{sample_data[primary_key_name]}', headers=headers) assert response.status_code == 200 response_data = response.json() # create the data update_column_on_conflict = { "update_columns": [ "int8_value", "numeric_value", "varchar_value", "json_value", "float8_value", "time_value", "timestamp_value", "timestamptz_value", "array_value", "bool_value", "array_str__value", "int2_value", "text_value", "uuid_value", "char_value", "jsonb_value", "interval_value", "date_value", "timetz_value" ] } response_data['on_conflict'] = update_column_on_conflict ran_num = random.randint(5, 100) bool_value_change = not response_data['bool_value'] char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' uuid_value_change = str(uuid.uuid4()) varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change = {} change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['uuid_value'] = uuid_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change for k, v in change.items(): response_data[k] = v response = client.post('/test_creation_one', headers=headers, data=json.dumps(response_data)) assert response.status_code == 201 response_result = response.json() for k, v in response_result.items(): if k in change: if isinstance(v, str): v = v.strip() assert json.dumps(change[k]).strip() == json.dumps(v).strip() def update_partial_fields(): headers = { 'accept': 'application/json', } sample_data = create_example_data() response = client.get(f'/test/{sample_data[primary_key_name]}', headers=headers) assert response.status_code == 200 response_data = response.json() # create the data update_column_on_conflict = { "update_columns": [ "varchar_value", "json_value", "float8_value", "time_value", "timestamp_value", "timestamptz_value", "array_value", "bool_value", "array_str__value", "char_value", "jsonb_value", "interval_value", "date_value", "timetz_value" ] } response_data['on_conflict'] = update_column_on_conflict ran_num = random.randint(5, 100) bool_value_change = not response_data['bool_value'] char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change = {} change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change for k, v in change.items(): response_data[k] = v response = client.post('/test_creation_one', headers=headers, data=json.dumps(response_data)) assert response.status_code == 201 response_result = response.json() for k, v in response_result.items(): if k in change: if isinstance(v, str): v = v.strip() assert json.dumps(change[k]).strip() == json.dumps(v).strip() update_all_fields() update_partial_fields() def test_try_input_with_conflict_but_missing_update_columns(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 0.0, "int2_value": 99, "int4_value": 0}.items(): data[k] = v data['on_conflict'] = {'update_columns': []} try: response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) except UpdateColumnEmptyException as e: assert True return assert False def test_try_input_with_conflict_but_unknown_update_columns(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 0.0, "int2_value": 99, "int4_value": 0}.items(): data[k] = v data['on_conflict'] = {'update_columns': ['testsetsetset']} try: response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) except UnknownColumn as e: assert True return assert False ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test_async/__init__.py ================================================ import asyncio import os from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR,Table, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_ASYNC_URL', 'postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres') from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine engine = create_async_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(autocommit=False, autoflush=False, bind=engine, class_=AsyncSession) async def get_transaction_session() -> AsyncSession: async with async_session() as session: yield session UntitledTable256 = Table( 'test_table', metadata, Column('primary_key', Integer, primary_key=True, nullable=False,autoincrement=True,info={'alias_name': 'primary_key'}), Column('bool_value', Boolean, nullable=False, server_default=text("false")), Column('bytea_value', LargeBinary), Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float, nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL), Column('json_value', JSON), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric), Column('text_value', Text), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('uuid_value', UUID), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), UniqueConstraint('primary_key', 'int4_value', 'float4_value'), ) async def create_table(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) loop = asyncio.get_event_loop() loop.run_until_complete(create_table()) ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test_async/test_create_many_api.py ================================================ import json import uuid from datetime import date, timedelta, datetime, timezone from starlette.testclient import TestClient from src.fastapi_quickcrud.misc.exceptions import ConflictColumnsCannotHit from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy_table.api_test_async import get_transaction_session, app, UntitledTable256 # Create Many API Test test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_creation_many", async_mode=True, tags=["test"] ) [app.include_router(i) for i in [test_create_many]] client = TestClient(app) primary_key_name = 'primary_key' unique_fields = ['primary_key', 'int4_value', 'float4_value'] def create_example_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{ "insert": [ { "bool_value": true, "char_value": "string", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963", "timestamptz_value": "2021-07-23T02:38:24.963Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }, { "bool_value": true, "char_value": "string", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963", "timestamptz_value": "2021-07-23T02:38:24.963Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }, { "bool_value": true, "char_value": "string", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963", "timestamptz_value": "2021-07-23T02:38:24.963Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] } ] }' response = client.post('/test_creation_many', headers=headers, data=data) assert response.status_code == 201 return response.json() def test_try_only_input_required_fields(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{ "insert": [ { "float4_value": 1, "int2_value": 1, "int4_value": 1 },{ "float4_value": 2, "int2_value": 2, "int4_value": 2 },{ "float4_value": 3, "int2_value": 3, "int4_value": 3 } ] }' data_ = json.loads(data)['insert'] response = client.post('/test_creation_many', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_try_input_with_conflict_but_conflict_columns_not_hit(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"on_conflict": {"update_columns": ["bool_value", "float8_value", "varchar_value", "interval_value", "time_value", "int8_value", "jsonb_value", "timetz_value", "array_str__value", "text_value", "char_value", "uuid_value", "array_value", "numeric_value", "timestamp_value", "int2_value", "date_value", "json_value", "timestamptz_value"]}} insert_data = [] for i in sample_data: _ = {} for k, v in i.items(): _[k] = v for k, v in {"float4_value": 99, "int2_value": 99, "int4_value": 99}.items(): _[k] = v insert_data.append(_) data['insert'] = insert_data try: _ = json.dumps(data) response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) except ConflictColumnsCannotHit as e: pass assert response.status_code == 409 def test_try_input_with_conflict(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"on_conflict": {"update_columns": ["bool_value", "float8_value", "varchar_value", "interval_value", "time_value", "int8_value", "jsonb_value", "timetz_value", "array_str__value", "text_value", "char_value", "uuid_value", "array_value", "numeric_value", "timestamp_value", "int2_value", "date_value", "json_value", "timestamptz_value"]}} insert_data = [] for i in sample_data: _ = {} for k, v in i.items(): _[k] = v for k, v in {"float8_value": 0.7}.items(): _[k] = v insert_data.append(_) data['insert'] = insert_data response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data['insert']): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == value[k] def test_try_input_without_conflict(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {} insert_data = [] for i in sample_data: _ = {} for k, v in i.items(): _[k] = v for k, v in {"float4_value": 99, "int2_value": 99, "int4_value": 99}.items(): _[k] = v insert_data.append(_) data['insert'] = insert_data response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 409 def test_update_specific_columns_when_conflict(): def update_all_fields(): headers = { 'accept': 'application/json', } response_data = create_example_data() # create the data update_column_on_conflict = { "update_columns": [ "int8_value", "numeric_value", "varchar_value", "json_value", "float8_value", "time_value", "timestamp_value", "timestamptz_value", "array_value", "bool_value", "array_str__value", "int2_value", "text_value", "uuid_value", "char_value", "jsonb_value", "interval_value", "date_value", "timetz_value" ] } tmp = {} tmp['on_conflict'] = update_column_on_conflict bool_value_change = not response_data[0]['bool_value'] char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' uuid_value_change = str(uuid.uuid4()) varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change = {} change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['uuid_value'] = uuid_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change for i in response_data: for k, v in change.items(): i[k] = v tmp['insert'] = response_data response = client.post('/test_creation_many', headers=headers, data=json.dumps(tmp)) assert response.status_code == 201 response_result = response.json() for i in response_result: for k, v in i.items(): if k in change: if isinstance(v, str): v = v.strip() assert json.dumps(change[k]).strip() == json.dumps(v).strip() def update_partial_fields_1(): headers = { 'accept': 'application/json', } response_data = create_example_data() # create the data update_column_on_conflict = { "update_columns": [ "int8_value", "numeric_value", "varchar_value", "json_value", "float8_value", "time_value", "timestamp_value", "timestamptz_value", "array_value", "bool_value", "array_str__value", ] } tmp = {} tmp['on_conflict'] = update_column_on_conflict bool_value_change = not response_data[0]['bool_value'] float8_value_change = 0.1 int8_value_change = 100 json_value_change = {"hello": "world"} numeric_value_change = 19 time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) uuid_value_change = str(uuid.uuid4()) varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change = {} change['int8_value'] = int8_value_change change['numeric_value'] = numeric_value_change change['varchar_value'] = varchar_value_change change['json_value'] = json_value_change change['float8_value'] = float8_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['array_value'] = array_value_change change['bool_value'] = bool_value_change change['array_str__value'] = array_str__value_change for i in response_data: for k, v in change.items(): i[k] = v tmp['insert'] = response_data response = client.post('/test_creation_many', headers=headers, data=json.dumps(tmp)) assert response.status_code == 201 response_result = response.json() for i in response_result: for k, v in i.items(): if k in change: if isinstance(v, str): v = v.strip() assert json.dumps(change[k]).strip() == json.dumps(v).strip() def update_partial_fields_2(): headers = { 'accept': 'application/json', } response_data = create_example_data() # create the data update_column_on_conflict = { "update_columns": [ "int2_value", "text_value", "uuid_value", "char_value", "jsonb_value", "interval_value", "date_value", "timetz_value" ] } tmp = {} tmp['on_conflict'] = update_column_on_conflict char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) int2_value_change = 100 interval_value_change = float(5400) jsonb_value_change = {"hello": "world"} text_value_change = 'hello world' timetz_value_change = '18:18:18+00:00' uuid_value_change = str(uuid.uuid4()) change = {} change['int2_value'] = int2_value_change change['text_value'] = text_value_change change['uuid_value'] = uuid_value_change change['char_value'] = char_value_change change['jsonb_value'] = jsonb_value_change change['interval_value'] = interval_value_change change['date_value'] = date_value_change change['timetz_value'] = timetz_value_change for i in response_data: for k, v in change.items(): i[k] = v tmp['insert'] = response_data response = client.post('/test_creation_many', headers=headers, data=json.dumps(tmp)) assert response.status_code == 201 response_result = response.json() for i in response_result: for k, v in i.items(): if k in change: if isinstance(v, str): v = v.strip() assert json.dumps(change[k]).strip() == json.dumps(v).strip() update_all_fields() update_partial_fields_1() update_partial_fields_2() ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test_async/test_create_one_api.py ================================================ import json import random import uuid from datetime import date, timedelta, datetime, timezone from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.exceptions import ConflictColumnsCannotHit, UnknownColumn, UpdateColumnEmptyException from src.fastapi_quickcrud.misc.type import CrudMethods from tests.test_implementations.test_sqlalchemy_table.api_test_async import get_transaction_session, app, \ UntitledTable256 test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test_creation_one", tags=["test"] ) test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_creation_many", async_mode=True, tags=["test"] ) test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test_post_direct_get", tags=["test"] ) test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", async_mode=True, tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = 'primary_key' unique_fields = ['primary_key', 'int4_value', 'float4_value'] # Create One API Test def create_example_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_creation_one', headers=headers, data=data) assert response.status_code == 201 return response.json() def test_try_only_input_required_fields(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"float4_value": 0.0, "int2_value": 0, "int4_value": 0, 'uuid_value': '3fa85f64-5717-4562-b3fc-2c963f66afa6'} response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) assert response.status_code == 201 response_result = response.json() for k, v in data.items(): assert response_result[k] == v def test_try_input_with_conflict_but_conflict_columns_not_hit(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"on_conflict": {"update_columns": ["bool_value", "float8_value", "varchar_value", "interval_value", "time_value", "int8_value", "jsonb_value", "timetz_value", "array_str__value", "text_value", "char_value", "uuid_value", "array_value", "numeric_value", "timestamp_value", "int2_value", "date_value", "json_value", "timestamptz_value"]}} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 99, "int2_value": 99, "int4_value": 99}.items(): data[k] = v # for k, v in {"float4_value": 99.9, "int2_value": 99, "int4_value": 99}.items(): # data[k] = v try: _ = json.dumps(data) response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) except ConflictColumnsCannotHit as e: pass assert response.status_code == 409 def test_try_input_with_conflict(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"on_conflict": {"update_columns": ["bool_value", "float8_value", "varchar_value", "interval_value", "time_value", "int8_value", "jsonb_value", "timetz_value", "array_str__value", "text_value", "char_value", "uuid_value", "array_value", "numeric_value", "timestamp_value", "int2_value", "date_value", "json_value", "timestamptz_value"]}} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 0.0, "int2_value": 99, "int4_value": 0}.items(): data[k] = v response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) assert response.status_code == 201 response_result = response.json() for k, v in response_result.items(): if k in data: if isinstance(v, str): v = v.strip() assert json.dumps(data[k]).strip() == json.dumps(v).strip() def test_try_input_without_conflict(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 0.0, "int2_value": 99, "int4_value": 0}.items(): data[k] = v # data['on_conflict'] = {'update_columns': []} response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) assert response.status_code == 409 def test_update_specific_columns_when_conflict(): def update_all_fields(): headers = { 'accept': 'application/json', } sample_data = create_example_data() response = client.get(f'/test/{sample_data[primary_key_name]}', headers=headers) assert response.status_code == 200 response_data = response.json() # create the data update_column_on_conflict = { "update_columns": [ "int8_value", "numeric_value", "varchar_value", "json_value", "float8_value", "time_value", "timestamp_value", "timestamptz_value", "array_value", "bool_value", "array_str__value", "int2_value", "text_value", "uuid_value", "char_value", "jsonb_value", "interval_value", "date_value", "timetz_value" ] } response_data['on_conflict'] = update_column_on_conflict ran_num = random.randint(5, 100) bool_value_change = not response_data['bool_value'] char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' uuid_value_change = str(uuid.uuid4()) varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change = {} change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['uuid_value'] = uuid_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change for k, v in change.items(): response_data[k] = v response = client.post('/test_creation_one', headers=headers, data=json.dumps(response_data)) assert response.status_code == 201 response_result = response.json() for k, v in response_result.items(): if k in change: if isinstance(v, str): v = v.strip() assert json.dumps(change[k]).strip() == json.dumps(v).strip() def update_partial_fields(): headers = { 'accept': 'application/json', } sample_data = create_example_data() response = client.get(f'/test/{sample_data[primary_key_name]}', headers=headers) assert response.status_code == 200 response_data = response.json() # create the data update_column_on_conflict = { "update_columns": [ "varchar_value", "json_value", "float8_value", "time_value", "timestamp_value", "timestamptz_value", "array_value", "bool_value", "array_str__value", "char_value", "jsonb_value", "interval_value", "date_value", "timetz_value" ] } response_data['on_conflict'] = update_column_on_conflict ran_num = random.randint(5, 100) bool_value_change = not response_data['bool_value'] char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change = {} change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change for k, v in change.items(): response_data[k] = v response = client.post('/test_creation_one', headers=headers, data=json.dumps(response_data)) assert response.status_code == 201 response_result = response.json() for k, v in response_result.items(): if k in change: if isinstance(v, str): v = v.strip() assert json.dumps(change[k]).strip() == json.dumps(v).strip() update_all_fields() update_partial_fields() def test_try_input_with_conflict_but_missing_update_columns(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 0.0, "int2_value": 99, "int4_value": 0}.items(): data[k] = v data['on_conflict'] = {'update_columns': []} try: response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) except UpdateColumnEmptyException as e: assert True return assert False def test_try_input_with_conflict_but_unknown_update_columns(): sample_data = create_example_data() headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {} for k, v in sample_data.items(): data[k] = v for k, v in {"float4_value": 0.0, "int2_value": 99, "int4_value": 0}.items(): data[k] = v data['on_conflict'] = {'update_columns': ['testsetsetset']} try: response = client.post('/test_creation_one', headers=headers, data=json.dumps(data)) except UnknownColumn as e: assert True return assert False ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test_async/test_delete_many_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods from tests.test_implementations.test_sqlalchemy_table.api_test_async import get_transaction_session, app, UntitledTable256 test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test_creation_one", tags=["test"] ) test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_creation_many", async_mode=True, tags=["test"] ) # Response Mode Test # response_many = create_many_response_model['__root__'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in response_many.items(): # assert not v.required test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_post_direct_get", async_mode=True, tags=["test"] ) test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) test_delete_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.DELETE_MANY ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_delete_many", async_mode=True, tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_delete_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = 'primary_key' unique_fields = ['primary_key', 'int4_value', 'float4_value'] def test_create_many_and_delete_many(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = { "insert": [ { "bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ], "time_value": "18:18:18" , "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] } response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list":True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) response = client.delete(f'/test_delete_many?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_create_many_and_delete_many_but_not_found(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = { "insert": [ { "bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ], "time_value": "18:18:18" , "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] } response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list":True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '10:18:18', "time_value____to": '12:18:18', "time_value____list": '12:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "timez_value____from": '18:18:18+00:00', "timez_value____to": '18:18:18+00:00', "timez_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) response = client.delete(f'/test_delete_many?{query_string}') assert response.status_code == 204 ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test_async/test_delete_one_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods from tests.test_implementations.test_sqlalchemy_table.api_test_async import get_transaction_session, app, \ UntitledTable256 test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test_creation_one", tags=["test"] ) test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test_creation_many", tags=["test"] ) test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test_post_direct_get", tags=["test"] ) test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test", tags=["test"] ) test_delete_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.DELETE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test_delete_one", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_delete_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = 'primary_key' unique_fields = ['primary_key', 'int4_value', 'float4_value'] def test_create_one_and_delete_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False} response = client.delete(f'/test_delete_one/{primary_key}?{query_string}') response_data = response.json() assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_create_one_and_delete_one_but_not_found(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key ,= [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '10:18:18', "time_value____to": '12:18:18', "time_value____list": '10:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "timez_value____from": '18:18:18+00:00', "timez_value____to": '18:18:18+00:00', "timez_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False} response = client.delete(f'/test_delete_one/{primary_key}?{query_string}') assert response.status_code == 404 ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test_async/test_get_many_api.py ================================================ import json from collections import OrderedDict from urllib.parse import urlencode from starlette.testclient import TestClient from src.fastapi_quickcrud.misc.exceptions import UnknownOrderType, UnknownColumn from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods from src.fastapi_quickcrud.misc.utils import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy_table.api_test_async import get_transaction_session, app, \ UntitledTable256 # # test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_creation_many", async_mode=True, tags=["test"] ) test_find_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.FIND_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test_get_many", tags=["test"] ) [app.include_router(i) for i in [test_create_many, test_find_many]] client = TestClient(app) primary_key_name = 'primary_key' unique_fields = ['primary_key', 'int4_value', 'float4_value'] # test create many def create_example_data(num=1, **kwargs): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } insert_sample_item = {"bool_value": kwargs.get('bool_value', True), "char_value": kwargs.get('char_value', 'string'), "date_value": kwargs.get('date_value', "2021-07-23"), "float4_value": kwargs.get('float4_value', 0.6), "float8_value": kwargs.get('float8_value', 0.8), "int2_value": kwargs.get('int2_value', 11), "int4_value": kwargs.get('int4_value', 1), "int8_value": kwargs.get('int8_value', 3), "interval_value": kwargs.get('interval_value', 5), "json_value": kwargs.get('json_value', {}), "jsonb_value": kwargs.get('jsonb_value', {}), "numeric_value": kwargs.get('numeric_value', 110), "text_value": kwargs.get('text_value', 'string'), "timestamp_value": kwargs.get('timestamp_value', "2021-07-23T02:38:24.963"), "timestamptz_value": kwargs.get('timestamptz_value', "2021-07-23T02:38:24.963Z"), "uuid_value": kwargs.get('uuid_value', "3fa85f64-5717-4562-b3fc-2c963f66afa6"), "varchar_value": kwargs.get('varchar_value', 'string'), "array_value": kwargs.get('array_value', [1, 2, 3, 4]), "array_str__value": kwargs.get('array_str__value', ["string", "string1"])} data = {'insert': [insert_sample_item for i in range(num)]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 response_result = response.json() for i in response_result: assert primary_key_name in i assert i[primary_key_name] return response_result # test pagination by offset and limit and ordering def test_pagination_and_ording(): sample_data = create_example_data(5 * 10) assert len(sample_data) == 5 * 10 limit = 5 seem = [] for num in range(0, 5 * 10, 5): response = client.get( f'/test_get_many?limit={limit}&offset={num}&order_by_columns=primary_key%20%3A%20DESC%20') response.headers['x-total-count'] == limit assert response.status_code == 200 _ = response.json() for i in _: assert i not in seem seem.append(i) assert i in sample_data # test create a new data and get by primary key def test_create_new_data_and_get_by_primary_key(): sample_data = create_example_data(10) primary_key_list = [i[primary_key_name] for i in sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key} from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in response_data: assert i['primary_key'] in primary_key_list params = {"primary_key____from": min_key, "primary_key____to": max_key, "primary_key____from_____comparison_operator": 'Greater_than', "primary_key____to_____comparison_operator": 'Less_than'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 8 for i in response_data: assert i['primary_key'] in primary_key_list # test create a more than one data which value is TRUE of boolean type, and get many def test_create_a_more_than_one_data_which_value_is_TRUE_of_boolean_type_and_get_many(): bool_false_sample_data = create_example_data(5, bool_value=False) bool_true_sample_data = create_example_data(5, bool_value=True) primary_key_list = [i[primary_key_name] for i in bool_false_sample_data] + \ [i[primary_key_name] for i in bool_true_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "In", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) + f"&bool_value____list=False" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "In", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i not in response.json() for i in bool_true_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "In", "bool_value____list": False} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Equal", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) + f"&bool_value____list=False" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Equal", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i not in response.json() for i in bool_true_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Equal", "bool_value____list": False} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i not in response.json() # params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_in", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) + f"&bool_value____list=False" response = client.get(f'/test_get_many?{query_string}') assert response.status_code == 204 params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_in", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_in", "bool_value____list": False} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i not in response.json() for i in bool_true_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_equal", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) + f"&bool_value____list=False" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_equal", "bool_value____list": True} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i in response.json() for i in bool_true_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list_____comparison_operator": "Not_equal", "bool_value____list": False} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in bool_false_sample_data: assert i not in response.json() for i in bool_true_sample_data: assert i in response.json() # test create a more than one data of char/text/varchar type, and get many def test_create_a_more_than_one_data_and_get_many_1(): char_str_sample_data = create_example_data(5, char_value='string') char_test_sample_data = create_example_data(5, char_value='test') primary_key_list = [i[primary_key_name] for i in char_str_sample_data] + \ [i[primary_key_name] for i in char_test_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) # match_regex_with_case_sensitive/ dose not match_regex_with_case_sensitive def match_regex_with_case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "char_value____str": 'str.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "char_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_match_regex_with_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "char_value____str": 'str.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "char_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "char_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "char_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "char_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "char_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def match_regex_with_case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "char_value____str": 'STR.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "char_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # does_not_match_regex_with_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "char_value____str": 'STR.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "char_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "char_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=STR.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "char_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=STR.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'case_sensitive', "char_value____str": 'string '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'case_sensitive', "char_value____str": 'test '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_sensitive', "char_value____str": 'string '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_sensitive', "char_value____str": 'test '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_sensitive', "char_value____str": 'test '} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=string " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_insensitive', "char_value____str": 'test '} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=string " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'case_insensitive', "char_value____str": 'STRING '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'case_insensitive', "char_value____str": 'TEST '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_insensitive', "char_value____str": 'STRING '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_insensitive', "char_value____str": 'TEST '} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_insensitive', "char_value____str": 'TEST '} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=STRING " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_case_sensitive', "char_value____str": 'TEST '} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=STRING " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def similar_to(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'similar_to', "char_value____str": 'string%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'similar_to', "char_value____str": 'test%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_similar_to', "char_value____str": 'string%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'not_similar_to', "char_value____str": 'test%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'similar_to'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str%&char_value____str=_es%" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "char_value____str_____matching_pattern": 'similar_to'} query_string = urlencode(OrderedDict(**params)) + "&char_value____str=str%&char_value____str=_es%" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() match_regex_with_case_sensitive() match_regex_with_case_insensitive() case_sensitive() case_insensitive() similar_to() # Varchar char_str_sample_data = create_example_data(5, varchar_value='string') char_test_sample_data = create_example_data(5, varchar_value='test') primary_key_list = [i[primary_key_name] for i in char_str_sample_data] + \ [i[primary_key_name] for i in char_test_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) # match_regex_with_case_sensitive/ dose not match_regex_with_case_sensitive def match_regex_with_case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "varchar_value____str": 'str.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "varchar_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_match_regex_with_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "varchar_value____str": 'str.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "varchar_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "varchar_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "varchar_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "varchar_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "varchar_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def match_regex_with_case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "varchar_value____str": 'STR.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "varchar_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # does_not_match_regex_with_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "varchar_value____str": 'STR.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "varchar_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "varchar_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=STR.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "varchar_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=STR.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_sensitive', "varchar_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_sensitive', "varchar_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_sensitive', "varchar_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=string " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_insensitive', "varchar_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=string " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'case_insensitive', "varchar_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'case_insensitive', "varchar_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_insensitive', "varchar_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_insensitive', "varchar_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_insensitive', "varchar_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_case_sensitive', "varchar_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def similar_to(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'similar_to', "varchar_value____str": 'string%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'similar_to', "varchar_value____str": 'test%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_similar_to', "varchar_value____str": 'string%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'not_similar_to', "varchar_value____str": 'test%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'similar_to'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str%&varchar_value____str=_es%" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "varchar_value____str_____matching_pattern": 'similar_to'} query_string = urlencode(OrderedDict(**params)) + "&varchar_value____str=str%&varchar_value____str=_es%" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() match_regex_with_case_sensitive() match_regex_with_case_insensitive() case_sensitive() case_insensitive() similar_to() # Text char_str_sample_data = create_example_data(5, text_value='string') char_test_sample_data = create_example_data(5, text_value='test') primary_key_list = [i[primary_key_name] for i in char_str_sample_data] + \ [i[primary_key_name] for i in char_test_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) # match_regex_with_case_sensitive/ dose not match_regex_with_case_sensitive def match_regex_with_case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "text_value____str": 'str.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "text_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_match_regex_with_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "text_value____str": 'str.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "text_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'match_regex_with_case_sensitive', "text_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "text_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "text_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "text_value____str": 'tes.*'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def match_regex_with_case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "text_value____str": 'STR.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'match_regex_with_case_insensitive', "text_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # does_not_match_regex_with_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "text_value____str": 'STR.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "text_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_sensitive', "text_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=STR.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'does_not_match_regex_with_case_insensitive', "text_value____str": 'TES.*'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=STR.*" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def case_sensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'case_sensitive', "text_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'case_sensitive', "text_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_sensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_sensitive', "text_value____str": 'string'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_sensitive', "text_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_sensitive', "text_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=string " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_insensitive', "text_value____str": 'test'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=string " response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def case_insensitive(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'case_insensitive', "text_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'case_insensitive', "text_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_insensitive', "text_value____str": 'STRING'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_insensitive', "text_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_insensitive', "text_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_case_sensitive', "text_value____str": 'TEST'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=STRING" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() def similar_to(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'similar_to', "text_value____str": 'string%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'similar_to', "text_value____str": 'test%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() # not_case_insensitive params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_similar_to', "text_value____str": 'string%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i not in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'not_similar_to', "text_value____str": 'test%'} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i not in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'similar_to'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str%&text_value____str=_es%" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() params = {"primary_key____from": min_key, "primary_key____to": max_key, "text_value____str_____matching_pattern": 'similar_to'} query_string = urlencode(OrderedDict(**params)) + "&text_value____str=str%&text_value____str=_es%" response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in char_str_sample_data: assert i in response.json() for i in char_test_sample_data: assert i in response.json() match_regex_with_case_sensitive() match_regex_with_case_insensitive() case_sensitive() case_insensitive() similar_to() # test create a more than one data of float4/text/varchar type, and get many def test_create_a_more_than_one_data_and_get_many_2(): float_one = 5.5 float_two = 10.7 # float 4 <= will round down to the odd floating even # data = 0.4 # <= 0.4 # result = [] # data = 0.4 # <= 0.5 # result = [0.4] num_one_sample_data = create_example_data(5, float4_value=float_one) num_two_sample_data = create_example_data(5, float4_value=float_two) primary_key_list = [i[primary_key_name] for i in num_one_sample_data] + \ [i[primary_key_name] for i in num_two_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) def greater_than_or_equal_to_Less_than_or_equal_to(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "float4_value____from_____comparison_operator": 'Greater_than_or_equal_to', "float4_value____to_____comparison_operator": 'Less_than_or_equal_to', "float4_value____from": float_one, "float4_value____to": float_two} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in num_one_sample_data: assert i in response.json() for i in num_two_sample_data: assert i in response.json() # data = 10.7 # < 10.7 # still got 10.7 but if data is 10.6 def less_than_or_equal_to_less_than(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "float4_value____from_____comparison_operator": 'Greater_than', "float4_value____to_____comparison_operator": 'Less_than', "float4_value____from": float_one, "float4_value____to": float_two + 0.1} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in num_one_sample_data: assert i not in response.json() for i in num_two_sample_data: assert i in response.json() greater_than_or_equal_to_Less_than_or_equal_to() less_than_or_equal_to_less_than() # float 4 < will round down to the odd floating odd # data = 0.3 # <= 0.4 # result = [] # data = 0.4 # <= 0.5 # result = [0.4] float_one = 5.5 float_two = 10.6 num_one_sample_data = create_example_data(5, float8_value=float_one) num_two_sample_data = create_example_data(5, float8_value=float_two) primary_key_list = [i[primary_key_name] for i in num_one_sample_data] + \ [i[primary_key_name] for i in num_two_sample_data] min_key = min(primary_key_list) max_key = max(primary_key_list) def greater_than_or_equal_to_Less_than_or_equal_to(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "float8_value____from_____comparison_operator": 'Greater_than_or_equal_to', "float8_value____to_____comparison_operator": 'Less_than_or_equal_to', "float8_value____from": float_one, "float8_value____to": float_two} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 10 for i in num_one_sample_data: assert i in response.json() for i in num_two_sample_data: assert i in response.json() def less_than_or_equal_to_less_than(): params = {"primary_key____from": min_key, "primary_key____to": max_key, "float8_value____from_____comparison_operator": 'Greater_than', "float8_value____to_____comparison_operator": 'Less_than', "float8_value____from": float_one, "float8_value____to": float_two + 0.1} query_string = urlencode(OrderedDict(**params)) response = client.get(f'/test_get_many?{query_string}') response_data = response.json() assert len(response_data) == 5 for i in num_one_sample_data: assert i not in response.json() for i in num_two_sample_data: assert i in response.json() greater_than_or_equal_to_Less_than_or_equal_to() less_than_or_equal_to_less_than() def test_get_many_with_ordering_unknown_column(): try: response = client.get(f'/test_get_many?order_by_columns=testestset') except UnknownColumn as e: assert str(e) == "column testestset is not exited" return assert False def test_get_many_with_ordering_with_default_order(): response = client.get(f'/test_get_many?order_by_columns=primary_key&limit=10&offset=0') a = response.json() init = 0 for i in a: assert i['primary_key'] > init init = i['primary_key'] def test_get_many_with_ordering_with_ASC(): response = client.get(f'/test_get_many?order_by_columns=primary_key:ASC&limit=10&offset=0') a = response.json() init = 0 for i in a: assert i['primary_key'] > init init = i['primary_key'] def test_get_many_with_ordering_with_DESC(): response = client.get(f'/test_get_many?order_by_columns=primary_key:DESC&limit=10&offset=10') a = response.json() init = a[0]['primary_key'] for i in a: assert i['primary_key'] == init init -= 1 def test_get_many_with_unknown_order_tyoe(): try: response = client.get(f'/test_get_many?order_by_columns=primary_key:DESCSS&limit=10&offset=0') except UnknownOrderType as e: assert str(e) == 'Unknown order type DESCSS, only accept DESC or ASC' return assert False def test_get_many_with_ordering_with_empty_input_list(): try: response = client.get(f'/test_get_many?order_by_columns=') except Exception as e: assert False assert True ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test_async/test_get_one_api.py ================================================ import json import os from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession from sqlalchemy.orm import sessionmaker from starlette.testclient import TestClient from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy_table.api_test_async import app, UntitledTable256 TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_ASYNC_URL', 'postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres') engine = create_async_engine(TEST_DATABASE_URL, echo=True, future=True) async_session = sessionmaker( engine, class_=AsyncSession, expire_on_commit=False ) async def get_session() -> AsyncSession: async with async_session() as session: yield session test_create_one = crud_router_builder(db_session=get_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test", tags=["test"] ) test_get_data = crud_router_builder(db_session=get_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) [app.include_router(i) for i in [test_get_data, test_create_one]] client = TestClient(app) # create a sample data headers = { 'accept': '*/*', 'Content-Type': 'application/json', } data = '{ "bool_value": true, "char_value": "string", "date_value": "2021-07-26", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-26T02:17:46.846", "timestamptz_value": "2021-07-26T02:17:46.846Z", "timetz_value": "18:18:18+00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }' response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_data = response.json() dict_data = json.loads(data) sample_primary_key = response_data['primary_key'] ''' { "primary_key": 1013, "interval_value": 0, <- querying not supported "json_value": {},<- querying not supported "jsonb_value": {},<- querying not supported "array_value": [ 0 ], "array_str__value": [ "string" ] } ''' # try find the data by primary key def test_get_by_primary_key_without_any_query_param(): response = client.get(f'/test/{sample_primary_key}', headers=headers) assert response.status_code == 200 assert response.json()['primary_key'] == sample_primary_key # "bool_value": true # try find the data by primary key but false by bool def test_get_by_primary_key_with_false_bool_query_param(): response = client.get(f'/test/{sample_primary_key}?bool_value____list=false', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?bool_value____list=true', headers=headers) assert response.status_code == 200 # "char_value": "string ", # try find the data by primary key but false by char def test_get_by_primary_key_with_false_char_query_param(): response = client.get(f'/test/{sample_primary_key}?char_value____list=string1&char_value____list=string2', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?char_value____list=string&char_value____list=string1&', headers=headers) assert response.status_code == 200 # Like operator response = client.get( f'/test/{sample_primary_key}?char_value____str=string1&char_value____str=%tri%&char_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=string1&char_value____str=%tsri%&char_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 404 # Ilike operator response = client.get( f'/test/{sample_primary_key}?char_value____str=string1&char_value____str=%tRi%&char_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=string1&char_value____str=%tsri%&char_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 404 # not like operator response = client.get( f'/test/{sample_primary_key}?char_value____str=string2&char_value____str=%strg%&char_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=string%&char_value____str=%strin%&char_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 404 # not ilike operator response = client.get( f'/test/{sample_primary_key}?char_value____str=String2&char_value____str=%Strg%&char_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=STRING%&char_value____str=%TRI%&char_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 404 # match regex with case sensitive operator response = client.get( f'/test/{sample_primary_key}?char_value____str=stri.*&varchar_value____stg=str&char_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=stg.*&char_value____str=stg&char_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) assert response.status_code == 404 # match regex with case insensitive operator response = client.get( f'/test/{sample_primary_key}?char_value____str=strI.*&char_value____str=STG&char_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=stG.*&char_value____str=STG&char_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) assert response.status_code == 404 # does_not_match_regex_with_case_insensitive response = client.get( f'/test/{sample_primary_key}?char_value____str=strI.*&char_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?char_value____str=stG.*&char_value____str=STG&char_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) assert response.status_code == 200 # dose not match regex with case sensitive operator response = client.get( f'/test/{sample_primary_key}?char_value____str=stri.*&varchar_value____stg=str&char_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?char_value____str=stg.*&char_value____str=stg&char_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) assert response.status_code == 200 # similar_to response = client.get( f'/test/{sample_primary_key}?char_value____str=string&char_value____str=%(r|z)%&char_value____str_____matching_pattern=similar_to', headers=headers) assert response.status_code == 200 response = client.get( f'/test/{sample_primary_key}?char_value____str=str&char_value____str=(r|z)%&char_value____str_____matching_pattern=similar_to', headers=headers) assert response.status_code == 404 # not_similar_to response = client.get( f'/test/{sample_primary_key}?char_value____str=string%&char_value____str=%(r|z)%&char_value____str_____matching_pattern=not_similar_to', headers=headers) assert response.status_code == 404 response = client.get( f'/test/{sample_primary_key}?char_value____str=str&char_value____str=(r|z)%&char_value____str_____matching_pattern=not_similar_to', headers=headers) assert response.status_code == 200 # "float4_value": 0, # try find the data by primary key but false by float4 def test_get_by_primary_key_with_false_float4_query_param(): # from response = client.get(f'/test/{sample_primary_key}?float4_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?float4_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??float4_value____from=-2&float4_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?float4_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?float4_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?float4_value____from=0&float4_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?float4_value____from=0&float4_value____to=0&float4_value____from_____comparison_operator=Greater_than_or_equal_to&float4_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?float4_value____from=-1&float4_value____to=2&float4_value____from_____comparison_operator=Greater_than&float4_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?float4_value____from=1&float4_value____to=2&float4_value____from_____comparison_operator=Greater_than&float4_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?float4_value____from=1&float4_value____to=2&float4_value____from_____comparison_operator=Greater_than_or_equal_to&float4_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # "float8_value": 0, # try find the data by primary key but false by float8 def test_get_by_primary_key_with_false_float8_query_param(): # from response = client.get(f'/test/{sample_primary_key}?float8_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?float8_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??float8_value____from=-2&float8_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?float8_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?float8_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?float8_value____from=0&float8_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?float8_value____from=0&float8_value____to=0&float8_value____from_____comparison_operator=Greater_than_or_equal_to&float8_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?float8_value____from=-1&float8_value____to=2&float8_value____from_____comparison_operator=Greater_than&float8_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?float8_value____from=1&float8_value____to=2&float8_value____from_____comparison_operator=Greater_than&float8_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?float8_value____from=1&float8_value____to=2&float8_value____from_____comparison_operator=Greater_than_or_equal_to&float8_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by int2 # int2 0 def test_get_by_primary_key_with_false_int2_query_param(): # from response = client.get(f'/test/{sample_primary_key}?int2_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?int2_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??int2_value____from=-2&int2_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?int2_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?int2_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?int2_value____from=0&int2_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int2_value____from=0&int2_value____to=0&int2_value____from_____comparison_operator=Greater_than_or_equal_to&int2_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int2_value____from=-1&int2_value____to=2&int2_value____from_____comparison_operator=Greater_than&int2_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int2_value____from=1&int2_value____to=2&int2_value____from_____comparison_operator=Greater_than&int2_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int2_value____from=1&int2_value____to=2&int2_value____from_____comparison_operator=Greater_than_or_equal_to&int2_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by int4 # int 4 0 def test_get_by_primary_key_with_false_int4_query_param(): # from response = client.get(f'/test/{sample_primary_key}?int4_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?int4_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??int4_value____from=-2&int4_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?int4_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?int4_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?int4_value____from=0&int4_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int4_value____from=0&int4_value____to=0&int4_value____from_____comparison_operator=Greater_than_or_equal_to&int4_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int4_value____from=-1&int4_value____to=2&int4_value____from_____comparison_operator=Greater_than&int4_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int4_value____from=1&int4_value____to=2&int4_value____from_____comparison_operator=Greater_than&int4_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int4_value____from=1&int4_value____to=2&int4_value____from_____comparison_operator=Greater_than_or_equal_to&int4_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by int8 # int 8 0 def test_get_by_primary_key_with_false_int8_query_param(): # from response = client.get(f'/test/{sample_primary_key}?int8_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?int8_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??int8_value____from=-2&int8_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?int8_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?int8_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?int8_value____from=0&int8_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int8_value____from=0&int8_value____to=0&int8_value____from_____comparison_operator=Greater_than_or_equal_to&int8_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?int8_value____from=-1&int8_value____to=2&int8_value____from_____comparison_operator=Greater_than&int8_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int8_value____from=1&int8_value____to=2&int8_value____from_____comparison_operator=Greater_than&int8_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?int8_value____from=1&int8_value____to=2&int8_value____from_____comparison_operator=Greater_than_or_equal_to&int8_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by numeric # numeric 0 def test_get_by_primary_key_with_false_numeric_query_param(): # from response = client.get(f'/test/{sample_primary_key}?numeric_value____from=1', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?numeric_value____to=-1', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??numeric_value____from=-2&numeric_value____to=-1', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?numeric_value____from=0', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?numeric_value____to=0', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?numeric_value____from=0&numeric_value____to=0', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?numeric_value____from=0&numeric_value____to=0&numeric_value____from_____comparison_operator=Greater_than_or_equal_to&numeric_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get( f'/test/{sample_primary_key}?numeric_value____from=-1&numeric_value____to=2&numeric_value____from_____comparison_operator=Greater_than&numeric_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?numeric_value____from=1&numeric_value____to=2&numeric_value____from_____comparison_operator=Greater_than&numeric_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get( f'/test/{sample_primary_key}?numeric_value____from=1&numeric_value____to=2&numeric_value____from_____comparison_operator=Greater_than_or_equal_to&numeric_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 # try find the data by primary key but false by text # "text_value": "string", def test_get_by_primary_key_with_false_text_query_param(): response = client.get(f'/test/{sample_primary_key}?text_value____list=string1&text_value____list=string2', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?text_value____list=string&text_value____list=string1&', headers=headers) assert response.status_code == 200 # Like operator response = client.get(f'/test/{sample_primary_key}?text_value____str=string1&text_value____str=%tri%&text_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?text_value____str=string1&text_value____str=%tsri%&text_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 404 # Ilike operator response = client.get(f'/test/{sample_primary_key}?text_value____str=string1&text_value____str=%tRi%&text_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?text_value____str=string1&text_value____str=%tsri%&text_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 404 # not like operator response = client.get(f'/test/{sample_primary_key}?text_value____str=string2&text_value____str=%strg%&text_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?text_value____str=string&text_value____str=%strin%&text_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 404 # not ilike operator response = client.get(f'/test/{sample_primary_key}?text_value____str=String2&text_value____str=%Strg%&text_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?text_value____str=STRING&text_value____str=%TRI%&text_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 404 # match regex with case sensitive operator response = client.get(f'/test/{sample_primary_key}?text_value____str=stri.*&varchar_value____stg=str&text_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?text_value____str=stg.*&text_value____str=stg&text_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) assert response.status_code == 404 # match regex with case insensitive operator response = client.get(f'/test/{sample_primary_key}?text_value____str=strI.*&text_value____str=STG&text_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?text_value____str=stG.*&text_value____str=STG&text_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) assert response.status_code == 404 # does_not_match_regex_with_case_insensitive response = client.get(f'/test/{sample_primary_key}?text_value____str=strI.*&text_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?text_value____str=stG.*&text_value____str=STG&text_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) assert response.status_code == 200 # dose not match regex with case sensitive operator response = client.get(f'/test/{sample_primary_key}?text_value____str=stri.*&varchar_value____stg=str&text_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?text_value____str=stg.*&text_value____str=stg&text_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) assert response.status_code == 200 # similar_to response = client.get(f'/test/{sample_primary_key}?text_value____str=string&text_value____str=%(r|z)%&text_value____str_____matching_pattern=similar_to', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?text_value____str=str&text_value____str=(r|z)%&text_value____str_____matching_pattern=similar_to', headers=headers) assert response.status_code == 404 # not_similar_to response = client.get(f'/test/{sample_primary_key}?text_value____str=string&text_value____str=%(r|z)%&text_value____str_____matching_pattern=not_similar_to', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?text_value____str=str&text_value____str=(r|z)%&text_value____str_____matching_pattern=not_similar_to', headers=headers) assert response.status_code == 200 # try find the data by primary key but false by uuid def test_get_by_primary_key_with_false_uuid_query_param(): # In operator response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa6&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afb6', headers=headers) assert response.status_code == 404 # not In operator response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa6&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list_____comparison_operator=Not_in', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afb6&uuid_value____list_____comparison_operator=Not_in', headers=headers) assert response.status_code == 200 # Equal operator response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa6&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list_____comparison_operator=Equal', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afb6&uuid_value____list_____comparison_operator=Equal', headers=headers) assert response.status_code == 404 # not Equal operator response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa6&uuid_value____list_____comparison_operator=Not_equal', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afa9&uuid_value____list=3fa85f64-5717-4562-b3fc-2c963f66afb6&uuid_value____list_____comparison_operator=Not_equal', headers=headers) assert response.status_code == 200 # try find the data by primary key but false by varchar def test_get_by_primary_key_with_false_varchar_query_param(): response = client.get(f'/test/{sample_primary_key}?varchar_value____list=string1&varchar_value____list=string2', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?varchar_value____list=string&varchar_value____list=string1&', headers=headers) assert response.status_code == 200 # Like operator response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string1&varchar_value____str=%tri%&varchar_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string1&varchar_value____str=%tsri%&varchar_value____str_____matching_pattern=case_sensitive', headers=headers) assert response.status_code == 404 # Ilike operator response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string1&varchar_value____str=%tRi%&varchar_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string1&varchar_value____str=%tsri%&varchar_value____str_____matching_pattern=case_insensitive', headers=headers) assert response.status_code == 404 # not like operator response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string2&varchar_value____str=%strg%&varchar_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string&varchar_value____str=%strin%&varchar_value____str_____matching_pattern=not_case_sensitive', headers=headers) assert response.status_code == 404 # not ilike operator response = client.get(f'/test/{sample_primary_key}?varchar_value____str=String2&varchar_value____str=%Strg%&varchar_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=STRING&varchar_value____str=%TRI%&varchar_value____str_____matching_pattern=not_case_insensitive', headers=headers) assert response.status_code == 404 # match regex with case sensitive operator response = client.get(f'/test/{sample_primary_key}?varchar_value____str=stri.*&varchar_value____stg=str&varchar_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=stg.*&varchar_value____str=stg&varchar_value____str_____matching_pattern=match_regex_with_case_sensitive', headers=headers) assert response.status_code == 404 # match regex with case insensitive operator response = client.get(f'/test/{sample_primary_key}?varchar_value____str=strI.*&varchar_value____str=STG&varchar_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=stG.*&varchar_value____str=STG&varchar_value____str_____matching_pattern=match_regex_with_case_insensitive', headers=headers) assert response.status_code == 404 # does_not_match_regex_with_case_insensitive response = client.get(f'/test/{sample_primary_key}?varchar_value____str=strI.*&varchar_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=stG.*&varchar_value____str=STG&varchar_value____str_____matching_pattern=does_not_match_regex_with_case_insensitive', headers=headers) assert response.status_code == 200 # dose not match regex with case sensitive operator response = client.get(f'/test/{sample_primary_key}?varchar_value____str=stri.*&varchar_value____stg=str&varchar_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=stg.*&varchar_value____str=stg&varchar_value____str_____matching_pattern=does_not_match_regex_with_case_sensitive', headers=headers) assert response.status_code == 200 # similar_to response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string&varchar_value____str=%(r|z)%&varchar_value____str_____matching_pattern=similar_to', headers=headers) assert response.status_code == 200 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=str&varchar_value____str=(r|z)%&varchar_value____str_____matching_pattern=similar_to', headers=headers) assert response.status_code == 404 # not_similar_to response = client.get(f'/test/{sample_primary_key}?varchar_value____str=string&varchar_value____str=%(r|z)%&varchar_value____str_____matching_pattern=not_similar_to', headers=headers) assert response.status_code == 404 response = client.get(f'/test/{sample_primary_key}?varchar_value____str=str&varchar_value____str=(r|z)%&varchar_value____str_____matching_pattern=not_similar_to', headers=headers) assert response.status_code == 200 # query by range of date field def test_get_by_primary_key_with_false_date_range_query_param(): # from response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-27', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?date_value____to=2021-07-24', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}??date_value____from=2021-07-21&date_value____to=2021-07-24', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-24', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?date_value____to=2021-07-27', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-24&date_value____to=2021-07-27', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-26&date_value____to=2021-07-26&date_value____from_____comparison_operator=Greater_than_or_equal_to&date_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-25&date_value____to=2021-07-27&date_value____from_____comparison_operator=Greater_than&date_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-26&date_value____to=2021-07-26&date_value____from_____comparison_operator=Greater_than&date_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?date_value____from=2021-07-27&date_value____to=2021-07-29&date_value____from_____comparison_operator=Greater_than_or_equal_to&date_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 def test_get_by_primary_key_with_false_time_range_query_param(): # from response = client.get(f'/test/{sample_primary_key}?time_value____from=19:18:18', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?time_value____to=17:18:18', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}?time_value____from=10:18:18&time_value____to=17:18:18', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?time_value____from=10:18:18', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?time_value____to=19:18:18', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?time_value____from=10:18:18&time_value____to=19:18:18', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?time_value____from=18:18:18&time_value____to=18:18:18&time_value____from_____comparison_operator=Greater_than_or_equal_to&time_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?time_value____from=18:18:17&time_value____to=18:18:19&time_value____from_____comparison_operator=Greater_than&time_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?time_value____from=18:18:18&time_value____to=18:18:18&time_value____from_____comparison_operator=Greater_than&time_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?time_value____from=19:18:18&time_value____to=19:19:18&time_value____from_____comparison_operator=Greater_than_or_equal_to&time_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 def test_get_by_primary_key_with_false_timestamp_range_query_param(): # "timestamp_value": "2021-07-26T02:17:46.846000", # from response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-27T02:17:46.846000', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?timestamp_value____to=2021-07-25T02:17:46.846000', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-20T02:17:46.846000×tamp_value____to=2021-07-25T02:17:46.846000', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-24T02:17:46.846000', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?timestamp_value____to=2021-07-28T02:17:46.846000', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-24T02:17:46.846000×tamp_value____to=2021-07-28T02:17:46.846000', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-26T02:17:46.846×tamp_value____to=2021-07-26T02:17:46.846×tampt_value____from_____comparison_operator=Greater_than_or_equal_to×tampt_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-26T02:17:46.746×tamp_value____to=2021-07-26T02:17:46.946×tampt_value____from_____comparison_operator=Greater_than×tampt_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-26T02:17:46.846×tamp_value____to=2021-07-26T02:17:46.946×tamp_value____from_____comparison_operator=Greater_than×tamp_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamp_value____from=2021-07-26T02:17:46.856×tamp_value____to=2021-07-26T02:17:46.986×tamp_value____from_____comparison_operator=Greater_than_or_equal_to×tamp_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 def test_get_by_primary_key_with_false_timetz_range_query_param(): # from response = client.get(f'/test/{sample_primary_key}?timetz_value____from=19%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?timetz_value____to=17%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}?timetz_value____from=16%3A18%3A18%2B00%3A00&timetz_value____to=17%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?timetz_value____from=17%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?timetz_value____to=19%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?timetz_value____from=16%3A18%3A18%2B00%3A00&timetz_value____to=19%3A18%3A18%2B00%3A00', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timetz_value____from_____comparison_operator=Greater_than&timetz_value____to_____comparison_operator=Less_than&timetz_value____from=17%3A18%3A18%2B00&timetz_value____to=19%3A18%3A18%2B00', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timetz_value____from_____comparison_operator=Greater_than_or_equal_to&timetz_value____to_____comparison_operator=Less_than_or_equal_to&timetz_value____from=18%3A18%3A18%2B00&timetz_value____to=18%3A19%3A18%2B00', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timetz_value____from_____comparison_operator=Greater_than&timetz_value____to_____comparison_operator=Less_than&timetz_value____from=16%3A18%3A18%2B00&timetz_value____to=18%3A18%3A18%2B00', headers=headers) assert response.status_code == 404 # failure from - to with special operator response = client.get(f'/test/{sample_primary_key}?timetz_value____from_____comparison_operator=Greater_than_or_equal_to&timetz_value____to_____comparison_operator=Less_than_or_equal_to&timetz_value____from=16%3A18%3A18%2B00&timetz_value____to=17%3A19%3A18%2B00', headers=headers) assert response.status_code == 404 def test_get_by_primary_key_with_false_timestamptz_range_query_param(): # "timestamp_value": "2021-07-26T02:17:46.846000", # from response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-27T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 404 # to response = client.get(f'/test/{sample_primary_key}?timestamptz_value____to=2021-07-25T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 404 # from - to response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-27T02%3A17%3A46.846000%2B00%3A00×tamptz_value____to=2021-07-28T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 404 # success from response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-20T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 200 # success to response = client.get(f'/test/{sample_primary_key}?timestamptz_value____to=2021-07-29T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 200 # success from - to response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-20T02%3A17%3A46.846000%2B00%3A00×tamptz_value____to=2021-07-27T02%3A17%3A46.846000%2B00%3A00', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-26T02%3A17%3A46.846Z×tamptz_value____to=2021-07-26T02%3A17%3A46.846Z×tamptz_value____from_____comparison_operator=Greater_than_or_equal_to×tamptz_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 200 # success from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-26T02%3A17%3A46.800Z×tamptz_value____to=2021-07-26T02%3A17%3A46.946Z×tamptz_value____from_____comparison_operator=Greater_than×tamptz_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 200 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-26T02%3A17%3A46.846Z×tamptz_value____to=2021-07-26T02%3A17%3A46.900Z×tamptz_value____from_____comparison_operator=Greater_than×tamptz_value____to_____comparison_operator=Less_than', headers=headers) assert response.status_code == 404 # failed from - to with special operator response = client.get(f'/test/{sample_primary_key}?timestamptz_value____from=2021-07-26T02%3A17%3A46.847Z×tamptz_value____to=2021-07-26T02%3A17%3A46.946Z×tamptz_value____from_____comparison_operator=Greater_than_or_equal_to×tamptz_value____to_____comparison_operator=Less_than_or_equal_to', headers=headers) assert response.status_code == 404 ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test_async/test_other_default_value.py ================================================ import asyncio import json import os import uuid from copy import deepcopy from datetime import datetime, timezone, date, timedelta from http import HTTPStatus from urllib.parse import urlencode from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text, Table from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_ASYNC_URL', 'postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession engine = create_async_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(autocommit=False, autoflush=False, bind=engine, class_=AsyncSession) async def get_transaction_session() -> AsyncSession: async with async_session() as session: yield session UUIDTable = Table( 'test_default_value', metadata, Column('primary_key', UUID, primary_key=True, server_default=text("uuid_generate_v4()")), Column('bool_value', Boolean, nullable=False, default=False), Column('bytea_value', LargeBinary), Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float(53), nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL), Column('json_value', JSON), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric), Column('text_value', Text), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), UniqueConstraint('primary_key', 'int4_value', 'float4_value') ) def setup_module(module): async def create_table(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) loop = asyncio.get_event_loop() loop.run_until_complete(create_table()) route_1 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.FIND_MANY, CrudMethods.UPSERT_MANY, CrudMethods.UPDATE_ONE, CrudMethods.UPDATE_MANY, CrudMethods.PATCH_MANY, CrudMethods.PATCH_ONE, CrudMethods.DELETE_MANY, CrudMethods.DELETE_ONE, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) route_2 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.UPSERT_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_2", tags=["test"] ) route_3 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_3", tags=["test"] ) [app.include_router(i) for i in [route_1, route_2, route_3]] client = TestClient(app) def test_get_one_data_and_create_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() find_target = create_response['primary_key'] response = client.get(f'/test/{find_target}', headers=headers, data=data) assert response.status_code == 200 assert response.json() == create_response create_response.pop('primary_key') query_param = urlencode(create_response) response = client.get(f'/test/{find_target}?{query_param}', headers=headers, data=data) assert response.status_code == 200 def test_get_many_data_and_create_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '''{ "insert": [ { "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00","varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }, { "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] },{ "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] } ] }''' data_dict = json.loads(data)['insert'] response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_dict): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_update_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() created_primary_key = create_response['primary_key'] update_data = { "bool_value":False,"char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} query_param = urlencode(update_data) response = client.put(f'/test/{created_primary_key}?{query_param}', data=json.dumps(update_data)) update_data["bool_value"] = False response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_update_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, { "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params)+f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value":False,"char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test?{query_string}', data=json.dumps(update_data)) update_data["bool_value"] = False response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: assert k[i] == update_data[i] def test_patch_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) update_data = {"bool_value": False} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(params) update_data = {"char_value": "string_u "} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(params) update_data = {"date_value": "2022-07-24"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(params) update_data = {"char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) update_data['bool_value'] = False response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_patch_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, { "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value": True, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00","varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test?{query_string}', data=json.dumps(update_data)) update_data['bool_value'] = True response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_delete_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) response = client.delete(f'/test/{primary_key}?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_delete_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{ "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, { "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, { "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": False, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' response = client.delete(f'/test?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_post_redirect_get_data(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_3', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() response_data['bool_value'] = False assert 'primary_key' in response_data for k, v in response_data.items(): if k in change: if isinstance(v, str): v = v.strip() response_ = json.dumps(v).strip() request_ = json.dumps(change[k]).strip() assert request_ == response_ return response_data def test_upsert_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 10 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k,v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 # conflict upsert_data = deepcopy(updated_data) upsert_data['on_conflict'] = {'update_columns':['numeric_value']} response = client.post('/test_2', headers=headers, data=json.dumps(dict(upsert_data, **json.loads(data)))) assert response.status_code == 201 # create response = client.post('/test_2', headers=headers, data=json.dumps(dict(updated_data, **json.loads(data)))) assert response.status_code == 409 def test_upsert_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 12.784 ,"int2_value": 0, "int4_value": 10 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k,v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 # conflict upsert_data = deepcopy(updated_data) upsert_data['on_conflict'] = {'update_columns':['numeric_value']} response = client.post('/test_2', headers=headers, data=json.dumps(dict(upsert_data, **json.loads(data)))) assert response.status_code == 201 # create response = client.post('/test_2', headers=headers, data=json.dumps(dict(updated_data, **json.loads(data)))) assert response.status_code == 409 def teardown_module(module): async def create_table(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.drop_all) loop = asyncio.get_event_loop() loop.run_until_complete(create_table()) ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test_async/test_other_no_alias.py ================================================ import asyncio import json import os import uuid from copy import deepcopy from datetime import datetime, timezone, date, timedelta from http import HTTPStatus from urllib.parse import urlencode from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, Table,String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_ASYNC_URL', 'postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine engine = create_async_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(autocommit=False, autoflush=False, bind=engine, class_=AsyncSession) async def get_transaction_session() -> AsyncSession: async with async_session() as session: yield session UUIDTable = Table( 'test_no_alias', metadata, Column('id', UUID, primary_key=True, server_default=text("uuid_generate_v4()")), Column('bool_value', Boolean, nullable=False, server_default=text("false")), Column('bytea_value', LargeBinary), Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float(53), nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL), Column('json_value', JSON), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric), Column('text_value', Text), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), UniqueConstraint('id', 'int4_value', 'float4_value') ) def setup_module(module): async def create_table(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) loop = asyncio.get_event_loop() loop.run_until_complete(create_table()) route_1 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.FIND_MANY, CrudMethods.UPSERT_MANY, CrudMethods.UPDATE_ONE, CrudMethods.UPDATE_MANY, CrudMethods.PATCH_MANY, CrudMethods.PATCH_ONE, CrudMethods.DELETE_MANY, CrudMethods.DELETE_ONE, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test", tags=["test"] ) route_2 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.UPSERT_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_2", async_mode=True, tags=["test"] ) route_3 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test_3", tags=["test"] ) [app.include_router(i) for i in [route_1, route_2, route_3]] client = TestClient(app) def test_get_one_data_and_create_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() find_target = create_response['id'] response = client.get(f'/test/{find_target}', headers=headers, data=data) assert response.status_code == 200 assert response.json() == create_response create_response.pop('id') query_param = urlencode(create_response) response = client.get(f'/test/{find_target}?{query_param}', headers=headers, data=data) assert response.status_code == 200 def test_get_many_data_and_create_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '''{ "insert": [ { "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00","varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }, { "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] },{ "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] } ] }''' data_dict = json.loads(data)['insert'] response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_dict): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_update_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() created_primary_key = create_response['id'] update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} query_param = urlencode(update_data) response = client.put(f'/test/{created_primary_key}?{query_param}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_update_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['id'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params)+f'&id____list={primary_key_list[0]}&id____list={primary_key_list[1]}&id____list={primary_key_list[2]}' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: assert k[i] == update_data[i] def test_patch_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['id'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) update_data = {"bool_value": False} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(params) update_data = {"char_value": "string_u "} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(params) update_data = {"date_value": "2022-07-24"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(params) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_patch_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['id'] for i in insert_response_data] params = { "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&id____list={primary_key_list[0]}&id____list={primary_key_list[1]}&id____list={primary_key_list[2]}' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00","varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_delete_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['id'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) response = client.delete(f'/test/{primary_key}?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_delete_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['id'] for i in insert_response_data] params = { "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&id____list={primary_key_list[0]}&id____list={primary_key_list[1]}&id____list={primary_key_list[2]}' response = client.delete(f'/test?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_post_redirect_get_data(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} bool_value_change = False char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_3', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() assert 'id' in response_data for k, v in response_data.items(): if k in change: if isinstance(v, str): v = v.strip() response_ = json.dumps(v).strip() request_ = json.dumps(change[k]).strip() assert request_ == response_ return response_data def test_upsert_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 10 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k,v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 # conflict upsert_data = deepcopy(updated_data) upsert_data['on_conflict'] = {'update_columns':['numeric_value']} response = client.post('/test_2', headers=headers, data=json.dumps(dict(upsert_data, **json.loads(data)))) assert response.status_code == 201 # create response = client.post('/test_2', headers=headers, data=json.dumps(dict(updated_data, **json.loads(data)))) assert response.status_code == 409 ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test_async/test_other_single_unique.py ================================================ import asyncio import json import os import uuid from copy import deepcopy from datetime import datetime, timezone, date, timedelta from http import HTTPStatus from urllib.parse import urlencode from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger,Table, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_ASYNC_URL', 'postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine engine = create_async_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(autocommit=False, autoflush=False, bind=engine, class_=AsyncSession) async def get_transaction_session() -> AsyncSession: async with async_session() as session: yield session UUIDTable = Table( 'test_single_unique_table', metadata, Column('id', UUID, primary_key=True, server_default=text("uuid_generate_v4()")), Column('bool_value', Boolean, nullable=False, server_default=text("false")), Column('bytea_value', LargeBinary), Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float(53), nullable=False,unique=True), Column('float8_value', Float(53), nullable=True, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=True), Column('int4_value', Integer, nullable=True), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL), Column('json_value', JSON), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric), Column('text_value', Text), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), ) def setup_module(module): async def create_table(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) loop = asyncio.get_event_loop() loop.run_until_complete(create_table()) route_1 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.FIND_MANY, CrudMethods.UPSERT_MANY, CrudMethods.UPDATE_ONE, CrudMethods.UPDATE_MANY, CrudMethods.PATCH_MANY, CrudMethods.PATCH_ONE, CrudMethods.DELETE_MANY, CrudMethods.DELETE_ONE, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test", tags=["test"] ) route_2 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.UPSERT_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_2", async_mode=True, tags=["test"] ) route_3 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test_3", tags=["test"] ) [app.include_router(i) for i in [route_1, route_2, route_3]] client = TestClient(app) def test_get_one_data_and_create_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0.443}' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() find_target = create_response['id'] response = client.get(f'/test/{find_target}', headers=headers, data=data) assert response.status_code == 200 assert response.json() == create_response create_response.pop('id') query_param = urlencode(create_response) response = client.get(f'/test/{find_target}?{query_param}', headers=headers, data=data) assert response.status_code == 200 def test_get_many_data_and_create_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '''{ "insert": [ { "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0.12, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00","varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }, { "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 1.2, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] },{ "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 9.3, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] } ] }''' data_dict = json.loads(data)['insert'] response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_dict): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_update_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0.98}' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() created_primary_key = create_response['id'] update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 12.7, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} query_param = urlencode(update_data) response = client.put(f'/test/{created_primary_key}?{query_param}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_update_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 3.5, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 3.6, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 3.7, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['id'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 200, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params)+f'&id____list={primary_key_list[0]}&id____list={primary_key_list[1]}&id____list={primary_key_list[2]}&float4_value____list=3.5&float4_value____list=3.6&float4_value____list=3.7' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.58, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test?{query_string}', data=json.dumps(update_data)) # FIXME: update the unique column will conflict, it may not a issue, because it should input all columns, you can use the patch assert response.status_code == 409 # response_data = response.json() # assert len(response_data) == 3 # for k in response_data: # for i in update_data: # assert k[i] == update_data[i] def test_patch_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 5.78, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['id'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 500, "float4_value____list": 5.78, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) update_data = {"bool_value": False} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(params) update_data = {"char_value": "string_u "} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(params) update_data = {"date_value": "2022-07-24"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(params) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 1.70, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_patch_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.91, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.92, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.93, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['id'] for i in insert_response_data] params = { "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 500, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&id____list={primary_key_list[0]}&id____list={primary_key_list[1]}&id____list={primary_key_list[2]}&float4_value____list=0.91&float4_value____list=0.92&float4_value____list=0.93' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00","varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_delete_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 2.54, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['id'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 500, "float4_value____list": 2.54, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) response = client.delete(f'/test/{primary_key}?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_delete_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.875, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.876, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0.877, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['id'] for i in insert_response_data] params = { "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 500, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&id____list={primary_key_list[0]}&id____list={primary_key_list[1]}&id____list={primary_key_list[2]}&float4_value____list=0.875&float4_value____list=0.876&&float4_value____list=0.877' response = client.delete(f'/test?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_post_redirect_get_data(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} bool_value_change = False char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 55.7 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_3', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() assert 'id' in response_data for k, v in response_data.items(): if k in change: if isinstance(v, str): v = v.strip() response_ = json.dumps(v).strip() request_ = json.dumps(change[k]).strip() assert request_ == response_ return response_data def test_upsert_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 12.784}' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k,v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 # conflict upsert_data = deepcopy(updated_data) upsert_data['on_conflict'] = {'update_columns':['numeric_value']} response = client.post('/test_2', headers=headers, data=json.dumps(dict(upsert_data, **json.loads(data)))) assert response.status_code == 201 # create response = client.post('/test_2', headers=headers, data=json.dumps(dict(updated_data, **json.loads(data)))) assert response.status_code == 409 def teardown_module(module): async def create_table(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.drop_all) loop = asyncio.get_event_loop() loop.run_until_complete(create_table()) ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test_async/test_other_uuid_primary.py ================================================ import asyncio import json import os import uuid from copy import deepcopy from datetime import datetime, timezone, date, timedelta from http import HTTPStatus from urllib.parse import urlencode from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Table,Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from starlette.testclient import TestClient from src.fastapi_quickcrud import sqlalchemy_to_pydantic from src.fastapi_quickcrud.crud_router import crud_router_builder from src.fastapi_quickcrud.misc.type import CrudMethods TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_ASYNC_URL', 'postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres') app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine engine = create_async_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(autocommit=False, autoflush=False, bind=engine, class_=AsyncSession) async def get_transaction_session() -> AsyncSession: async with async_session() as session: yield session UUIDTable = Table( 'test_uuid_primary', metadata, Column('primary_key', UUID, primary_key=True, server_default=text("uuid_generate_v4()")), Column('bool_value', Boolean, nullable=False, server_default=text("false")), Column('bytea_value', LargeBinary), Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float(53), nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL), Column('json_value', JSON), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric), Column('text_value', Text), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), UniqueConstraint('primary_key', 'int4_value', 'float4_value') ) def setup_module(module): async def create_table(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) loop = asyncio.get_event_loop() loop.run_until_complete(create_table()) route_1 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.FIND_MANY, CrudMethods.UPSERT_MANY, CrudMethods.UPDATE_ONE, CrudMethods.UPDATE_MANY, CrudMethods.PATCH_MANY, CrudMethods.PATCH_ONE, CrudMethods.DELETE_MANY, CrudMethods.DELETE_ONE, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test", tags=["test"] ) route_2 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.UPSERT_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_2", async_mode=True, tags=["test"] ) route_3 = crud_router_builder(db_session=get_transaction_session, db_model=UUIDTable, crud_methods=[ CrudMethods.FIND_ONE, CrudMethods.POST_REDIRECT_GET, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test_3", tags=["test"] ) [app.include_router(i) for i in [route_1, route_2, route_3]] client = TestClient(app) def test_get_one_data_and_create_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() find_target = create_response['primary_key'] response = client.get(f'/test/{find_target}', headers=headers, data=data) assert response.status_code == 200 assert response.json() == create_response create_response.pop('primary_key') query_param = urlencode(create_response) response = client.get(f'/test/{find_target}?{query_param}', headers=headers, data=data) assert response.status_code == 200 def test_get_many_data_and_create_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '''{ "insert": [ { "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00","varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }, { "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] },{ "bool_value": true, "char_value": "string ", "date_value": "2021-07-23", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-23T02:38:24.963000", "timestamptz_value": "2021-07-23T02:38:24.963000+00:00", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] } ] }''' data_dict = json.loads(data)['insert'] response = client.post('/test', headers=headers, data=data) assert response.status_code == 201 response_result = response.json() for index, value in enumerate(data_dict): res_result_by_index = response_result[index] for k, v in value.items(): assert res_result_by_index[k] == v def test_update_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 0 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() created_primary_key = create_response['primary_key'] update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} query_param = urlencode(update_data) response = client.put(f'/test/{created_primary_key}?{query_param}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_update_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params)+f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: assert k[i] == update_data[i] def test_patch_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) update_data = {"bool_value": False} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(params) update_data = {"char_value": "string_u "} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(params) update_data = {"date_value": "2022-07-24"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(params) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] def test_patch_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00","varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_delete_one_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i['primary_key'] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(params) response = client.delete(f'/test/{primary_key}?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '1' def test_delete_many_data(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i['primary_key'] for i in insert_response_data] params = { "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode( params) + f'&primary_key____list={primary_key_list[0]}&primary_key____list={primary_key_list[1]}&primary_key____list={primary_key_list[2]}' response = client.delete(f'/test?{query_string}') assert response.status_code == 200 assert response.headers['x-total-count'] == '3' def test_post_redirect_get_data(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} bool_value_change = False char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_3', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() assert 'primary_key' in response_data for k, v in response_data.items(): if k in change: if isinstance(v, str): v = v.strip() response_ = json.dumps(v).strip() request_ = json.dumps(change[k]).strip() assert request_ == response_ return response_data def test_upsert_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = '{"float4_value": 0, "int2_value": 0, "int4_value": 10 }' response = client.post('/test_2', headers=headers, data=data) assert response.status_code == 201 create_response = response.json() updated_data = {} for k,v in create_response.items(): if k not in data: updated_data[k] = v updated_data['numeric_value'] = 100 # conflict upsert_data = deepcopy(updated_data) upsert_data['on_conflict'] = {'update_columns':['numeric_value']} response = client.post('/test_2', headers=headers, data=json.dumps(dict(upsert_data, **json.loads(data)))) assert response.status_code == 201 # create response = client.post('/test_2', headers=headers, data=json.dumps(dict(updated_data, **json.loads(data)))) assert response.status_code == 409 ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test_async/test_patch_many_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy_table.api_test_async import get_transaction_session, app, \ UntitledTable256 # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # create_one_model = api_model[CrudMethods.UPSERT_ONE].__dict__ # assert create_one_model['requestModel'] or create_one_model['responseModel'] # create_one_request_model = deepcopy(create_one_model['requestModel'].__dict__['__fields__']) # create_one_response_model = deepcopy(create_one_model['responseModel'].__dict__['__fields__']) # Request Test # assert create_one_request_model.pop('on_conflict', False) # for k, v in create_one_request_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Response Test # for k, v in create_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, async_mode=True, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_creation_one", tags=["test"] ) # # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # create_many_model = api_model[CrudMethods.UPSERT_MANY].__dict__ # assert create_many_model['requestModel'] or create_many_model['responseModel'] # create_many_request_model = deepcopy(create_many_model['requestModel'].__dict__['__fields__']) # create_many_response_model = deepcopy(create_many_model['responseModel'].__dict__['__fields__']) # # # Request Model Test # assert create_many_request_model.pop('on_conflict', None) # insert_many_model = create_many_request_model['insert'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in insert_many_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # # # Response Model Test # for k, v in create_many_response_model.items(): # create_many_response_model_item = v.type_.__dict__['__fields__'] # for k, v in create_many_response_model_item.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_creation_many", async_mode=True, tags=["test"] ) # Response Mode Test # response_many = create_many_response_model['__root__'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in response_many.items(): # assert not v.required # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # post_redirect_get_model = api_model[CrudMethods.POST_REDIRECT_GET].__dict__ # assert post_redirect_get_model['requestModel'] or post_redirect_get_model['responseModel'] # post_redirect_get_request_model = deepcopy(post_redirect_get_model['requestModel'].__dict__['__fields__']) # post_redirect_get_response_model = deepcopy(post_redirect_get_model['responseModel'].__dict__['__fields__']) # Request Model Test # for k, v in post_redirect_get_request_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Response Model Test # for k, v in post_redirect_get_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # for k, v in post_redirect_get_response_model.items(): # assert v.required test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_post_direct_get", async_mode=True, tags=["test"] ) # # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # # FIXME some thing may not require # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"], async_mode=True, ) test_patch_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.PATCH_MANY ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test_patch_many", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_patch_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = 'primary_key' unique_fields = ['primary_key', 'int4_value', 'float4_value'] def test_create_many_and_patch_many(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test_patch_many?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test_async/test_patch_one_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy_table.api_test_async import get_transaction_session, app, \ UntitledTable256 test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test_creation_one", tags=["test"] ) # # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # create_many_model = api_model[CrudMethods.UPSERT_MANY].__dict__ # assert create_many_model['requestModel'] or create_many_model['responseModel'] # create_many_request_model = deepcopy(create_many_model['requestModel'].__dict__['__fields__']) # create_many_response_model = deepcopy(create_many_model['responseModel'].__dict__['__fields__']) # # # Request Model Test # assert create_many_request_model.pop('on_conflict', None) # insert_many_model = create_many_request_model['insert'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in insert_many_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # # # Response Model Test # for k, v in create_many_response_model.items(): # create_many_response_model_item = v.type_.__dict__['__fields__'] # for k, v in create_many_response_model_item.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, async_mode=True, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_creation_many", tags=["test"] ) # Response Mode Test # response_many = create_many_response_model['__root__'].sub_fields[0].outer_type_.__dict__['__fields__'] # for k, v in response_many.items(): # assert not v.required # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # post_redirect_get_model = api_model[CrudMethods.POST_REDIRECT_GET].__dict__ # assert post_redirect_get_model['requestModel'] or post_redirect_get_model['responseModel'] # post_redirect_get_request_model = deepcopy(post_redirect_get_model['requestModel'].__dict__['__fields__']) # post_redirect_get_response_model = deepcopy(post_redirect_get_model['responseModel'].__dict__['__fields__']) # Request Model Test # for k, v in post_redirect_get_request_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Response Model Test # for k, v in post_redirect_get_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # for k, v in post_redirect_get_response_model.items(): # assert v.required test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test_post_direct_get", tags=["test"] ) # # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # # FIXME some thing may not require # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test", tags=["test"] ) # # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # # FIXME some thing may not require # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_update_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.PATCH_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test_patch_one", tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_update_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = 'primary_key' unique_fields = ['primary_key', 'int4_value', 'float4_value'] def test_create_one_and_patch_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False} response = client.patch(f'/test_patch_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['bool_value____list'] = False query_string = urlencode(OrderedDict(**params)) update_data = {"char_value": "string_u "} response = client.patch(f'/test_patch_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['char_value____str'] = "string_u " query_string = urlencode(OrderedDict(**params)) update_data = {"date_value": "2022-07-24"} # update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, # "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, # "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, # "text_value": "string_update", # "timestamp_value": "2022-07-24T02:54:53.285000", # "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", # "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", # "array_value": [1, 2, 3, 4, 5], # "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test_patch_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] params['date_value____from'] = "2022-07-23" params['date_value____to'] = "2022-07-25" query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.patch(f'/test_patch_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: assert response_data[i] == update_data[i] ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test_async/test_post_redirect_get_api.py ================================================ import json import uuid from datetime import date, timedelta, datetime, timezone from http import HTTPStatus from starlette.testclient import TestClient from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy_table.api_test_async import get_transaction_session, app, \ UntitledTable256 test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_post_direct_get", async_mode=True, tags=["test"] ) # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_post_direct_get", async_mode=True, tags=["test"] ) test_post_and_redirect_get_without_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_post_direct_get_without_get", async_mode=True, tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_get_data,test_post_and_redirect_get_without_get]] client = TestClient(app) primary_key_name = 'primary_key' unique_fields = ['primary_key', 'int4_value', 'float4_value'] # Post Redirect Get API Test def test_create_one_but_no_follow_redirect(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } data = '{ "bool_value": true, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ] }' response = client.post('/test_post_direct_get', headers=headers, data=data, allow_redirects=False) assert response.status_code == HTTPStatus.SEE_OTHER def test_create_one_with_redirect(): headers = { 'accept': '*/*', 'Content-Type': 'application/json', } change = {} bool_value_change = False char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' uuid_value_change = str(uuid.uuid4()) varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['uuid_value'] = uuid_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data_ = json.dumps(change) response = client.post('/test_post_direct_get', headers=headers, data=data_, allow_redirects=True) assert response.status_code == HTTPStatus.OK response_data = response.json() assert primary_key_name in response_data for k, v in response_data.items(): if k in change: if isinstance(v, str): v = v.strip() response_ = json.dumps(v).strip() request_ = json.dumps(change[k]).strip() assert request_ == response_ return response_data def test_create_but_conflict(): data = test_create_one_with_redirect() headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.post('/test_post_direct_get', headers=headers, data=json.dumps(data), allow_redirects=True) assert response.status_code == HTTPStatus.CONFLICT def test_create_but_not_found_get_api(): change = {} bool_value_change = False char_value_change = "test" date_value_change = str(date.today() - timedelta(days=1)) float8_value_change = 0.1 int2_value_change = 100 int8_value_change = 100 interval_value_change = float(5400) json_value_change = {"hello": "world"} jsonb_value_change = {"hello": "world"} numeric_value_change = 19 text_value_change = 'hello world' time_value_change = '18:18:18' timestamp_value_change = str(datetime.utcnow().isoformat()) timestamptz_value_change = str(datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()) timetz_value_change = '18:18:18+00:00' uuid_value_change = str(uuid.uuid4()) varchar_value_change = 'hello world' array_value_change = [1, 2, 3, 4] array_str__value_change = ['1', '2', '3', '4'] change['bool_value'] = bool_value_change change['char_value'] = char_value_change change['date_value'] = date_value_change change['float8_value'] = float8_value_change change['int2_value'] = int2_value_change change['int8_value'] = int8_value_change change['float4_value'] = 0.4 change['int4_value'] = 4 change['interval_value'] = interval_value_change change['json_value'] = json_value_change change['jsonb_value'] = jsonb_value_change change['numeric_value'] = numeric_value_change change['text_value'] = text_value_change change['time_value'] = time_value_change change['timestamp_value'] = timestamp_value_change change['timestamptz_value'] = timestamptz_value_change change['timetz_value'] = timetz_value_change change['uuid_value'] = uuid_value_change change['varchar_value'] = varchar_value_change change['array_value'] = array_value_change change['array_str__value'] = array_str__value_change data = json.dumps(change) headers = { 'accept': '*/*', 'Content-Type': 'application/json', } response = client.post('/test_post_direct_get_without_get', headers=headers, data=data, allow_redirects=True) assert response.status_code == HTTPStatus.NOT_FOUND ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test_async/test_put_many_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy_table.api_test_async import get_transaction_session, app, \ UntitledTable256 # Model Test # api_model = UntitledTable256Model.__dict__['POST'] # assert api_model # create_one_model = api_model[CrudMethods.UPSERT_ONE].__dict__ # assert create_one_model['requestModel'] or create_one_model['responseModel'] # create_one_request_model = deepcopy(create_one_model['requestModel'].__dict__['__fields__']) # create_one_response_model = deepcopy(create_one_model['responseModel'].__dict__['__fields__']) # Request Test # assert create_one_request_model.pop('on_conflict', False) # for k, v in create_one_request_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") # Response Test # for k, v in create_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test_creation_one", tags=["test"] ) test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], async_mode=True, prefix="/test_creation_many", tags=["test"] ) test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_post_direct_get", async_mode=True, tags=["test"] ) # # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # # FIXME some thing may not require # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, async_mode=True, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) # # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # # FIXME some thing may not require # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_update_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPDATE_MANY ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_update_many", async_mode=True, tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_update_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = 'primary_key' unique_fields = ['primary_key', 'int4_value', 'float4_value'] def test_create_many_and_update_many(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [{"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test_update_many?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert len(response_data) == 3 for k in response_data: for i in update_data: print(i) print(k[i]) assert k[i] == update_data[i] def test_create_many_and_update_many_but_not_found(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = { "insert": [ { "bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [ 0 ], "array_str__value": [ "string" ], "time_value": "18:18:18" , "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "time_value": "18:18:18", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "timetz_value": "18:18:18+00:00"}, {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ] } response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key_list = [i[primary_key_name] for i in insert_response_data] min_key = min(primary_key_list) max_key = max(primary_key_list) params = {"primary_key____from": min_key, "primary_key____to": max_key, "bool_value____list":True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '10:18:18', "time_value____to": '12:18:18', "time_value____list": '10:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "timez_value____from": '18:18:18+00:00', "timez_value____to": '18:18:18+00:00', "timez_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = { "bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test':'hello'}, "jsonb_value": {'test':'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", "array_value": [ 1,2,3,4,5 ], "array_str__value": [ "test" ], "time_value": "18:19:18" , "timetz_value": "18:19:18+00:00"} response = client.put(f'/test_update_many?{query_string}', data= json.dumps(update_data)) # response_data = response.json() # assert len(response_data) == 3 # for k in response_data: # for i in update_data: # print(i) # print(k[i]) # assert k[i] == update_data[i] assert response.status_code == 204 ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/api_test_async/test_put_one_api.py ================================================ import json from collections import OrderedDict from starlette.testclient import TestClient from src.fastapi_quickcrud import CrudMethods from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import sqlalchemy_to_pydantic from tests.test_implementations.test_sqlalchemy_table.api_test_async import get_transaction_session, app, \ UntitledTable256 test_create_one = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_creation_one", async_mode=True, tags=["test"] ) test_create_many = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_creation_many", async_mode=True, tags=["test"] ) test_post_and_redirect_get = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_post_direct_get", async_mode=True, tags=["test"] ) # # # Model Test # api_model = UntitledTable256Model.__dict__['GET'] # assert api_model # get_one_model = api_model[CrudMethods.FIND_ONE].__dict__ # assert get_one_model['requestModel'] or get_one_model['responseModel'] # get_one_request_model = deepcopy(get_one_model['requestModel'].__dict__['__fields__']) # get_one_response_model = deepcopy(get_one_model['responseModel'].__dict__['__fields__']) # primary_key_of_get_sql_schema = get_one_request_model[UntitledTable256.__dict__['primary_key_of_table']] # assert not primary_key_of_get_sql_schema.required # get_one_request_model.pop(UntitledTable256.__dict__['primary_key_of_table'], None) # for k, v in get_one_request_model.items(): # assert not v.required # # FIXME some thing may not require # for k, v in get_one_response_model.items(): # sql_schema = UntitledTable256.__dict__[v.name].comparator # # if sql_schema.server_default or sql_schema.default: # assert not v.required # elif not sql_schema.nullable and sql_schema.server_default or sql_schema.default: # assert not v.required # elif sql_schema.nullable: # assert not v.required # elif not sql_schema.nullable: # assert v.required # elif not sql_schema.nullable and not sql_schema.server_default or not sql_schema.default: # assert v.required # else: # print(f"{v.name=}") # print(f"{v.required=}") # print(f"{v.default=}") test_get_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, async_mode=True, crud_methods=[ CrudMethods.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test", tags=["test"] ) test_update_data = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.UPDATE_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], prefix="/test_update_one", async_mode=True, tags=["test"] ) [app.include_router(i) for i in [test_post_and_redirect_get, test_update_data, test_create_one, test_create_many, test_get_data]] client = TestClient(app) primary_key_name = 'primary_key' unique_fields = ['primary_key', 'int4_value', 'float4_value'] def test_create_one_and_update_one(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key, = [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '18:18:18', "time_value____to": '18:18:18', "time_value____list": '18:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_value____from": '18:18:18+00:00', "time_value____to": '18:18:18+00:00', "time_value____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "" "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test_update_one/{primary_key}?{query_string}', data=json.dumps(update_data)) response_data = response.json() assert response_data for i in update_data: print(i) print(response_data[i]) assert response_data[i] == update_data[i] def test_create_one_and_update_one_but_not_found(): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', } data = {"insert": [ {"bool_value": True, "char_value": "string", "date_value": "2021-07-24", "float4_value": 0, "float8_value": 0, "int2_value": 0, "int4_value": 0, "int8_value": 0, "interval_value": 0, "json_value": {}, "jsonb_value": {}, "numeric_value": 0, "text_value": "string", "timestamp_value": "2021-07-24T02:54:53.285", "timestamptz_value": "2021-07-24T02:54:53.285Z", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "varchar_value": "string", "array_value": [0], "array_str__value": ["string"], "time_value": "18:18:18", "timetz_value": "18:18:18+00:00"}, ]} response = client.post('/test_creation_many', headers=headers, data=json.dumps(data)) assert response.status_code == 201 insert_response_data = response.json() primary_key ,= [i[primary_key_name] for i in insert_response_data] params = {"bool_value____list": True, "char_value____str": 'string%', "char_value____str_____matching_pattern": 'case_sensitive', "date_value____from": "2021-07-22", "date_value____to": "2021-07-25", "float4_value____from": -1, "float4_value____to": 2, "float4_value____list": 0, "float8_value____from": -1, "float8_value____to": 2, "float8_value____list": 0, "int2_value____from": -1, "int2_value____to": 9, "int2_value____list": 0, "int4_value____from": -1, "int4_value____to": 9, "int4_value____list": 0, "int8_value____from": -1, "int8_value____to": 9, "int8_value____list": 0, "interval_value____from": -1, "interval_value____to": 9, "interval_value____list": 0, "numeric_value____from": -1, "numeric_value____to": 9, "numeric_value____list": 0, "text_value____list": "string", "time_value____from": '10:18:18', "time_value____to": '12:18:18', "time_value____list": '10:18:18', "timestamp_value_value____from": "2021-07-24T02:54:53.285", "timestamp_value_value____to": "2021-07-24T02:54:53.285", "timestamp_value_value____list": "2021-07-24T02:54:53.285", "timestamptz_value_value____from": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____to": "2021-07-24T02:54:53.285Z", "timestamptz_value_value____list": "2021-07-24T02:54:53.285Z", "uuid_value_value____list": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "time_valuez____from": '18:18:18+00:00', "time_valuez____to": '18:18:18+00:00', "time_valuez____list": '18:18:18+00:00', "varchar_value____str": 'string', "varchar_value____str_____matching_pattern": 'case_sensitive', "varchar_value____list": 'string', } from urllib.parse import urlencode query_string = urlencode(OrderedDict(**params)) update_data = {"bool_value": False, "char_value": "string_u ", "date_value": "2022-07-24", "float4_value": 10.50, "float8_value": 10.5, "int2_value": 10, "int4_value": 10, "int8_value": 10, "interval_value": 3600, "json_value": {'test': 'hello'}, "jsonb_value": {'test': 'hello'}, "numeric_value": 10, "text_value": "string_update", "timestamp_value": "2022-07-24T02:54:53.285000", "timestamptz_value": "2022-07-24T02:54:53.285000+00:00", "uuid_value": "3fa85f64-5717-4562-b3fc-2c963f66afb6", "varchar_value": "string", "array_value": [1, 2, 3, 4, 5], "array_str__value": ["test"], "time_value": "18:19:18", "timetz_value": "18:19:18+00:00"} response = client.put(f'/test_update_one/{primary_key}?{query_string}', data=json.dumps(update_data)) # response_data = response.json() response.status_code = 404 # assert response_data # for i in update_data: # assert response_data[i] == update_data[i] ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/error_test/__init__.py ================================================ ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/error_test/test_create_null_type.py ================================================ import os from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, text, PrimaryKeyConstraint, Table, UniqueConstraint, \ create_engine from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, synonym, sessionmaker from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods from src.fastapi_quickcrud.misc.exceptions import SchemaException, ColumnTypeNotSupportedException, PrimaryMissing Base = declarative_base() metadata = Base.metadata UntitledTable256 = Table( 'test_table', metadata, Column('primary_key', Integer, nullable=False,autoincrement=True,info={'alias_name': 'primary_key'}), Column('bool_value', Boolean, nullable=False, server_default=text("false")), Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float, nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL), Column('json_value', JSON,), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric), Column('text_value', Text), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('uuid_value', UUID), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', None), ) TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_ASYNC_URL', 'postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres') engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() try: crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, crud_methods=[ CrudMethods.PATCH_ONE, ], exclude_columns=['xml_value', 'box_valaue'], prefix="/child", tags=["child"] ) except BaseException as e: assert 'not supported yet' in str(e) # except BaseException as e: # print(str(e)) ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/error_test/test_pk_no_default_value.py ================================================ from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, text, PrimaryKeyConstraint, Table, UniqueConstraint from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, synonym from src.fastapi_quickcrud.misc.utils import table_to_declarative_base from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods from src.fastapi_quickcrud.misc.exceptions import SchemaException, ColumnTypeNotSupportedException, PrimaryMissing Base = declarative_base() metadata = Base.metadata UntitledTable256 = Table( 'test_table', metadata, Column('primary_key', Integer, nullable=False, primary_key=True, autoincrement=False), Column('bool_value', Boolean, nullable=False, server_default=text("false")), Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float, nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL), Column('json_value', JSON,), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric), Column('text_value', Text), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('uuid_value', UUID), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', None), ) UntitledTable256 = table_to_declarative_base(UntitledTable256) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.PATCH_ONE, ], exclude_columns=['xml_value', 'box_valaue']) except ColumnTypeNotSupportedException as e: print(str(e)) assert 'The type of column array_str__value (NULL) not supported yet' in str(e) ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/error_test/test_use_composite_primary.py ================================================ from sqlalchemy import ARRAY, BigInteger, Table, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text, PrimaryKeyConstraint from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from src.fastapi_quickcrud.misc.utils import table_to_declarative_base from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods, sqlalchemy_to_pydantic from src.fastapi_quickcrud.misc.exceptions import SchemaException, MultipleSingleUniqueNotSupportedException Base = declarative_base() metadata = Base.metadata UntitledTable256 = Table( 'test_table', metadata, Column('primary_key', Integer, nullable=False,autoincrement=True,info={'alias_name': 'primary_key'}), Column('bool_value', Boolean, nullable=False, server_default=text("false")), Column('bytea_value', LargeBinary), Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float, nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL, unique=True), Column('json_value', JSON, unique=True), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric, unique=True), Column('text_value', Text, unique=True), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('uuid_value', UUID), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), PrimaryKeyConstraint('primary_key', 'int4_value', 'float4_value'), ) UntitledTable256 = table_to_declarative_base(UntitledTable256) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) except SchemaException as e: print(e) 'multiple primary key / or composite not supported;' in str(e) ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/error_test/test_use_more_than_one_pk.py ================================================ from sqlalchemy import ARRAY, BigInteger, Table, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text, PrimaryKeyConstraint from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from src.fastapi_quickcrud.misc.utils import table_to_declarative_base from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods, sqlalchemy_to_pydantic from src.fastapi_quickcrud.misc.exceptions import SchemaException, MultipleSingleUniqueNotSupportedException Base = declarative_base() metadata = Base.metadata UntitledTable256 = Table( 'test_table', metadata, Column('primary_key', Integer, primary_key=True, nullable=False,autoincrement=True,info={'alias_name': 'primary_key'}), Column('bool_value', Boolean,primary_key=True, nullable=False, server_default=text("false")), Column('bytea_value', LargeBinary,primary_key=True, ), Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float, nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL, unique=True), Column('json_value', JSON, unique=True), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric, unique=True), Column('text_value', Text, unique=True), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('uuid_value', UUID), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), ) UntitledTable256 = table_to_declarative_base(UntitledTable256) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) except SchemaException as e: print(e) 'multiple primary key / or composite not supported;' in str(e) ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/error_test/test_use_more_than_one_unique.py ================================================ from sqlalchemy import ARRAY, BigInteger,Table, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from src.fastapi_quickcrud.misc.utils import table_to_declarative_base from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods, sqlalchemy_to_pydantic from src.fastapi_quickcrud.misc.exceptions import SchemaException, MultipleSingleUniqueNotSupportedException Base = declarative_base() metadata = Base.metadata UntitledTable256 = Table( 'test_table', metadata, Column('primary_key', Integer, primary_key=True, nullable=False,autoincrement=True,info={'alias_name': 'primary_key'}), Column('bool_value', Boolean, nullable=False, server_default=text("false")), Column('bytea_value', LargeBinary), Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float, nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL, unique=True), Column('json_value', JSON, unique=True), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric, unique=True), Column('text_value', Text, unique=True), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('uuid_value', UUID), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), ) UntitledTable256 = table_to_declarative_base(UntitledTable256) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) except SchemaException as e: str(e) == 'Only support one unique constraint/ Use unique constraint and composite unique constraint at same time is not supported / Use composite unique constraint if there are more than one unique constraint' ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/error_test/test_use_unique_and_composite_unique.py ================================================ from sqlalchemy import ARRAY, BigInteger,Table, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from src.fastapi_quickcrud.misc.utils import table_to_declarative_base from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods, sqlalchemy_to_pydantic from src.fastapi_quickcrud.misc.exceptions import SchemaException Base = declarative_base() metadata = Base.metadata UntitledTable256 = Table( 'test_table', metadata, Column('primary_key', Integer, primary_key=True, nullable=False,autoincrement=True,info={'alias_name': 'primary_key'}), Column('bool_value', Boolean, nullable=False, server_default=text("false")), Column('bytea_value', LargeBinary), Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float, nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL, unique=True), Column('json_value', JSON), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric), Column('text_value', Text), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('uuid_value', UUID), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), UniqueConstraint('primary_key', 'int4_value', 'float4_value'), ) UntitledTable256 = table_to_declarative_base(UntitledTable256) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) except SchemaException as e: str(e) == 'Only support one unique constraint/ Use unique constraint and composite unique constraint at same time is not supported / Use composite unique constraint if there are more than one unique constraint' ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/error_test/test_use_unsupported_type.py ================================================ from sqlalchemy import ARRAY, BigInteger, Table, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text, PrimaryKeyConstraint from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from src.fastapi_quickcrud.misc.utils import table_to_declarative_base from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods, sqlalchemy_to_pydantic from src.fastapi_quickcrud.misc.exceptions import SchemaException, MultipleSingleUniqueNotSupportedException, \ ColumnTypeNotSupportedException Base = declarative_base() metadata = Base.metadata UntitledTable256 = Table( 'test_table', metadata, Column('primary_key', LargeBinary,nullable=False,autoincrement=True,info={'alias_name': 'primary_key'}), Column('bool_value', Boolean, nullable=False, server_default=text("false")), Column('bytea_value', LargeBinary), Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float, nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL), Column('json_value', JSON), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric), Column('text_value', Text, unique=True), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('uuid_value', UUID), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), ) UntitledTable256 = table_to_declarative_base(UntitledTable256) try: UntitledTable256Model = sqlalchemy_to_pydantic(UntitledTable256, crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) except ColumnTypeNotSupportedException as e: 'not supported yet' in str(e) ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/error_test/test_use_unsupported_type_2.py ================================================ import os from sqlalchemy import ARRAY, BigInteger, Table, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text, PrimaryKeyConstraint, \ create_engine from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods, sqlalchemy_to_pydantic from src.fastapi_quickcrud.misc.exceptions import SchemaException, MultipleSingleUniqueNotSupportedException, \ ColumnTypeNotSupportedException Base = declarative_base() metadata = Base.metadata UntitledTable256 = Table( 'test_table', metadata, Column('primary_key', INTERVAL,nullable=False,autoincrement=True,info={'alias_name': 'primary_key'}), Column('bool_value', Boolean, nullable=False, server_default=text("false")), Column('bytea_value', LargeBinary), Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float, nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL), Column('json_value', JSON), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric), Column('text_value', Text, unique=True), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('uuid_value', UUID), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), ) TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_ASYNC_URL', 'postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres') engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() try: crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, prefix="/child", tags=["child"], crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) except ColumnTypeNotSupportedException as e: 'not supported yet' in str(e) ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/error_test/test_use_unsupported_type_3.py ================================================ import os from sqlalchemy import ARRAY, BigInteger, Table, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text, PrimaryKeyConstraint, \ create_engine from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods, sqlalchemy_to_pydantic from src.fastapi_quickcrud.misc.exceptions import SchemaException, MultipleSingleUniqueNotSupportedException, \ ColumnTypeNotSupportedException Base = declarative_base() metadata = Base.metadata UntitledTable256 = Table( 'test_table', metadata, Column('primary_key', JSON,nullable=False,autoincrement=True,info={'alias_name': 'primary_key'}), Column('bool_value', Boolean, nullable=False, server_default=text("false")), Column('bytea_value', LargeBinary), Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float, nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL), Column('json_value', JSON), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric), Column('text_value', Text, unique=True), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('uuid_value', UUID), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), ) TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_ASYNC_URL', 'postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres') engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() try: crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, prefix="/child", tags=["child"], crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) except ColumnTypeNotSupportedException as e: 'not supported yet' in str(e) ================================================ FILE: tests/test_implementations/test_sqlalchemy_table/error_test/test_use_unsupported_type_4.py ================================================ import os from sqlalchemy import ARRAY, BigInteger, Table, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text, PrimaryKeyConstraint, \ create_engine from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import sqlalchemy_to_pydantic, CrudMethods, sqlalchemy_to_pydantic from src.fastapi_quickcrud.misc.exceptions import SchemaException, MultipleSingleUniqueNotSupportedException, \ ColumnTypeNotSupportedException Base = declarative_base() metadata = Base.metadata UntitledTable256 = Table( 'test_table', metadata, Column('primary_key', JSONB,nullable=False,autoincrement=True,info={'alias_name': 'primary_key'}), Column('bool_value', Boolean, nullable=False, server_default=text("false")), Column('bytea_value', LargeBinary), Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float, nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL), Column('json_value', JSON), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric), Column('text_value', Text, unique=True), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('uuid_value', UUID), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), ) TEST_DATABASE_URL = os.environ.get('TEST_DATABASE_ASYNC_URL', 'postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres') engine = create_engine(TEST_DATABASE_URL, future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() try: crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=UntitledTable256, prefix="/child", tags=["child"], crud_methods=[ CrudMethods.UPSERT_MANY, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) except ColumnTypeNotSupportedException as e: 'not supported yet' in str(e) ================================================ FILE: tutorial/__init__.py ================================================ from collections import defaultdict a = [ { "id": 1, "id_foreign": { "id": 1, "parent_id": 1 } }, { "id": 1, "id_foreign": { "id": 2, "parent_id": 1 } }, { "id": 1, "id_foreign": { "id": 3, "parent_id": 1 } }, { "id": 2, "id_foreign": { "id": 4, "parent_id": 2 } }, { "id": 2, "id_foreign": { "id": 5, "parent_id": 2 } }, { "id": 2, "id_foreign": { "id": 6, "parent_id": 2 } } ] b = [ {"id": 1, "id_foreign":[{ "id": 3, "parent_id": 1 }, { "id": 1, "parent_id": 1 }, {"id": 2, "parent_id": 1} ], }, {"id": 2, "id_foreign": [{ "id": 4, "parent_id": 2 }, { "id": 5, "parent_id": 2 }, { "id": 6, "parent_id": 2} ] } ] tmp = defaultdict(list) print(tmp) from itertools import groupby def test(*args, **kwargs): tmp = {} for k, v in args[0].items(): if '_foreign' not in k: tmp[k] = v return tmp response_list = [] for key, group in groupby(a, test): response = {} for i in group: for k , v in i.items(): if '_foreign' in k: if k not in response: response[k] = [v] else: response[k].append(v) for response_ in response: i.pop(response_, None) result = i | response response_list.append(result) print() # result = [] # for data_index in range(0, len(a)): # for data_index_ in range(0, len(a)): # foreign_ = {} # non_foreign_ = {} # for k, v in a[data_index].items(): # tmp = {} # if '_foreign' in k: # foreign_[k] = v # else: # non_foreign_[k] = v # # foreign__ = {} # non_foreign__ = {} # for k, v in a[data_index_].items(): # tmp = {} # if '_foreign' in k: # foreign__[k] = v # else: # non_foreign__[k] = v # if non_foreign_ == non_foreign__: # print(data_index) # print(data_index_) # print('----') # print('===') ================================================ FILE: tutorial/basic_usage/__init__.py ================================================ ================================================ FILE: tutorial/basic_usage/depencies_example_auth.py ================================================ from typing import Optional import uvicorn from fastapi import FastAPI, Depends, Security, Request from fastapi.security import HTTPBearer, APIKeyHeader, APIKeyQuery from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from src.fastapi_quickcrud import CrudMethods as CrudRouter from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import sqlalchemy_to_pydantic app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import create_engine engine = create_engine('postgresql://postgres:1234@127.0.0.1:5432/postgres', future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = async_session() yield db finally: db.close() class ExampleTable(Base): __tablename__ = 'example_table' __table_args__ = ( UniqueConstraint('id', 'int4_value', 'float4_value'), ) id = Column(Integer, primary_key=True, info={'alias_name': 'primary_key'}, server_default=text("nextval('untitled_table_256_id_seq'::regclass)")) primary_key = synonym('id') bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, info={'alias_name': 'int4_alias'}, nullable=False) int4_alias = synonym('int4_value') int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text, info={'alias_name': 'text_alias'}) text_alias = synonym('text_value') time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) def AuthenticationService( auth_rest_url: str, apikey_header_accept: str = "x-api-key", apikey_query_accept: str = "apikey", ): jwt_bearer = HTTPBearer(auto_error=False) apikey_header = APIKeyHeader(name=apikey_header_accept, auto_error=False) apikey_query = APIKeyQuery(name=apikey_query_accept, auto_error=False) async def security_schemes( _jwt_bearer: Optional[str] = Security(jwt_bearer), _apikey_header: Optional[str] = Security(apikey_header), _apikey_query: Optional[str] = Security(apikey_query), ): """ authentication dependencices for correct generating openapi by fastapi """ class AuthenticationServiceClass: @staticmethod def AuthRequest(request: Request, schemes=Depends(security_schemes)): return request @staticmethod def auth_check(request: Request = Depends(security_schemes)): ''' do your business logic''' return True return AuthenticationServiceClass authentication = AuthenticationService( auth_rest_url='0.0.0.0', apikey_header_accept='x-api-key', apikey_query_accept='api-key', ) dependencies = [authentication.auth_check] UntitledTable256Model = sqlalchemy_to_pydantic(ExampleTable, crud_methods=[ CrudRouter.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) UntitledTable256Model = sqlalchemy_to_pydantic(ExampleTable, crud_methods=[ CrudRouter.UPSERT_MANY ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) upsert_many_router = crud_router_builder(db_session=get_transaction_session, crud_models=UntitledTable256Model, db_model=ExampleTable, prefix="/create_many", dependencies=dependencies, tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(ExampleTable, crud_methods=[ CrudRouter.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) post_redirect_get_router = crud_router_builder(db_session=get_transaction_session, crud_models=UntitledTable256Model, db_model=ExampleTable, prefix="/post_redirect_get", dependencies=dependencies, tags=["test"] ) example_table_full_api = sqlalchemy_to_pydantic(ExampleTable, crud_methods=[ CrudRouter.FIND_MANY, CrudRouter.FIND_ONE, CrudRouter.UPSERT_ONE, CrudRouter.UPDATE_MANY, CrudRouter.UPDATE_ONE, CrudRouter.DELETE_ONE, CrudRouter.DELETE_MANY, CrudRouter.PATCH_MANY, CrudRouter.PATCH_ONE, ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) example_table_full_router = crud_router_builder(db_session=get_transaction_session, crud_models=example_table_full_api, db_model=ExampleTable, dependencies=dependencies, prefix="/test_CRUD", tags=["test"] ) ExampleTable.__table__.create(engine, checkfirst=True) [app.include_router(i) for i in [example_table_full_router, post_redirect_get_router, upsert_many_router]] uvicorn.run(app, host="0.0.0.0", port=8001, debug=False) ================================================ FILE: tutorial/basic_usage/quick_usage_with_async_SQLALchemy_Base.py ================================================ from datetime import datetime, timezone import uvicorn from fastapi import FastAPI from sqlalchemy import * from sqlalchemy.dialects.postgresql import * from sqlalchemy.orm import * from src.fastapi_quickcrud import CrudMethods as CrudRouter from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import sqlalchemy_to_pydantic app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession engine = create_async_engine('postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres', future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(bind=engine, class_=AsyncSession) async def get_transaction_session() -> AsyncSession: async with async_session() as session: async with session.begin(): yield session class ExampleTable(Base): __tablename__ = 'example_table' __table_args__ = ( UniqueConstraint('id', 'int4_value', 'float4_value'), ) id = Column(Integer, primary_key=True, info={'alias_name': 'primary_key'}, autoincrement=True) primary_key = synonym('id') bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, info={'alias_name': 'int4_alias'}, nullable=False) int4_alias = synonym('int4_value') int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text, info={'alias_name': 'text_alias'}) text_alias = synonym('text_value') time_value = Column(Time(False), default=datetime.now(timezone.utc).strftime('%H:%M:%S')) timestamp_value = Column(DateTime(False), default=datetime.now()) timestamptz_value = Column(DateTime(True), default=datetime.now(timezone.utc)) timetz_value = Column(Time(True), default=datetime.now(timezone.utc).strftime('%H:%M:%S%z')) uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) UntitledTable256Model = sqlalchemy_to_pydantic(ExampleTable, crud_methods=[ CrudRouter.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) UntitledTable256Model = sqlalchemy_to_pydantic(ExampleTable, crud_methods=[ CrudRouter.UPSERT_MANY ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) upsert_many_router = crud_router_builder(db_session=get_transaction_session, db_model=ExampleTable, crud_models=UntitledTable256Model, prefix="/create_many", async_mode=True, tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(ExampleTable, crud_methods=[ CrudRouter.FIND_ONE, CrudRouter.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) post_redirect_get_router = crud_router_builder(db_session=get_transaction_session, db_model=ExampleTable, crud_models=UntitledTable256Model, prefix="/post_redirect_get", async_mode=True, tags=["test"] ) example_table_full_api = sqlalchemy_to_pydantic(ExampleTable, crud_methods=[ CrudRouter.FIND_MANY, CrudRouter.UPSERT_ONE, CrudRouter.UPDATE_MANY, CrudRouter.UPDATE_ONE, CrudRouter.DELETE_ONE, CrudRouter.DELETE_MANY, CrudRouter.PATCH_MANY, CrudRouter.PATCH_ONE, ], exclude_columns=['array_str__value', 'bytea_value', 'xml_value', 'box_valaue']) example_table_full_router = crud_router_builder(db_session=get_transaction_session, db_model=ExampleTable, crud_models=example_table_full_api, async_mode=True, prefix="/test_CRUD", tags=["test"] ) # Base.metadata.create_all(engine) # unknown reason that will throw error when add the code following @app.on_event("startup") async def startup_event(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) # [app.include_router(i) for i in [example_table_full_router, post_redirect_get_router, upsert_many_router]] uvicorn.run(app, host="0.0.0.0", port=8000, debug=False) ================================================ FILE: tutorial/basic_usage/quick_usage_with_async_SQLALchemy_table.py ================================================ import uvicorn from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from sqlalchemy.testing.schema import Table from fastapi_quickcrud.misc.utils import sqlalchemy_table_to_pydantic from src.fastapi_quickcrud import CrudMethods as CrudRouter from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import sqlalchemy_to_pydantic app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession engine = create_async_engine('postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres', future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(bind=engine, class_=AsyncSession) async def get_transaction_session() -> AsyncSession: async with async_session() as session: async with session.begin(): yield session ExampleTable = Table( 'untitled_table_256', metadata, Column('id', Integer, primary_key=True, nullable=False,autoincrement=True,info={'alias_name': 'primary_key'}), Column('bool_value', Boolean, nullable=False, server_default=text("false")), Column('bytea_value', LargeBinary), Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float, nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL), Column('json_value', JSON), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric), Column('text_value', Text), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('uuid_value', UUID), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), UniqueConstraint('id', 'int4_value', 'float4_value'), ) UntitledTable256Model = sqlalchemy_table_to_pydantic(ExampleTable, crud_methods=[ CrudRouter.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) UntitledTable256Model = sqlalchemy_table_to_pydantic(ExampleTable, crud_methods=[ CrudRouter.UPSERT_MANY ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) upsert_many_router = crud_router_builder(db_session=get_transaction_session, db_model=ExampleTable, crud_models=UntitledTable256Model, prefix="/create_many", async_mode=True, tags=["test"] ) UntitledTable256Model = sqlalchemy_table_to_pydantic(ExampleTable, crud_methods=[ CrudRouter.POST_REDIRECT_GET, CrudRouter.FIND_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) post_redirect_get_router = crud_router_builder(db_session=get_transaction_session, db_model=ExampleTable, crud_models=UntitledTable256Model, prefix="/post_redirect_get", async_mode=True, tags=["test"] ) example_table_full_api = sqlalchemy_table_to_pydantic(ExampleTable, crud_methods=[ CrudRouter.FIND_MANY, CrudRouter.UPSERT_ONE, CrudRouter.UPDATE_MANY, CrudRouter.UPDATE_ONE, CrudRouter.DELETE_ONE, CrudRouter.DELETE_MANY, CrudRouter.PATCH_MANY, CrudRouter.PATCH_ONE, ], exclude_columns=['array_str__value', 'bytea_value', 'xml_value', 'box_valaue']) example_table_full_router = crud_router_builder(db_session=get_transaction_session, db_model=ExampleTable, crud_models=example_table_full_api, async_mode=True, prefix="/test_CRUD", tags=["test"] ) @app.on_event("startup") async def startup_event(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) # # Base.metadata.create_all(engine) # unknown reason that will throw error when add the code following # async def create_table(): # async with engine.begin() as conn: # await conn.run_sync(Base.metadata.create_all) # print('created') # print('done') # return # # asyncio.run(create_table()) # loop.stop() # loop.close() # print(loop.is_closed()) [app.include_router(i) for i in [example_table_full_router, post_redirect_get_router, upsert_many_router]] uvicorn.run(app, host="0.0.0.0", port=8000, debug=False) ================================================ FILE: tutorial/basic_usage/quick_usage_with_async_SQLALchemy_table_with_out_primary_key.py ================================================ import uvicorn from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative_base, sessionmaker, synonym from sqlalchemy.testing.schema import Table from fastapi_quickcrud.misc.utils import sqlalchemy_table_to_pydantic from src.fastapi_quickcrud import CrudMethods as CrudRouter from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import sqlalchemy_to_pydantic app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession engine = create_async_engine('postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres', future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(bind=engine, class_=AsyncSession) async def get_transaction_session() -> AsyncSession: async with async_session() as session: async with session.begin(): yield session ExampleTable = Table( 'untitled_table_256', metadata, Column('bool_value', Boolean, nullable=False, server_default=text("false")), Column('bytea_value', LargeBinary), Column('char_value', CHAR(10)), Column('date_value', Date, server_default=text("now()")), Column('float4_value', Float, nullable=False), Column('float8_value', Float(53), nullable=False, server_default=text("10.10")), Column('int2_value', SmallInteger, nullable=False), Column('int4_value', Integer, nullable=False), Column('int8_value', BigInteger, server_default=text("99")), Column('interval_value', INTERVAL), Column('json_value', JSON), Column('jsonb_value', JSONB(astext_type=Text())), Column('numeric_value', Numeric), Column('text_value', Text), Column('time_value', Time), Column('timestamp_value', DateTime), Column('timestamptz_value', DateTime(True)), Column('timetz_value', Time(True)), Column('uuid_value', UUID), Column('varchar_value', String), Column('array_value', ARRAY(Integer())), Column('array_str__value', ARRAY(String())), UniqueConstraint( 'int4_value', 'float4_value'), ) UntitledTable256Model = sqlalchemy_table_to_pydantic(ExampleTable, crud_methods=[ CrudRouter.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) UntitledTable256Model = sqlalchemy_table_to_pydantic(ExampleTable, crud_methods=[ CrudRouter.UPSERT_MANY ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) upsert_many_router = crud_router_builder(db_session=get_transaction_session, db_model=ExampleTable, crud_models=UntitledTable256Model, prefix="/create_many", async_mode=True, tags=["test"] ) example_table_full_api = sqlalchemy_table_to_pydantic(ExampleTable, crud_methods=[ CrudRouter.FIND_MANY, CrudRouter.UPSERT_ONE, CrudRouter.UPDATE_MANY, CrudRouter.DELETE_MANY, CrudRouter.PATCH_MANY, ], exclude_columns=['array_str__value', 'bytea_value', 'xml_value', 'box_valaue']) example_table_full_router = crud_router_builder(db_session=get_transaction_session, db_model=ExampleTable, crud_models=example_table_full_api, async_mode=True, prefix="/test_CRUD", tags=["test"] ) @app.on_event("startup") async def startup_event(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) [app.include_router(i) for i in [example_table_full_router, upsert_many_router]] uvicorn.run(app, host="0.0.0.0", port=8000, debug=False) ================================================ FILE: tutorial/basic_usage/quick_usage_with_sync_SQLAlchemy_Base.py ================================================ import uvicorn from fastapi import FastAPI from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, UniqueConstraint, text from sqlalchemy import create_engine from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, synonym from src.fastapi_quickcrud import CrudMethods as CrudRouter from src.fastapi_quickcrud import crud_router_builder from src.fastapi_quickcrud import sqlalchemy_to_pydantic app = FastAPI() Base = declarative_base() metadata = Base.metadata engine = create_engine('postgresql://root@127.0.0.1:5432/postgres', future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) sync_session = sessionmaker(autoflush=False, bind=engine) def get_transaction_session(): try: db = sync_session() yield db db.commit() except Exception as e: db.rollback() raise e finally: db.close() class ExampleTable(Base): __tablename__ = 'untitled_table_256' __table_args__ = ( UniqueConstraint('id', 'int4_value', 'float4_value'), ) id = Column(Integer, primary_key=True, info={'alias_name': 'primary_key'},autoincrement=True) primary_key = synonym('id') bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), info={'alias_name': 'float8_alias'}, nullable=False, server_default=text("10.10")) float8_alias = synonym('float8_value') int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, info={'alias_name': 'int4_alias'}, nullable=False) int4_alias = synonym('int4_value') int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text, info={'alias_name': 'text_alias'}) text_alias = synonym('text_value') time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID(as_uuid=True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) UntitledTable256Model = sqlalchemy_to_pydantic(ExampleTable, crud_methods=[ CrudRouter.UPSERT_ONE ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) UntitledTable256Model = sqlalchemy_to_pydantic(ExampleTable, crud_methods=[ CrudRouter.UPSERT_MANY ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) upsert_many_router = crud_router_builder(db_session=get_transaction_session, db_model=ExampleTable, crud_models=UntitledTable256Model, prefix="/create_many", tags=["test"] ) UntitledTable256Model = sqlalchemy_to_pydantic(ExampleTable, crud_methods=[ # CrudRouter.FIND_ONE, # CrudRouter.FIND_ONE, CrudRouter.POST_REDIRECT_GET ], exclude_columns=['bytea_value', 'xml_value', 'box_valaue']) post_redirect_get_router = crud_router_builder(db_session=get_transaction_session, db_model=ExampleTable, crud_models=UntitledTable256Model, prefix="/post_redirect_get", tags=["post_redirect_get"] ) example_table_full_api = sqlalchemy_to_pydantic(ExampleTable, crud_methods=[ CrudRouter.FIND_MANY, CrudRouter.UPSERT_ONE, CrudRouter.FIND_ONE, CrudRouter.UPDATE_MANY, CrudRouter.UPDATE_ONE, CrudRouter.DELETE_ONE, CrudRouter.DELETE_MANY, CrudRouter.PATCH_MANY, CrudRouter.PATCH_ONE, ], exclude_columns=['array_str__value', 'bytea_value', 'xml_value', 'box_valaue']) example_table_full_router = crud_router_builder(db_session=get_transaction_session, db_model=ExampleTable, crud_models=example_table_full_api, async_mode=False, prefix="/test_CRUD", tags=["test"], dependencies=[], autocommit=False ) ExampleTable.__table__.create(engine, checkfirst=True) [app.include_router(i) for i in [example_table_full_router, post_redirect_get_router, upsert_many_router]] uvicorn.run(app, host="0.0.0.0", port=8000, debug=False) ================================================ FILE: tutorial/foreign_tree/__init__.py ================================================ ================================================ FILE: tutorial/foreign_tree/async_m2m.py ================================================ import asyncio from fastapi import FastAPI from sqlalchemy import Column, Integer, \ ForeignKey, Table, CHAR from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession from sqlalchemy.orm import declarative_base, sessionmaker, relationship from src.fastapi_quickcrud.misc.type import SqlType from src.fastapi_quickcrud.crud_router import crud_router_builder app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy.pool import StaticPool engine = create_async_engine('sqlite+aiosqlite://', future=True, echo=True, pool_pre_ping=True, pool_recycle=7200, connect_args={"check_same_thread": False}, poolclass=StaticPool) session = sessionmaker(autocommit=False, autoflush=False, bind=engine, class_=AsyncSession) async def get_transaction_session(): async with session() as s: yield s association_table = Table('test_association', Base.metadata, Column('left_id', ForeignKey('test_left.id')), Column('right_id', ForeignKey('test_right.id')) ) association_table_second = Table('test_association_second', Base.metadata, Column('left_id_second', ForeignKey('test_left.id')), Column('right_id_second', ForeignKey('test_right_second.id')) ) class Child(Base): __tablename__ = 'test_right' id = Column(Integer, primary_key=True) child = Column(CHAR(10)) parent = relationship("Parent", secondary=association_table) class Parent(Base): __tablename__ = 'test_left' id = Column(Integer, primary_key=True) parent = Column(CHAR(10)) children = relationship("Child", secondary=association_table) children_second = relationship("ChildSecond", secondary=association_table_second) class ChildSecond(Base): __tablename__ = 'test_right_second' id = Column(Integer, primary_key=True) child_second = Column(CHAR(10)) children_second = relationship("Parent", secondary=association_table_second) crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child", tags=["child"], sql_type=SqlType.sqlite, foreign_include=[Parent], async_mode=True ) crud_route_association_table_second = crud_router_builder(db_session=get_transaction_session, db_model=association_table_second, prefix="/association_table_second", tags=["association_table_second"], sql_type=SqlType.sqlite, async_mode=True ) crud_route_association_table_second = crud_router_builder(db_session=get_transaction_session, db_model=association_table_second, prefix="/association_table_second", tags=["association_table_second"], sql_type=SqlType.sqlite, async_mode=True ) crud_route_child_second = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child_second", tags=["child_second"], sql_type=SqlType.sqlite, async_mode=True ) crud_route_parent = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"], foreign_include=[Child, ], sql_type=SqlType.sqlite, async_mode=True ) crud_route_parent2 = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"], foreign_include=[ChildSecond], sql_type=SqlType.sqlite, async_mode=True ) crud_route_association = crud_router_builder(db_session=get_transaction_session, db_model=association_table, prefix="/association", tags=["association"], sql_type=SqlType.sqlite, async_mode=True ) [app.include_router(i) for i in [crud_route_association_table_second, crud_route_child_second, crud_route_parent, crud_route_child, crud_route_parent2, crud_route_association]] from starlette.testclient import TestClient async def create_table(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) db = session() db.add(Child(id=1, child="child1")) db.add(Child(id=2, child="child2")) db.add(Child(id=3, child="child3")) db.add(Child(id=4, child="child4")) await db.flush() db.add(Parent(id=1, parent="parent1")) db.add(Parent(id=2, parent="parent2")) db.add(Parent(id=3, parent="parent3")) db.add(Parent(id=4, parent="parent4")) await db.flush() await db.execute(association_table.insert().values(left_id=1, right_id=1)) await db.execute(association_table.insert().values(left_id=2, right_id=2)) await db.execute(association_table.insert().values(left_id=3, right_id=3)) await db.execute(association_table.insert().values(left_id=4, right_id=4)) db.add(ChildSecond(id=1, child_second="child_second1")) db.add(ChildSecond(id=2, child_second="child_second2")) db.add(ChildSecond(id=3, child_second="child_second3")) db.add(ChildSecond(id=4, child_second="child_second4")) await db.flush() await db.execute(association_table_second.insert().values(left_id_second=1, right_id_second=1)) await db.execute(association_table_second.insert().values(left_id_second=2, right_id_second=2)) await db.execute(association_table_second.insert().values(left_id_second=3, right_id_second=3)) await db.execute(association_table_second.insert().values(left_id_second=4, right_id_second=4)) await db.commit() loop = asyncio.get_event_loop() loop.run_until_complete(create_table()) import uvicorn uvicorn.run(app, host="0.0.0.0", port=8002, debug=False) ================================================ FILE: tutorial/foreign_tree/m2m.py ================================================ from fastapi import FastAPI from fastapi_quickcrud import crud_router_builder from sqlalchemy import * from sqlalchemy.orm import * from fastapi_quickcrud.misc.type import SqlType Base = declarative_base() from sqlalchemy.pool import StaticPool engine = create_engine('sqlite://', echo=True, connect_args={"check_same_thread": False}, pool_recycle=7200, poolclass=StaticPool) session = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_transaction_session(): try: db = session() yield db finally: db.close() association_table = Table('test_association', Base.metadata, Column('left_id', ForeignKey('test_left.id')), Column('right_id', ForeignKey('test_right.id')) ) association_table_second = Table('test_association_second', Base.metadata, Column('left_id_second', ForeignKey('test_left.id')), Column('right_id_second', ForeignKey('test_right_second.id')) ) class Child(Base): __tablename__ = 'test_right' id = Column(Integer, primary_key=True) child = Column(CHAR(10)) parent = relationship("Parent", secondary=association_table) class Parent(Base): __tablename__ = 'test_left' id = Column(Integer, primary_key=True) parent = Column(CHAR(10)) children = relationship("Child", secondary=association_table) children_second = relationship("ChildSecond", secondary=association_table_second) class ChildSecond(Base): __tablename__ = 'test_right_second' id = Column(Integer, primary_key=True) child_second = Column(CHAR(10)) children_second = relationship("Parent", secondary=association_table_second) crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child", tags=["child"], sql_type=SqlType.sqlite, foreign_include=[Parent], ) crud_route_association_table_second = crud_router_builder(db_session=get_transaction_session, db_model=association_table_second, prefix="/association_table_second", tags=["association_table_second"], sql_type=SqlType.sqlite, ) crud_route_association_table_second = crud_router_builder(db_session=get_transaction_session, db_model=association_table_second, prefix="/association_table_second", tags=["association_table_second"], sql_type=SqlType.sqlite, ) crud_route_child_second = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child_second", tags=["child_second"], sql_type=SqlType.sqlite, ) crud_route_parent = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"], foreign_include=[Child,], sql_type=SqlType.sqlite, ) crud_route_parent2 = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"], foreign_include=[ChildSecond], sql_type=SqlType.sqlite, ) crud_route_association = crud_router_builder(db_session=get_transaction_session, db_model=association_table, prefix="/association", tags=["association"], sql_type=SqlType.sqlite, ) app = FastAPI() [app.include_router(i) for i in [crud_route_association_table_second, crud_route_child_second, crud_route_parent, crud_route_child,crud_route_parent2, crud_route_association]] Child.__table__.create(engine, checkfirst=True) ChildSecond.__table__.create(engine, checkfirst=True) Parent.__table__.create(engine, checkfirst=True) association_table.create(engine, checkfirst=True) association_table_second.create(engine, checkfirst=True) db = session() db.add(Child(id=1, child="child1")) db.add(Child(id=2, child="child2")) db.add(Child(id=3, child="child3")) db.add(Child(id=4, child="child4")) db.flush() db.add(Parent(id=1, parent="parent1")) db.add(Parent(id=2, parent="parent2")) db.add(Parent(id=3, parent="parent3")) db.add(Parent(id=4, parent="parent4")) db.flush() db.execute(association_table.insert().values(left_id=1, right_id=1)) db.execute(association_table.insert().values(left_id=2, right_id=2)) db.execute(association_table.insert().values(left_id=3, right_id=3)) db.execute(association_table.insert().values(left_id=4, right_id=4)) db.add(ChildSecond(id=1, child_second="child_second1")) db.add(ChildSecond(id=2, child_second="child_second2")) db.add(ChildSecond(id=3, child_second="child_second3")) db.add(ChildSecond(id=4, child_second="child_second4")) db.flush() db.execute(association_table_second.insert().values(left_id_second=1, right_id_second=1)) db.execute(association_table_second.insert().values(left_id_second=2, right_id_second=2)) db.execute(association_table_second.insert().values(left_id_second=3, right_id_second=3)) db.execute(association_table_second.insert().values(left_id_second=4, right_id_second=4)) q = db.execute(''' SELECT name FROM sqlite_master ''') available_tables = q.fetchall() db.commit() import uvicorn uvicorn.run(app, host="0.0.0.0", port=8002, debug=False) ================================================ FILE: tutorial/foreign_tree/sample_tree.py ================================================ from fastapi import FastAPI import uvicorn from fastapi_quickcrud import crud_router_builder from sqlalchemy import * from sqlalchemy.orm import * from fastapi_quickcrud.crud_router import generic_sql_crud_router_builder Base = declarative_base() class Account(Base): __tablename__ = "account" id = Column(Integer, primary_key=True, autoincrement=True) blog_post = relationship("BlogPost", back_populates="account") class BlogPost(Base): __tablename__ = "blog_post" id = Column(Integer, primary_key=True, autoincrement=True) account_id = Column(Integer, ForeignKey("account.id"), nullable=False) account = relationship("Account", back_populates="blog_post") blog_comment = relationship("BlogComment", back_populates="blog_post") class BlogComment(Base): __tablename__ = "blog_comment" id = Column(Integer, primary_key=True, autoincrement=True) blog_id = Column(Integer, ForeignKey("blog_post.id"), nullable=False) blog_post = relationship("BlogPost", back_populates="blog_comment") crud_route_parent = crud_router_builder( db_model=Account, prefix="/account", tags=["account"], foreign_include=[BlogComment, BlogPost] ) crud_route_child1 = generic_sql_crud_router_builder( db_model=BlogPost, prefix="/blog_post", tags=["blog_post"], foreign_include=[BlogComment] ) crud_route_child2 = generic_sql_crud_router_builder( db_model=BlogComment, prefix="/blog_comment", tags=["blog_comment"] ) app = FastAPI() [app.include_router(i) for i in [crud_route_parent, crud_route_child1, crud_route_child2]] uvicorn.run(app, host="0.0.0.0", port=8002, debug=False) ================================================ FILE: tutorial/relationship/__init__.py ================================================ ================================================ FILE: tutorial/relationship/many_to_many.py ================================================ import uvicorn from fastapi import FastAPI, Depends from sqlalchemy.orm import declarative_base, sessionmaker from fastapi_quickcrud import CrudMethods from fastapi_quickcrud import crud_router_builder from fastapi_quickcrud import sqlalchemy_to_pydantic from fastapi_quickcrud.misc.memory_sql import sync_memory_db app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy import CHAR, Column, ForeignKey, Integer, Table from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() metadata = Base.metadata association_table = Table('association', Base.metadata, Column('left_id', ForeignKey('left.id')), Column('right_id', ForeignKey('right.id')) ) class Parent(Base): __tablename__ = 'left' id = Column(Integer, primary_key=True) children = relationship("Child", secondary=association_table) class Child(Base): __tablename__ = 'right' id = Column(Integer, primary_key=True) name = Column(CHAR, nullable=True) user_model_m2m = sqlalchemy_to_pydantic(db_model=association_table, crud_methods=[ CrudMethods.FIND_MANY, CrudMethods.UPSERT_ONE, CrudMethods.UPDATE_MANY, CrudMethods.DELETE_MANY, CrudMethods.PATCH_MANY, ], exclude_columns=[]) user_model_set = sqlalchemy_to_pydantic(db_model=Parent, crud_methods=[ CrudMethods.FIND_MANY, CrudMethods.FIND_ONE, CrudMethods.CREATE_ONE, CrudMethods.UPDATE_MANY, CrudMethods.UPDATE_ONE, CrudMethods.DELETE_ONE, CrudMethods.DELETE_MANY, CrudMethods.PATCH_MANY, ], exclude_columns=[]) friend_model_set = sqlalchemy_to_pydantic(db_model=Child, crud_methods=[ CrudMethods.FIND_MANY, CrudMethods.UPSERT_MANY, CrudMethods.UPDATE_MANY, CrudMethods.DELETE_MANY, CrudMethods.CREATE_ONE, CrudMethods.PATCH_MANY, ], exclude_columns=[]) crud_route_1 = crud_router_builder(crud_models=user_model_set, db_model=Parent, prefix="/Parent", dependencies=[], async_mode=True, tags=["Parent"] ) crud_route_3 = crud_router_builder(crud_models=user_model_m2m, db_model=association_table, prefix="/Parent2child", dependencies=[], async_mode=True, tags=["m2m"] ) crud_route_2 = crud_router_builder(crud_models=friend_model_set, db_model=Child, async_mode=True, prefix="/Child", dependencies=[], tags=["Child"] ) post_model = friend_model_set.POST[CrudMethods.CREATE_ONE] sync_memory_db.create_memory_table(Child) @app.post("/hello", status_code=201, tags=["Child"], response_model=post_model.responseModel, dependencies=[]) async def my_api( body: post_model.requestBodyModel = Depends(post_model.requestBodyModel), session=Depends(sync_memory_db.get_memory_db_session) ): db_item = Child(**body.__dict__) session.add(db_item) session.commit() session.refresh(db_item) return db_item.__dict__ app.include_router(crud_route_1) app.include_router(crud_route_2) app.include_router(crud_route_3) uvicorn.run(app, host="0.0.0.0", port=8000, debug=False) ================================================ FILE: tutorial/relationship/many_to_one.py ================================================ import asyncio from datetime import datetime, timezone import uvicorn from fastapi import FastAPI from sqlalchemy import Column, Integer, \ String, Table, ForeignKey, DateTime, Text, text, select, Index, UniqueConstraint from sqlalchemy.dialects.postgresql import UUID, ARRAY from sqlalchemy.orm import declarative_base, sessionmaker, relationship from fastapi_quickcrud import CrudMethods from fastapi_quickcrud import crud_router_builder from fastapi_quickcrud import sqlalchemy_to_pydantic app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession engine = create_async_engine('postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres', future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(bind=engine, class_=AsyncSession) async def get_transaction_session() -> AsyncSession: async with async_session() as session: async with session.begin(): yield session from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, ForeignKey, Index, Integer, JSON, LargeBinary, Numeric, SmallInteger, String, Table, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, TIMESTAMP, UUID from sqlalchemy.orm import relationship from sqlalchemy.sql.sqltypes import NullType from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() metadata = Base.metadata class Child(Base): __tablename__ = 'child_m2o_back_populates' id = Column(Integer, primary_key=True) class Parent(Base): __tablename__ = 'parent_m2o_back_populates' id = Column(Integer, primary_key=True) child_id = Column(Integer, ForeignKey('child_m2o_back_populates.id')) child = relationship("Child", backref="parents") @app.on_event("startup") async def startup_event(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) user_model_set = sqlalchemy_to_pydantic(db_model=Parent, crud_methods=[ CrudMethods.FIND_MANY, CrudMethods.FIND_ONE, CrudMethods.UPSERT_ONE, CrudMethods.UPDATE_MANY, CrudMethods.UPDATE_ONE, CrudMethods.DELETE_ONE, CrudMethods.DELETE_MANY, CrudMethods.PATCH_MANY, ], exclude_columns=[]) friend_model_set = sqlalchemy_to_pydantic(db_model=Child, crud_methods=[ CrudMethods.FIND_MANY, CrudMethods.UPSERT_MANY, CrudMethods.UPDATE_MANY, CrudMethods.DELETE_MANY, CrudMethods.PATCH_MANY, ], exclude_columns=[]) crud_route_1 = crud_router_builder(db_session=get_transaction_session, crud_models=user_model_set, db_model=Parent, prefix="/Parent", dependencies=[], async_mode=True, tags=["Parent"] ) crud_route_2 = crud_router_builder(db_session=get_transaction_session, crud_models=friend_model_set, db_model=Child, async_mode=True, prefix="/Child", dependencies=[], tags=["Child"] ) app.include_router(crud_route_1) app.include_router(crud_route_2) uvicorn.run(app, host="0.0.0.0", port=8000, debug=False) ================================================ FILE: tutorial/relationship/one_to_many.py ================================================ import asyncio from datetime import datetime, timezone import uvicorn from fastapi import FastAPI from sqlalchemy import Column, Integer, \ String, Table, ForeignKey, DateTime, Text, text, select, Index, UniqueConstraint from sqlalchemy.dialects.postgresql import UUID, ARRAY from sqlalchemy.orm import declarative_base, sessionmaker, relationship from fastapi_quickcrud import CrudMethods from fastapi_quickcrud import crud_router_builder from fastapi_quickcrud import sqlalchemy_to_pydantic app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession engine = create_async_engine('postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres', future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(bind=engine, class_=AsyncSession) async def get_transaction_session() -> AsyncSession: async with async_session() as session: async with session.begin(): yield session from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, ForeignKey, Index, Integer, JSON, LargeBinary, Numeric, SmallInteger, String, Table, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, TIMESTAMP, UUID from sqlalchemy.orm import relationship from sqlalchemy.sql.sqltypes import NullType from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() metadata = Base.metadata class Parent(Base): __tablename__ = 'parent_one_to_many_back_ref' id = Column(Integer, primary_key=True) children = relationship("Child", backref="parent_one_to_many_back_ref") class Child(Base): __tablename__ = 'child_one_to_many_back_ref' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('parent_one_to_many_back_ref.id')) @app.on_event("startup") async def startup_event(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) user_model_set = sqlalchemy_to_pydantic(db_model=Parent, crud_methods=[ CrudMethods.FIND_MANY, CrudMethods.FIND_ONE, CrudMethods.UPSERT_ONE, CrudMethods.UPDATE_MANY, CrudMethods.UPDATE_ONE, CrudMethods.DELETE_ONE, CrudMethods.DELETE_MANY, CrudMethods.PATCH_MANY, ], exclude_columns=[]) friend_model_set = sqlalchemy_to_pydantic(db_model=Child, crud_methods=[ CrudMethods.FIND_MANY, CrudMethods.UPSERT_MANY, CrudMethods.UPDATE_MANY, CrudMethods.DELETE_MANY, CrudMethods.PATCH_MANY, ], exclude_columns=[]) crud_route_1 = crud_router_builder(db_session=get_transaction_session, crud_models=user_model_set, db_model=Parent, prefix="/Parent", dependencies=[], async_mode=True, tags=["Parent"] ) crud_route_2 = crud_router_builder(db_session=get_transaction_session, crud_models=friend_model_set, db_model=Child, async_mode=True, prefix="/Child", dependencies=[], tags=["Child"] ) app.include_router(crud_route_1) app.include_router(crud_route_2) uvicorn.run(app, host="0.0.0.0", port=8000, debug=False) ================================================ FILE: tutorial/relationship/one_to_one.py ================================================ import uvicorn from fastapi import FastAPI from sqlalchemy import Column, ForeignKey, Integer from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy.orm import sessionmaker from fastapi_quickcrud import crud_router_builder app = FastAPI() Base = declarative_base() metadata = Base.metadata engine = create_async_engine('postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres', future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(bind=engine, class_=AsyncSession) async def get_transaction_session() -> AsyncSession: async with async_session() as session: async with session.begin(): yield session Base = declarative_base() metadata = Base.metadata class Parent(Base): __tablename__ = 'parent_o2o' id = Column(Integer, primary_key=True) # one-to-many collection children = relationship("Child", back_populates="parent") class Child(Base): __tablename__ = 'child_o2o' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('parent_o2o.id')) # many-to-one scalar parent = relationship("Parent", back_populates="children") @app.on_event("startup") async def startup_event(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) crud_route_1 = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/Parent", tags=['parent'] ) crud_route_2 = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/Child", tags=['child'] ) app.include_router(crud_route_1) app.include_router(crud_route_2) uvicorn.run(app, host="0.0.0.0", port=8000, debug=False) ================================================ FILE: tutorial/sample.py ================================================ from fastapi import FastAPI from sqlalchemy import * from sqlalchemy.orm import * from fastapi_quickcrud.crud_router import generic_sql_crud_router_builder Base = declarative_base() class Parent(Base): __tablename__ = 'parent_o2o' id = Column(Integer, primary_key=True, comment='test-test-test') name = Column(String, default='ok', unique = True) children = relationship("Child", back_populates="parent") class Child(Base): __tablename__ = 'child_o2o' id = Column(Integer, primary_key=True, comment='child_pk_test') parent_id = Column(Integer, ForeignKey('parent_o2o.id'), info=({'description': 'child_parent_id_test'})) parent = relationship("Parent", back_populates="children") crud_route_parent = generic_sql_crud_router_builder( db_model=Parent, prefix="/parent", tags=["parent"], ) crud_route_child = generic_sql_crud_router_builder( db_model=Child, prefix="/child", tags=["child"] ) app = FastAPI() [app.include_router(i) for i in [crud_route_parent, crud_route_child]] @app.get("/", tags=["child"]) async def root(): return {"message": "Hello World"} import uvicorn uvicorn.run(app, host="0.0.0.0", port=8002, debug=False) ================================================ FILE: tutorial/sample_case.py ================================================ import uvicorn from fastapi import FastAPI from sqlalchemy import Column, Integer, \ String, Table, ForeignKey, orm from fastapi_quickcrud import crud_router_builder Base = orm.declarative_base() class User(Base): __tablename__ = 'test_users' id = Column(Integer, primary_key=True, autoincrement=True, unique=True) name = Column(String, nullable=False) email = Column(String, nullable=False) friend = Table( 'test_friend', Base.metadata, Column('id', ForeignKey('test_users.id', ondelete='CASCADE', onupdate='CASCADE'), nullable=False), Column('friend_name', String, nullable=False) ) crud_route_1 = crud_router_builder(db_model=User, prefix="/user", tags=["User"], async_mode=True ) crud_route_2 = crud_router_builder(db_model=friend, prefix="/friend", tags=["friend"], async_mode=True ) app = FastAPI() app.include_router(crud_route_1) app.include_router(crud_route_2) uvicorn.run(app, host="0.0.0.0", port=8002) ================================================ FILE: tutorial/sample_two_table.py ================================================ import uvicorn from fastapi import FastAPI from sqlalchemy.orm import declarative_base, sessionmaker, synonym from fastapi_quickcrud import crud_router_builder app = FastAPI() Base = declarative_base() metadata = Base.metadata from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession engine = create_async_engine('postgresql+asyncpg://postgres:1234@127.0.0.1:5432/postgres', future=True, echo=True, pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200) async_session = sessionmaker(bind=engine, class_=AsyncSession) async def get_transaction_session() -> AsyncSession: async with async_session() as session: async with session.begin(): yield session from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, ForeignKey, Index, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Table, Text, Time, UniqueConstraint, text from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, TIMESTAMP, UUID from sqlalchemy.orm import relationship from sqlalchemy.sql.sqltypes import NullType from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() metadata = Base.metadata class Category(Base): __tablename__ = 'category' category_id = Column(Integer, primary_key=True, server_default=text("nextval('category_category_id_seq'::regclass)")) name = Column(String(50)) movies = relationship('Movie', secondary='movie_category_junction') t_critical_fault_chart = Table( 'critical_fault_chart', metadata, Column('log_datetime', TIMESTAMP(True, 0)), Column('site_code', String), Column('site_name', String), Column('equipment_type', String(64)), Column('crit_fault_cnt', BigInteger) ) class DataRestCachingCompOption(Base): __tablename__ = 'data_rest_caching_comp_option' comp_id = Column(Integer, primary_key=True, server_default=text("nextval('data_rest_caching_comp_option_comp_id_seq'::regclass)")) comp_hash = Column(CHAR(64), nullable=False, unique=True) comp_content = Column(JSONB(astext_type=Text()), nullable=False) created_at = Column(DateTime(True), server_default=text("now()")) class DataRestCachingFilterOption(Base): __tablename__ = 'data_rest_caching_filter_option' filter_id = Column(Integer, primary_key=True, server_default=text("nextval('data_rest_caching_filter_option_filter_id_seq'::regclass)")) filter_hash = Column(CHAR(64), nullable=False, unique=True) filter_content = Column(JSONB(astext_type=Text()), nullable=False) created_at = Column(DateTime(True), server_default=text("now()")) class DataRestCachingQueryOption(Base): __tablename__ = 'data_rest_caching_query_option' query_id = Column(Integer, primary_key=True, server_default=text("nextval('data_rest_caching_query_option_query_id_seq'::regclass)")) query_hash = Column(CHAR(64), nullable=False, unique=True) query_content = Column(JSONB(astext_type=Text()), nullable=False) created_at = Column(DateTime(True), server_default=text("now()")) t_data_rest_pre_aggregated_data_view = Table( 'data_rest_pre_aggregated_data_view', metadata, Column('site_code', String(24)), Column('timestamp', DateTime(True)), Column('query_hash', CHAR(64)), Column('filter_hash', CHAR(64)), Column('comp_hash', CHAR(64)), Column('payload', LargeBinary), Column('updated_at', DateTime(True)) ) t_display_fault = Table( 'display_fault', metadata, Column('log_datetime', TIMESTAMP(True, 0)), Column('site_name_en', String), Column('site_code', String), Column('device_name', String), Column('equip_type_name', String(64)), Column('detailed_result', JSONB(astext_type=Text())), Column('plot_metadata', JSONB(astext_type=Text())), Column('impact', JSONB(astext_type=Text())) ) t_equipment_fault_overview = Table( 'equipment_fault_overview', metadata, Column('log_datetime', TIMESTAMP(True, 0)), Column('site_code', String), Column('site_name', String), Column('equip_type_name', String(64)), Column('crit_fault_cnt', BigInteger), Column('minor_fault_cnt', BigInteger) ) class EquipmentTypeNew(Base): __tablename__ = 'equipment_type_new' __table_args__ = ( UniqueConstraint('equip_type_id', 'equip_type_name'), ) equip_type_id = Column(Integer, primary_key=True, unique=True, server_default=text("nextval('equipment_type_equip_type_id_seq'::regclass)")) created_at = Column(DateTime(True), nullable=False, server_default=text("now()")) updated_at = Column(DateTime(True)) equip_type_name = Column(String(64), nullable=False, unique=True) class EquipmentType(Base): __tablename__ = 'equipment_types' equip_type_id = Column(Integer, primary_key=True, server_default=text("nextval('equipment_types_equip_type_id_seq'::regclass)")) equip_type_name = Column(String(64), nullable=False, unique=True) creation_time = Column(DateTime(True), server_default=text("now()")) class Example(Base): __tablename__ = 'example' __table_args__ = ( UniqueConstraint('p_id', 'test'), ) p_id = Column(Integer, primary_key=True) test = Column(Integer) test_1 = Column(Text) class ExampleTable(Base): __tablename__ = 'example_table' __table_args__ = ( UniqueConstraint('id', 'int4_value', 'float4_value'), ) id = Column(Integer, primary_key=True, server_default=text("nextval('untitled_table_256_id_seq'::regclass)")) bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float(53), nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) t_fault_diagnosis_view = Table( 'fault_diagnosis_view', metadata, Column('log_datetime', TIMESTAMP(True, 0)), Column('site_code', String), Column('device_name', String), Column('detailed_result', JSONB(astext_type=Text())), Column('plot_metadata', JSONB(astext_type=Text())), Column('severity', String(16)), Column('equip_type_id', Integer), Column('equip_type_name', String(64)), Column('impact', JSONB(astext_type=Text())) ) t_fault_features_view = Table( 'fault_features_view', metadata, Column('log_date', Date), Column('site_code', String(24)), Column('device_name', String(64)), Column('feature_name', String(64)), Column('sub_type', String(64)), Column('value_json', JSONB(astext_type=Text())) ) t_fault_list = Table( 'fault_list', metadata, Column('log_datetime', DateTime(True)), Column('site_code', String), Column('site_name', String), Column('device_name', String), Column('equip_type_name', String(64)), Column('severity', String(16)), Column('impact', JSONB(astext_type=Text())), Column('fault_cnt', BigInteger), Column('detailed_result', JSONB(astext_type=Text())), Column('fault_category', JSONB(astext_type=Text())) ) class FunctionGroup(Base): __tablename__ = 'function_group' func_group_id = Column(String(5), primary_key=True) func_group_name = Column(String, nullable=False) created_at = Column(DateTime(True)) updated_at = Column(DateTime(True)) deleted_at = Column(DateTime(True)) function_catagory = Column(String(20), nullable=False, server_default=text("'site'::character varying")) t_list_of_critical_fault = Table( 'list_of_critical_fault', metadata, Column('log_datetime', TIMESTAMP(True, 0)), Column('site_code', String), Column('site_name', String), Column('device_name', String), Column('severity', String(16)), Column('equipment_type', String(64)), # Column('impact', JSONB(astext_type=Text())), # Column('fault_issue', JSONB(astext_type=Text())) ) class Movie(Base): __tablename__ = 'movie' movie_id = Column(Integer, primary_key=True, server_default=text("nextval('movie_movie_id_seq'::regclass)")) name = Column(String(50)) class ProcessedFilter(Base): __tablename__ = 'processed_filter' filter_id = Column(Integer, primary_key=True, server_default=text("nextval('processed_filter_filter_id_seq'::regclass)")) name = Column(String, nullable=False, unique=True) class ProcessedResolution(Base): __tablename__ = 'processed_resolution' resolution_id = Column(Integer, primary_key=True, server_default=text("nextval('processed_resolution_resolution_id_seq'::regclass)")) name = Column(String, nullable=False, unique=True) class ProcessedValue(Base): __tablename__ = 'processed_value' pid = Column(UUID, primary_key=True, nullable=False) timestamp = Column(DateTime(True), primary_key=True, nullable=False) count = Column(Integer, nullable=False) value = Column(Float(53)) sum = Column(Float(53)) mean = Column(Float(53)) std = Column(Float(53)) min = Column(Float(53)) max = Column(Float(53)) median = Column(Float(53)) class RefCode(Base): __tablename__ = 'ref_code' code_key = Column(String, primary_key=True, nullable=False) code_type = Column(String, primary_key=True, nullable=False) code_sub_type = Column(String, primary_key=True, nullable=False) descn = Column(String) created_at = Column(DateTime(True), nullable=False) updated_at = Column(DateTime(True), nullable=False) deleted_at = Column(DateTime(True)) class RefFilter(Base): __tablename__ = 'ref_filter' code_key = Column(String(20), primary_key=True, nullable=False) code_type = Column(String(20), primary_key=True, nullable=False) processed_filter_id = Column(SmallInteger, nullable=False) descn = Column(String(100)) created_at = Column(DateTime(True), nullable=False) updated_at = Column(DateTime(True), nullable=False) deleted_at = Column(DateTime(True)) code_sub_type = Column(String(20)) class RefResolution(Base): __tablename__ = 'ref_resolution' code_key = Column(String(20), primary_key=True, nullable=False) code_type = Column(String(20), primary_key=True, nullable=False) processed_resolution_id = Column(SmallInteger, nullable=False) descn = Column(String(100)) created_at = Column(DateTime(True), nullable=False) updated_at = Column(DateTime(True), nullable=False) deleted_at = Column(DateTime(True)) class RefSymptomGroup(Base): __tablename__ = 'ref_symptom_group' id = Column(String(40), primary_key=True) description = Column(String(100)) created_at = Column(DateTime(True), nullable=False) updated_at = Column(DateTime(True), nullable=False) deleted_at = Column(DateTime(True)) class RelationshipTestA(Base): __tablename__ = 'relationship_test_a' id = Column(Integer, primary_key=True, server_default=text("nextval('untitled_table_271_id_seq'::regclass)")) name = Column(String, nullable=False) email = Column(String, nullable=False) class Sometable(Base): __tablename__ = 'sometable' __table_args__ = ( UniqueConstraint('col1', 'col2'), ) id = Column(Integer, primary_key=True, server_default=text("nextval('sometable_id_seq'::regclass)")) col1 = Column(Integer, nullable=False) col2 = Column(Integer, nullable=False) class TempSite(Base): __tablename__ = 'temp_sites' site_name_chn = Column(String) site_name_en = Column(String) tenant_id = Column(UUID, nullable=False) version = Column(Integer, nullable=False, server_default=text("0")) created_at = Column(DateTime(True), nullable=False) updated_at = Column(DateTime(True), nullable=False) deleted_at = Column(DateTime(True)) site_code = Column(String, primary_key=True) photo = Column(String) location = Column(String) weather_station = Column(String) is_activate = Column(Boolean) class Tenant(Base): __tablename__ = 'tenants' id = Column(UUID, primary_key=True) tenant_code = Column(String(10), nullable=False, unique=True) tenant_name_en = Column(String(750), server_default=text("NULL::character varying")) tenant_name_chn = Column(String(150), server_default=text("NULL::character varying")) logo = Column(String(1000), server_default=text("NULL::character varying")) created_at = Column(DateTime(True), nullable=False) updated_at = Column(DateTime(True), nullable=False) deleted_at = Column(DateTime(True), index=True) version = Column(Integer, nullable=False, server_default=text("0")) class TestAliasUniqueColumn(Base): __tablename__ = 'test_alias_unique_column' __table_args__ = ( UniqueConstraint('id', 'test_case_column', 'float4_value'), ) id = Column(UUID, primary_key=True, server_default=text("uuid_generate_v4()")) bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float(53), nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) test_case_column = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) class TestAliasUniqueColumnAsync(Base): __tablename__ = 'test_alias_unique_column_async' __table_args__ = ( UniqueConstraint('id', 'test_case_column', 'float4_value'), ) id = Column(UUID, primary_key=True, server_default=text("uuid_generate_v4()")) bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float(53), nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) test_case_column = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) class TestBuildMyself(Base): __tablename__ = 'test_build_myself' __table_args__ = ( UniqueConstraint('id', 'int4_value', 'float4_value'), ) id = Column(Integer, primary_key=True, server_default=text("nextval('test_build_myself_id_seq'::regclass)")) bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float(53), nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) class TestBuildMyselfAsync(Base): __tablename__ = 'test_build_myself_async' __table_args__ = ( UniqueConstraint('id', 'int4_value', 'float4_value'), ) id = Column(Integer, primary_key=True, server_default=text("nextval('test_build_myself_async_id_seq'::regclass)")) bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float(53), nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) class TestNoAlia(Base): __tablename__ = 'test_no_alias' __table_args__ = ( UniqueConstraint('id', 'int4_value', 'float4_value'), ) id = Column(UUID, primary_key=True, server_default=text("uuid_generate_v4()")) bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float(53), nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) class TestNoAliasAsync(Base): __tablename__ = 'test_no_alias_async' __table_args__ = ( UniqueConstraint('id', 'int4_value', 'float4_value'), ) id = Column(UUID, primary_key=True, server_default=text("uuid_generate_v4()")) bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float(53), nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) class TestTable(Base): __tablename__ = 'test_table' __table_args__ = ( UniqueConstraint('primary_key', 'int4_value', 'float4_value'), ) primary_key = Column(Integer, primary_key=True, server_default=text("nextval('test_table_primary_key_seq'::regclass)")) bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float(53), nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) class TestUuidPrimary(Base): __tablename__ = 'test_uuid_primary' __table_args__ = ( UniqueConstraint('primary_key', 'int4_value', 'float4_value'), ) primary_key = Column(UUID, primary_key=True, server_default=text("uuid_generate_v4()")) bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float(53), nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) class TestUuidPrimaryAsync(Base): __tablename__ = 'test_uuid_primary_async' __table_args__ = ( UniqueConstraint('primary_key', 'int4_value', 'float4_value'), ) primary_key = Column(UUID, primary_key=True, server_default=text("uuid_generate_v4()")) bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float(53), nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) class TestUuidPrimarySync(Base): __tablename__ = 'test_uuid_primary_sync' __table_args__ = ( UniqueConstraint('id', 'int4_value', 'float4_value'), ) id = Column(UUID, primary_key=True, server_default=text("uuid_generate_v4()")) bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float(53), nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) varchar_value = Column(String) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) # class UntitledTable256(Base): # __tablename__ = 'untitled_table_256' # __table_args__ = ( # UniqueConstraint('id', 'int4_value', 'float4_value'), # ) # # id = Column(Integer, primary_key=True, nullable=False, # server_default=text("nextval('untitled_table_256_id_seq'::regclass)")) # bool_value = Column(Boolean, primary_key=True, nullable=False, server_default=text("false")) # bytea_value = Column(LargeBinary) # char_value = Column(CHAR(10)) # date_value = Column(Date, server_default=text("now()")) # float4_value = Column(Float, nullable=False) # float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) # int2_value = Column(SmallInteger, nullable=False) # int4_value = Column(Integer, nullable=False) # int8_value = Column(BigInteger, server_default=text("99")) # interval_value = Column(INTERVAL) # json_value = Column(JSON) # jsonb_value = Column(JSONB(astext_type=Text())) # numeric_value = Column(Numeric) # text_value = Column(Text) # time_value = Column(Time) # timestamp_value = Column(DateTime) # timestamptz_value = Column(DateTime(True)) # timetz_value = Column(Time(True)) # uuid_value = Column(UUID) # varchar_value = Column(String) # xml_value = Column(NullType) # array_value = Column(ARRAY(Integer())) # array_str__value = Column(ARRAY(String())) # box_valaue = Column(NullType) t_user_group_dashboard = Table( 'user_group_dashboard', metadata, Column('ordering', Integer, nullable=False), Column('created_at', DateTime(True), nullable=False), Column('updated_at', DateTime(True), nullable=False), Column('deleted_at', DateTime(True)), Column('dashboard_id', UUID, nullable=False), Column('user_group_id', UUID, nullable=False), Column('tenant_id', UUID, nullable=False), Column('children_list', ARRAY(UUID())), Column('created_by', UUID), Column('item_type', String) ) t_user_policy_table = Table( 'user_policy_table', metadata, Column('user_group_name', String), Column('group_id', UUID), Column('policy_level', Integer), Column('policy_name', String), Column('policy_id', UUID), Column('site_code', String), Column('user_info', JSON), Column('available_function', JSON) ) class ZFaultDiagnosisType(Base): __tablename__ = 'z_fault_diagnosis_type' diagnosis_type_id = Column(Integer, primary_key=True, server_default=text("nextval('z_fault_diagnosis_type_diagnosis_type_id_seq'::regclass)")) created_at = Column(DateTime(True), nullable=False, server_default=text("now()")) updated_at = Column(DateTime(True)) severity = Column(String(16)) impact = Column(JSONB(astext_type=Text())) recommendation = Column(JSONB(astext_type=Text())) issue = Column(JSONB(astext_type=Text())) class FaultFeatureTypeNew(Base): __tablename__ = 'fault_feature_type_new' __table_args__ = ( UniqueConstraint('equip_type_id', 'feature_name', 'sub_type', 'frequency', 'attribute_name'), ) feature_type_id = Column(Integer, primary_key=True, server_default=text("nextval('fault_feature_type_feature_type_id_seq'::regclass)")) equip_type_id = Column(ForeignKey('equipment_type_new.equip_type_id'), nullable=False) created_at = Column(DateTime(True), nullable=False, server_default=text("now()")) updated_at = Column(DateTime(True)) feature_name = Column(String(64), nullable=False) sub_type = Column(String(64), nullable=False) frequency = Column(String(16), nullable=False) attribute_name = Column(JSONB(astext_type=Text()), nullable=False) equip_type = relationship('EquipmentTypeNew') class FaultFeatureType(Base): __tablename__ = 'fault_feature_types' __table_args__ = ( UniqueConstraint('feature_name', 'sub_type', 'equip_type_id'), ) feature_type_id = Column(Integer, primary_key=True, server_default=text("nextval('fault_feature_types_feature_type_id_seq'::regclass)")) feature_name = Column(String(64), nullable=False) sub_type = Column(String(64), nullable=False) equip_type_id = Column(ForeignKey('equipment_types.equip_type_id'), nullable=False) creation_time = Column(DateTime(True), server_default=text("now()")) equip_type = relationship('EquipmentType') class FaultSymptomType(Base): __tablename__ = 'fault_symptom_type' __table_args__ = ( UniqueConstraint('equip_type_id', 'symptom_name', 'frequency', 'attribute_names'), ) symptom_type_id = Column(Integer, primary_key=True, server_default=text("nextval('fault_symptom_type_symptom_type_id_seq'::regclass)")) created_at = Column(DateTime(True), nullable=False, server_default=text("now()")) updated_at = Column(DateTime(True)) symptom_name = Column(String(64), nullable=False) frequency = Column(String(16), nullable=False) attribute_names = Column(String(64), nullable=False) equip_type_id = Column(ForeignKey('equipment_type_new.equip_type_id'), nullable=False) equip_type = relationship('EquipmentTypeNew') class Function(Base): __tablename__ = 'functions' func_id = Column(String(10), primary_key=True) func_name = Column(String(100)) created_at = Column(DateTime(True)) updated_at = Column(DateTime(True)) deleted_at = Column(DateTime(True)) func_group_id = Column(ForeignKey('function_group.func_group_id')) func_group = relationship('FunctionGroup') t_movie_category_junction = Table( 'movie_category_junction', metadata, Column('movie_id', ForeignKey('movie.movie_id'), primary_key=True, nullable=False), Column('category_id', ForeignKey('category.category_id'), primary_key=True, nullable=False) ) t_relationship_test_b = Table( 'relationship_test_b', metadata, Column('id', ForeignKey('relationship_test_a.id', ondelete='CASCADE', onupdate='CASCADE'), nullable=False), Column('friend', String, nullable=False) ) class Site(Base): __tablename__ = 'sites' id = Column(String(24), primary_key=True) site_name_chn = Column(String) site_name_en = Column(String) tenant_id = Column(ForeignKey('tenants.id', ondelete='SET NULL', onupdate='CASCADE'), nullable=False) version = Column(Integer, nullable=False, server_default=text("0")) created_at = Column(DateTime(True), nullable=False) updated_at = Column(DateTime(True), nullable=False) deleted_at = Column(DateTime(True)) site_code = Column(String, unique=True) photo = Column(String) location = Column(String) weather_station = Column(String) is_activate = Column(Boolean) tenant = relationship('Tenant') class TenantPolicy(Base): __tablename__ = 'tenant_policy' id = Column(UUID, primary_key=True, server_default=text("uuid_generate_v4()")) tenant_id = Column(ForeignKey('tenants.id'), nullable=False) policy_name = Column(String, nullable=False) created_at = Column(DateTime(True)) updated_at = Column(DateTime(True)) deleted_at = Column(DateTime(True)) policy_level = Column(Integer, nullable=False) tenant = relationship('Tenant') class UserGroup(Base): __tablename__ = 'user_group' id = Column(UUID, primary_key=True, server_default=text("uuid_generate_v4()")) tenant_id = Column(ForeignKey('tenants.id', onupdate='CASCADE'), nullable=False) group_name = Column(String, nullable=False) created_at = Column(DateTime(True)) updated_at = Column(DateTime(True)) deleted_at = Column(DateTime(True)) description = Column(Text) policy_id = Column(UUID) icon_url = Column(Text) tenant = relationship('Tenant') class User(Base): __tablename__ = 'users' id = Column(UUID, primary_key=True) first_name = Column(String(30)) last_name = Column(String(70)) email = Column(String(100), nullable=False, unique=True) avatar = Column(String(1000), server_default=text("NULL::character varying")) created_at = Column(DateTime(True), nullable=False) updated_at = Column(DateTime(True), nullable=False) deleted_at = Column(DateTime(True), index=True) version = Column(Integer, nullable=False, server_default=text("0")) tenant_id = Column(ForeignKey('tenants.id', ondelete='SET NULL', onupdate='CASCADE'), nullable=False, index=True) active = Column(Boolean, nullable=False, server_default=text("false")) tenant = relationship('Tenant') class WidgetInfo(Base): __tablename__ = 'widget_info' id = Column(UUID, primary_key=True) method_template_id = Column(String) title = Column(String) widget_type = Column(String, nullable=False) tenant_id = Column(ForeignKey('tenants.id'), nullable=False) polling_interval = Column(Integer) internal_dataset = Column(JSONB(astext_type=Text())) created_at = Column(DateTime(True)) updated_at = Column(DateTime(True)) deleted_at = Column(DateTime(True)) local_start_date = Column(DateTime(True)) local_end_date = Column(DateTime(True)) created_by = Column(UUID) local_filter_option = Column(JSONB(astext_type=Text())) local_groupby = Column(String(255)) point_configs = Column(JSONB(astext_type=Text())) groupby_point_configs = Column(JSONB(astext_type=Text())) chart_data = Column(ARRAY(JSONB(astext_type=Text()))) axis_config = Column(JSONB(astext_type=Text())) axis = Column(JSONB(astext_type=Text())) extra_axis = Column(JSONB(astext_type=Text())) legend_orientation = Column(String) legend_location = Column(String) legend = Column(JSONB(astext_type=Text())) color_palette = Column(ARRAY(String())) marker_symbol = Column(String) extra_axis_data = Column(ARRAY(JSONB(astext_type=Text()))) alignment = Column(String) required_other_data_source = Column(Boolean) extra_columns = Column(ARRAY(String())) testing_colors = Column(JSONB(astext_type=Text())) subtitle = Column(String) desc = Column(String) ref_widget_data_id = Column(UUID) extra_rows = Column(JSONB(astext_type=Text())) horizontal_rows = Column(ARRAY(String())) model_unit = Column(String) chart_data_2 = Column(JSONB(astext_type=Text())) tenant = relationship('Tenant') t_apikeys = Table( 'apikeys', metadata, Column('user_id', ForeignKey('users.id', ondelete='CASCADE', onupdate='CASCADE'), nullable=False), Column('apikey', String, nullable=False, unique=True), Column('description', String), Column('created_at', DateTime(True), server_default=text("CURRENT_TIMESTAMP")) ) class Dashboard(Base): __tablename__ = 'dashboards' id = Column(UUID, primary_key=True, info={'alias_name': 'primary_key'}) icon = Column(String(1000), server_default=text("NULL::character varying")) name_en = Column(String(750), nullable=False) name_chn = Column(String(150), nullable=False) created_at = Column(DateTime(True), nullable=False) updated_at = Column(DateTime(True), nullable=False) deleted_at = Column(DateTime(True)) version = Column(Integer, nullable=False, server_default=text("0")) tenant_id = Column(ForeignKey('tenants.id', ondelete='SET NULL', onupdate='CASCADE'), nullable=False, index=True) descn_en = Column(String) descn_chn = Column(String) site_id = Column(ForeignKey('sites.id', onupdate='CASCADE'), index=True) compact_type = Column(String(10), server_default=text("'vertical'::character varying")) item_type = Column(String, nullable=False) site = relationship('Site') tenant = relationship('Tenant') class DataRestCachingPayload(Base): __tablename__ = 'data_rest_caching_payload' site_code = Column(ForeignKey('sites.site_code', ondelete='CASCADE'), primary_key=True, nullable=False) timestamp = Column(DateTime(True), primary_key=True, nullable=False) query_id = Column(ForeignKey('data_rest_caching_query_option.query_id', ondelete='CASCADE'), primary_key=True, nullable=False) filter_id = Column(ForeignKey('data_rest_caching_filter_option.filter_id', ondelete='CASCADE'), primary_key=True, nullable=False) comp_id = Column(ForeignKey('data_rest_caching_comp_option.comp_id', ondelete='CASCADE'), primary_key=True, nullable=False) payload = Column(LargeBinary) updated_at = Column(DateTime(True), server_default=text("now()")) comp = relationship('DataRestCachingCompOption') filter = relationship('DataRestCachingFilterOption') query = relationship('DataRestCachingQueryOption') site = relationship('Site') class Device(Base): __tablename__ = 'devices' __table_args__ = ( UniqueConstraint('site_code', 'device_name'), ) device_id = Column(Integer, primary_key=True, server_default=text("nextval('devices_device_id_seq'::regclass)")) site_code = Column(ForeignKey('sites.site_code'), nullable=False) device_name = Column(String(64), nullable=False) equip_type_id = Column(ForeignKey('equipment_types.equip_type_id')) creation_time = Column(DateTime(True), server_default=text("now()")) equip_type = relationship('EquipmentType') site = relationship('Site') class FaultDiagnosi(Base): __tablename__ = 'fault_diagnosis' __table_args__ = ( UniqueConstraint('log_datetime', 'site_code', 'equip_type_id', 'device_name'), ) fault_id = Column(Integer, primary_key=True, server_default=text("nextval('vav_faults_fault_id_seq'::regclass)")) log_datetime = Column(TIMESTAMP(True, 0), nullable=False) detailed_result = Column(JSONB(astext_type=Text())) plot_metadata = Column(JSONB(astext_type=Text())) severity = Column(String(16)) equip_type_id = Column(ForeignKey('equipment_types.equip_type_id')) fault_category = Column(JSONB(astext_type=Text())) device_name = Column(String) site_code = Column(ForeignKey('sites.site_code')) created_at = Column(DateTime(True), nullable=False, server_default=text("now()")) updated_at = Column(DateTime(True)) impact = Column(JSONB(astext_type=Text()), server_default=text("'[]'::jsonb")) equip_type = relationship('EquipmentType') site = relationship('Site') class FaultFeatureNew(Base): __tablename__ = 'fault_feature_new' log_datetime = Column(DateTime(True), primary_key=True, nullable=False) created_at = Column(DateTime(True), nullable=False, server_default=text("now()")) updated_at = Column(DateTime(True)) feature_type_id = Column(ForeignKey('fault_feature_type_new.feature_type_id'), primary_key=True, nullable=False) value_json = Column(JSONB(astext_type=Text())) site_code = Column(ForeignKey('sites.site_code'), primary_key=True, nullable=False) device_name = Column(String(64), primary_key=True, nullable=False) feature_type = relationship('FaultFeatureTypeNew') site = relationship('Site') class FaultSymptom(Base): __tablename__ = 'fault_symptom' log_datetime = Column(DateTime(True), primary_key=True, nullable=False) created_at = Column(DateTime(True), nullable=False, server_default=text("now()")) updated_at = Column(DateTime(True)) symptom_type_id = Column(ForeignKey('fault_symptom_type.symptom_type_id'), primary_key=True, nullable=False) detected = Column(Boolean, comment='conflict update') value_json = Column(JSONB(astext_type=Text()), comment='conflict update') device_name = Column(String, primary_key=True, nullable=False) site_code = Column(ForeignKey('sites.site_code'), primary_key=True, nullable=False) site = relationship('Site') symptom_type = relationship('FaultSymptomType') t_link_site_func_group = Table( 'link_site_func_group', metadata, Column('site_code', ForeignKey('sites.site_code'), nullable=False), Column('func_group_id', ForeignKey('function_group.func_group_id')), Column('created_at', DateTime(True)), Column('updated_at', DateTime(True)), Column('deleted_at', DateTime(True)) ) t_link_user_group = Table( 'link_user_group', metadata, Column('user_id', ForeignKey('users.id', onupdate='CASCADE'), nullable=False), Column('group_id', ForeignKey('user_group.id'), nullable=False), Column('created_at', DateTime(True)), Column('updated_at', DateTime(True)), Column('deleted_at', DateTime(True)) ) t_link_user_group_site_func = Table( 'link_user_group_site_func', metadata, Column('user_group_id', ForeignKey('user_group.id', onupdate='CASCADE'), nullable=False), Column('func_id', ForeignKey('functions.func_id'), nullable=False), Column('created_at', DateTime(True)), Column('updated_at', DateTime(True)), Column('deleted_at', DateTime(True)), Column('site_code', ForeignKey('sites.site_code'), nullable=False), Column('func_group_id', ForeignKey('function_group.func_group_id')) ) class FaultFeature(Base): __tablename__ = 'fault_features' device_id = Column(ForeignKey('devices.device_id'), primary_key=True, nullable=False) feature_type_id = Column(ForeignKey('fault_feature_types.feature_type_id'), primary_key=True, nullable=False) log_date = Column(Date, primary_key=True, nullable=False) value_json = Column(JSONB(astext_type=Text())) device = relationship('Device') feature_type = relationship('FaultFeatureType') class UserDashboard(Base): __tablename__ = 'user_dashboard' start_from = Column(DateTime(True)) start_to = Column(DateTime(True)) ordering = Column(Integer, nullable=False) created_at = Column(DateTime(True), nullable=False) updated_at = Column(DateTime(True), nullable=False) deleted_at = Column(DateTime(True), index=True) version = Column(Integer, nullable=False, server_default=text("0")) dashboard_id = Column(ForeignKey('dashboards.id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True, nullable=False, index=True) user_id = Column(ForeignKey('users.id', onupdate='CASCADE'), primary_key=True, nullable=False, index=True) tenant_id = Column(ForeignKey('tenants.id', ondelete='SET NULL', onupdate='CASCADE'), nullable=False, index=True) children_list = Column(ARRAY(UUID())) dashboard = relationship('Dashboard') tenant = relationship('Tenant') user = relationship('User') class WidgetLayout(Base): __tablename__ = 'widget_layout' __table_args__ = ( Index('widget_layout_widget_data_id_idx', 'deleted_at', 'widget_data_id'), Index('widget_layout_dashboard_id_idx', 'deleted_at', 'dashboard_id') ) dashboard_id = Column(ForeignKey('dashboards.id', ondelete='CASCADE', onupdate='CASCADE'), info={'alias_name': 'primary_key'}, primary_key=True, nullable=False) primary_key = synonym('dashboard_id') tenant_id = Column(ForeignKey('tenants.id', ondelete='SET NULL', onupdate='CASCADE'), nullable=False) widget_data_id = Column(ForeignKey('widget_info.id'), nullable=False) user_id = Column(ForeignKey('users.id', onupdate='CASCADE'), nullable=False) x = Column(Integer, nullable=False, server_default=text("0")) y = Column(Integer, nullable=False, server_default=text("0")) h = Column(Integer, nullable=False, server_default=text("0")) w = Column(Integer, nullable=False, server_default=text("0")) start_from = Column(DateTime(True)) start_to = Column(DateTime(True)) created_at = Column(DateTime(True), nullable=False) updated_at = Column(DateTime(True), nullable=False) deleted_at = Column(DateTime(True)) version = Column(Integer, nullable=False, server_default=text("0")) dashboard = relationship('Dashboard') tenant = relationship('Tenant') user = relationship('User') widget_data = relationship('WidgetInfo') class UntitledTable256(Base): __tablename__ = 'untitled_table_256' __table_args__ = ( UniqueConstraint('id', 'int4_value', 'float4_value'), ) id = Column(Integer, primary_key=True, nullable=False, server_default=text("nextval('untitled_table_256_id_seq'::regclass)")) bool_value = Column(Boolean, nullable=False, server_default=text("false")) bytea_value = Column(LargeBinary) char_value = Column(CHAR(10)) date_value = Column(Date, server_default=text("now()")) float4_value = Column(Float, nullable=False) float8_value = Column(Float(53), nullable=False, server_default=text("10.10")) int2_value = Column(SmallInteger, nullable=False) int4_value = Column(Integer, nullable=False) int8_value = Column(BigInteger, server_default=text("99")) interval_value = Column(INTERVAL) json_value = Column(JSON) jsonb_value = Column(JSONB(astext_type=Text())) numeric_value = Column(Numeric) text_value = Column(Text) time_value = Column(Time) timestamp_value = Column(DateTime) timestamptz_value = Column(DateTime(True)) timetz_value = Column(Time(True)) uuid_value = Column(UUID) varchar_value = Column(String) xml_value = Column(NullType) array_value = Column(ARRAY(Integer())) array_str__value = Column(ARRAY(String())) box_valaue = Column(NullType) def test(self): print('ok') association_table = Table('test_association', Base.metadata, Column('left_id', ForeignKey('test_left.id')), Column('right_id', ForeignKey('test_right.id')) ) association_table_second = Table('test_association_second', Base.metadata, Column('left_id_second', ForeignKey('test_left.id')), Column('right_id_second', ForeignKey('test_right_second.id')) ) class Child(Base): __tablename__ = 'test_right' id = Column(Integer, primary_key=True) class Parent(Base): __tablename__ = 'test_left' id = Column(Integer, primary_key=True) children = relationship("Child", secondary=association_table) children_second = relationship("ChildSecond", secondary=association_table_second) class ChildSecond(Base): __tablename__ = 'test_right_second' id = Column(Integer, primary_key=True) crud_route_child = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child", tags=["child"] ) crud_route_association_table_second = crud_router_builder(db_session=get_transaction_session, db_model=association_table_second, prefix="/association_table_second", tags=["association_table_second"] ) crud_route_child_second = crud_router_builder(db_session=get_transaction_session, db_model=Child, prefix="/child_second", tags=["child_second"] ) crud_route_parent = crud_router_builder(db_session=get_transaction_session, db_model=Parent, prefix="/parent", tags=["parent"] ) crud_route_association = crud_router_builder(db_session=get_transaction_session, db_model=association_table, prefix="/association", tags=["association"] ) [app.include_router(i) for i in [crud_route_association_table_second, crud_route_child_second, crud_route_parent, crud_route_child, crud_route_association]] # crud_route_2 = crud_router_builder(db_session=get_transaction_session, # db_model=UntitledTable256, # crud_methods=[ # CrudMethods.UPSERT_MANY, # ], # exclude_columns=['bytea_value', 'xml_value', 'box_valaue'], # prefix="/friend", # ) # app.include_router(crud_route_2) uvicorn.run(app, host="0.0.0.0", port=8002, debug=False)