Skip to content

Commit

Permalink
Merge pull request #153 from facundobatista/refresh-testexec
Browse files Browse the repository at this point in the history
Run all the tests in a better way.
  • Loading branch information
facundobatista authored Jun 22, 2024
2 parents a8b88bd + d3b090a commit b1c35bb
Show file tree
Hide file tree
Showing 11 changed files with 84 additions and 26 deletions.
6 changes: 3 additions & 3 deletions .github/workflows/tests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ name: Tests

on:
push:
branches: [ main ]
branches: [ master ]
pull_request:
branches: [ main ]
branches: [ master ]

# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
Expand All @@ -14,7 +14,7 @@ jobs:
strategy:
matrix:
os: [ubuntu-20.04, ubuntu-22.04, ubuntu-24.04]
python-version: [3.9, "3.10", "3.11", "3.12"]
python-version: ["3.10", "3.11", "3.12"]

runs-on: ${{ matrix.os }}
steps:
Expand Down
15 changes: 11 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Some awesome details:
There is a Telegram bot!
------------------------

Try it [here](https://t.me/linkode_bot).
Try it [here](https://t.me/linkode_bot).

Note this bot has a project on its own, [check it!](https://gitlab.com/c0x6a/linkode-bot)

Expand Down Expand Up @@ -77,6 +77,13 @@ docker build -t kilink .
docker run -it -p 5000:5000 kilink
```

To run the tests: in the virtualenv, do:

```
python -m pytest
```


How to Translate
----------------

Expand Down Expand Up @@ -174,8 +181,8 @@ cd linkode_app
pip install -r requirements.txt
```

The WSGI configuration file is already in the project, ready to use; for develop

The WSGI configuration file is already in the project, ready to use; for develop
or debugging you can add to it:

```
Expand All @@ -189,7 +196,7 @@ application = EvalException(application)

Create a virtual host configuration file in /etc/apache2/sites-enabled/
with the name that you want, in this case "linkode"

`sudo vi /etc/apache2/sites-enabled/linkode`

And paste this:
Expand Down
6 changes: 4 additions & 2 deletions kilink/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class KilinkDataTooBigError(Exception):


def _get_unique_id():
"""Returns a unique ID everytime it's called."""
"""Return a unique ID everytime it's called."""
arr = []
base = len(ALPHABET)
num = uuid.uuid4().int
Expand Down Expand Up @@ -93,7 +93,7 @@ def __repr__(self):


def session_manager(orig_func):
"""Decorator to wrap function with the session."""
"""Wrap function with the session."""

def new_func(self, *a, **k):
"""Wrappend function to manage DB session."""
Expand All @@ -117,6 +117,7 @@ def __init__(self):

@property
def session(self):
"""Return the cached or just built session."""
if self._session is None:
db_engine = config[DB_ENGINE_INSTANCE_KEY]
Base.metadata.create_all(db_engine)
Expand Down Expand Up @@ -225,4 +226,5 @@ def build_tree(self, linkode_id):

return root_node, len(nodes)


kilinkbackend = KilinkBackend()
3 changes: 2 additions & 1 deletion kilink/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,15 @@ class Config(dict):
It starts empty, and then the config can be set at any time.
"""

def load_file(self, filename):
"""Set the configuration from a YAML file."""
with open(filename, "rt", encoding="utf8") as fh:
cfg = yaml.safe_load(fh)
self.update(cfg)

def load_config(self, environment=PROD_ENVIRONMENT_VALUE):

"""Load the config."""
if environment == PROD_ENVIRONMENT_VALUE:
self.load_file("/home/kilink/project/production/configs/production.yaml")
db_engine = self._prod_database_engine()
Expand Down
7 changes: 3 additions & 4 deletions kilink/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from flask import Flask, jsonify, render_template, request, make_response
from flask_cors import CORS
from flask_babel import Babel
from sqlalchemy import create_engine

from kilink import backend, loghelper
from kilink.config import config, LANGUAGES
Expand All @@ -29,15 +28,15 @@

@app.errorhandler(backend.KilinkNotFoundError)
def handle_not_found_error(error):
"""Return 404 on kilink not found"""
"""Return 404 on kilink not found."""
msg = str(error)
logger.debug(msg)
return jsonify({'message': msg}), 404


@app.errorhandler(backend.KilinkDataTooBigError)
def handle_content_data_too_big_error(error):
"""Return 413 on content data too big"""
"""Return 413 on content data too big."""
logger.debug(error.message)
return jsonify({'message': error.message}), 413

Expand Down Expand Up @@ -124,7 +123,7 @@ def api_update(linkode_id):
@app.route('/api/1/linkodes/<linkode_id>/<revno>', methods=['GET'])
@app.route('/api/1/linkodes/<linkode_id>', methods=['GET'])
def api_get(linkode_id, revno=None):
"""Get the kilink and revno content"""
"""Get the kilink and revno content."""
logger.debug("API get; linkode_id=%r revno=%r", linkode_id, revno)
if revno is not None:
# the linkode_id to get the info from is the second token
Expand Down
5 changes: 4 additions & 1 deletion requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
pytest
-r requirements.txt

flake8
pydocstyle
pytest
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ flask==2.0.2
flask-cors==3.0.10
flask-babel==2.0.0
sqlalchemy==1.4.26
pyyaml==6.0
pyyaml==6.0.1
werkzeug==2.0.3 # until we get flask updated
3 changes: 0 additions & 3 deletions test

This file was deleted.

6 changes: 1 addition & 5 deletions tests/test_api.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
# encoding: utf8

# Copyright 2011-2017 Facundo Batista, Nicolás César
# Copyright 2011-2024 Facundo Batista, Nicolás César
# All Rigths Reserved

"""API tests."""
Expand All @@ -10,8 +8,6 @@
from unittest import TestCase
from unittest.mock import patch

from sqlalchemy import create_engine

from kilink import main, backend
from kilink.config import config, UNITTESTING_ENVIRONMENT_VALUE

Expand Down
3 changes: 1 addition & 2 deletions tests/test_backend.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Copyright 2011-2021 Facundo Batista, Nicolás César
# Copyright 2011-2024 Facundo Batista, Nicolás César
# All Rigths Reserved

"""Backend tests."""
Expand All @@ -9,7 +9,6 @@

from unittest import TestCase

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from kilink.backend import (
Expand Down
54 changes: 54 additions & 0 deletions tests/test_infra.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Copyright 2024 Facundo Batista
# Licensed under the GPL v3 License
# For further info, check https://github.com/facundobatista/kilink

"""Infrastructure tests."""

import os

import pydocstyle
import pytest
from flake8.api.legacy import get_style_guide


def get_python_filepaths(roots):
"""Retrieve paths of Python files."""
python_paths = []
for root in roots:
for dirpath, dirnames, filenames in os.walk(root):
for filename in filenames:
if filename.endswith(".py"):
python_paths.append(os.path.join(dirpath, filename))
return python_paths


def test_pep8(capsys):
"""Verify all files are nicely styled."""
python_filepaths = get_python_filepaths(["kilink", "tests"])
style_guide = get_style_guide()
report = style_guide.check_files(python_filepaths)

# if flake8 didn't report anything, we're done
if report.total_errors == 0:
return

# grab on which files we have issues
out, _ = capsys.readouterr()
pytest.fail(f"Please fix {report.total_errors} issue(s):\n{''.join(out)}", pytrace=False)


def test_pep257():
"""Verify all files have nice docstrings."""
python_filepaths = get_python_filepaths(["kilink"])
to_ignore = {
"D105", # Missing docstring in magic method
"D107", # Missing docstring in __init__
}
to_include = pydocstyle.violations.conventions.pep257 - to_ignore
errors = list(pydocstyle.check(python_filepaths, select=to_include))

if errors:
report = ["Please fix files as suggested by pydocstyle ({:d} issues):".format(len(errors))]
report.extend(str(e) for e in errors)
msg = "\n".join(report)
pytest.fail(msg, pytrace=False)

0 comments on commit b1c35bb

Please sign in to comment.