Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: minor fixes and code style improvements #148

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
Open
14 changes: 12 additions & 2 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,18 @@ API_VERSION='v2'

OPENAPI_VERSION='3.0.3'

# Base URL for API provider.
BASE_URI=https://127.0.0.1:5000
# Determines the host address on which the Flask server will listen for
# incoming connections. By default, Flask uses the value
# '127.0.0.1' (localhost), which means that the server will be accessible only
# on the local machine. If you want to make the server accessible to external
# clients, you can set FLASK_RUN_HOST to the value '0.0.0.0' or another IP
# address of your server.
FLASK_RUN_HOST=127.0.0.1

# Defines the port on which the Flask server will run. By default, Flask uses
# port 5000. You can change this port by setting a value for FLASK_RUN_PORT
# according to your requirements.
FLASK_RUN_PORT=5000

# Local database to use w/o Docker. Comment it out to use the default value.
# To see the default value refer to 'provider.DevelopmentConfig' in
Expand Down
19 changes: 17 additions & 2 deletions .github/labeler.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,28 @@
# the LICENSE file that was distributed with this source code.

'open api':
- '.redocly.yaml'
- 'openapi/*.yaml'

python:
- any: ['provider/**/*']
- '**/*.py'
- 'setup.cfg'
- 'provider/**/*'
- 'requirements/*.in'
- 'requirements/*.txt'

javascript:
- 'package.json'
- 'package-lock.json'

dependencies:
- 'package.json'
- 'package-lock.json'
- 'requirements/*.in'
- 'requirements/*.txt'

github_actions:
- any: ['.github/**/*']
- '.github/workflows/*.yaml'

documentation:
- '*.rst'
File renamed without changes.
6 changes: 6 additions & 0 deletions .github/workflows/test-code.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,12 @@ jobs:
- name: Install dependencies
run: make install

- name: Setuptools self-test
run: |
python setup.py --fullname
python setup.py --long-description
python setup.py --classifiers

- name: Run unit tests with coverage
run: make test

Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@

# Application configuration
.env
.env.*
!.env.example

# Python cache.
*.py[cod]
Expand Down
12 changes: 10 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,6 @@ endef
requirements/%.txt: requirements/%.in $(VENV_BIN)
$(VENV_BIN)/pip-compile --allow-unsafe --generate-hashes --output-file=$@ $<

## Public targets

$(VENV_PYTHON): $(VENV_ROOT)
@echo

Expand All @@ -55,6 +53,8 @@ $(VENV_ROOT):
@echo
$(call mk-venv-link)

## Public targets

.PHONY: init
init: $(VENV_PYTHON)
@echo $(CS)Set up virtualenv$(CE)
Expand All @@ -79,6 +79,7 @@ uninstall:
@echo Done.
@echo

.PHONY: serve
serve: $(VENV_PYTHON) .env runner.py
@echo $(CS)Run builtin server$(CE)
$(VENV_BIN)/flask --app runner:app run --debug
Expand All @@ -90,6 +91,12 @@ migrate: $(VENV_PYTHON)
$(VENV_BIN)/flask --app runner:app db upgrade
@echo

.PHONY: shell
shell: $(PYTHON)
@echo $(CS)Starting a shell$(CE)
$(VENV_BIN)/flask --app runner:app shell
@echo

.PHONY: seed
seed: $(VENV_PYTHON)
@echo $(CS)Add seed data to the database$(CE)
Expand Down Expand Up @@ -156,6 +163,7 @@ help:
@echo ' uninstall: Uninstall local version of the project'
@echo ' serve: Run builtin server'
@echo ' migrate: Run database migrations'
@echo ' shell: Run a shell in the app context'
@echo ' seed: Add seed data to the database'
@echo ' lint: Lint the code'
@echo ' test: Run unit tests with coverage'
Expand Down
4 changes: 2 additions & 2 deletions default.mk
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
# For the full copyright and license information, please view
# the LICENSE file that was distributed with this source code.

# Run “make test” by default
.DEFAULT_GOAL = test
# Run “make help” by default
.DEFAULT_GOAL = help

ROOT_DIR := $(shell dirname $(realpath $(firstword $(MAKEFILE_LIST))))
PKG_NAME = provider
Expand Down
2 changes: 1 addition & 1 deletion provider/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,4 @@
__author__ = 'Serghei Iakovlev'
__author_email__ = '[email protected]'
__url__ = 'https://github.com/sergeyklay/provider-pact-example'
__description__ = 'Sample Products API'
__description__ = 'Sample Products API for contract testing purpose.'
9 changes: 8 additions & 1 deletion provider/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,10 +122,17 @@ def configure_context_processors(app: Flask):
import inspect
from provider import models

ctx = {}
for pair in inspect.getmembers(models, inspect.isclass):
# Do not reimport non-project models
if pair[1].__module__ == models.__name__:
ctx[pair[0]] = pair[1]

@app.shell_context_processor
def make_shell_context():
"""Configure flask shell command to autoimport app objects."""
return {
'app': app,
'db': db,
**dict(inspect.getmembers(models, inspect.isclass))}
**ctx
}
8 changes: 7 additions & 1 deletion provider/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@
# For the full copyright and license information, please view
# the LICENSE file that was distributed with this source code.

"""Module for managing the configuration of the application."""
"""Configuration module for the application.

Provides the base configuration and specific configurations for development,
testing, and production. Includes the 'config' dictionary for easy switching
between different configurations.

"""

import os

Expand Down
75 changes: 60 additions & 15 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,60 @@ def read_file(filepath):

def long_description():
"""Provide long description for package."""
contents = (
'====================',
'Provider API Example',
'====================',
'',
'Sample Products API for contract testing purpose.',
)

return '\n'.join(contents)
def extract_text_between(text, start, end) -> str:
pattern = f'{re.escape(start)}(.*?){re.escape(end)}'
result = re.search(pattern, text, re.DOTALL)
return result.group(1) if result else ''

def description() -> str:
readme = path.join(PKG_DIR, 'README.rst')
if not path.isfile(readme):
return ''

text = read_file(readme)
return extract_text_between(
text,
'.. teaser-begin',
'.. teaser-end'
).strip()

def changes() -> str:
changelog = path.join(PKG_DIR, 'CHANGELOG.rst')
if not path.isfile(changelog):
return ''

pattern = (fr'({VERSION_REGEX} \(.*?\)\r?\n.*?)'
r'\r?\n\r?\n\r?\n----\r?\n\r?\n\r?\n')
result = re.search(pattern, read_file(changelog), re.S)

return result.group(1) if result else ''

try:
title = f"{PKG_NAME}: {find_meta('description')}"
head = '=' * (len(title) - 1)

contents = (
head,
format(title.strip(' .')),
head,
'',
description(),
'',
'Release Information',
'===================\n',
changes(),
'',
f"`Full changelog <{find_meta('url')}/blob/main/CHANGELOG.rst>`_.",
'',
read_file(path.join(PKG_DIR, 'SECURITY.rst')),
'',
read_file(path.join(PKG_DIR, 'AUTHORS.rst')),
)
return '\n'.join(contents)
except (RuntimeError, FileNotFoundError) as read_error:
message = 'Long description could not be read from README.rst'
raise RuntimeError(f'{message}: {read_error}') from read_error


def is_canonical_version(version):
Expand All @@ -53,7 +98,7 @@ def is_canonical_version(version):
def find_meta(meta):
"""Extract __*meta*__ from META_CONTENTS."""
meta_match = re.search(
r"^__{meta}__\s+=\s+['\"]([^'\"]*)['\"]".format(meta=meta),
fr"^__{meta}__\s+=\s+['\"]([^'\"]*)['\"]",
META_CONTENTS,
re.M
)
Expand All @@ -72,8 +117,8 @@ def get_version_string():
# Check validity
if not is_canonical_version(version_string):
message = (
'The detected version string "{}" is not in canonical '
'format as defined in PEP 440.'.format(version_string))
f'The detected version string "{version_string}" is not in '
'canonical format as defined in PEP 440.')
raise ValueError(message)

return version_string
Expand Down Expand Up @@ -159,10 +204,10 @@ def get_version_string():

# Project's URLs
PROJECT_URLS = {
'Documentation': 'https://github.com/sergeyklay/provider-pact-example',
'Changelog': 'https://github.com/sergeyklay/provider-pact-example/blob/main/CHANGELOG.rst', # noqa: E501
'Bug Tracker': 'https://github.com/sergeyklay/provider-pact-example/issues', # noqa: E501
'Source Code': 'https://github.com/sergeyklay/provider-pact-example',
'Documentation': find_meta('url'),
'Changelog': f"{find_meta('url')}/blob/main/CHANGELOG.rst",
'Bug Tracker': f"{find_meta('url')}/issues",
'Source Code': find_meta('url'),
}

if __name__ == '__main__':
Expand Down
2 changes: 1 addition & 1 deletion tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@
# For the full copyright and license information, please view
# the LICENSE file that was distributed with this source code.

"""Module for Provider API Example testing."""
"""The top-level module for application testing."""