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

Tests #1

Open
wants to merge 25 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
name: Test

on: [push, pull_request]

jobs:
build:
name: Python ${{ matrix.python-version }}
runs-on: ubuntu-latest

# The maximum number of minutes to let a workflow run
# before GitHub automatically cancels it. Default: 360
timeout-minutes: 30

strategy:
# When set to true, GitHub cancels
# all in-progress jobs if any matrix job fails.
fail-fast: false

max-parallel: 5

matrix:
python-version:
- "3.8"
- "3.9"
- "3.10"
- "3.11"

steps:
- uses: actions/checkout@v2

- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}

- name: Get pip cache dir
id: pip-cache
run: echo "::set-output name=dir::$(pip cache dir)"

- name: Cache
uses: actions/cache@v2
with:
path: ${{ steps.pip-cache.outputs.dir }}
key: ${{ matrix.python-version }}-v1-${{ hashFiles('**/setup.py') }}-${{ hashFiles('**/tox.ini') }}
restore-keys: |
${{ matrix.python-version }}-v1-

- name: Install Python dependencies
run: |
python -m pip install --upgrade pip
python -m pip install --upgrade tox tox-gh-actions

- name: Tox tests
run: tox -v

- name: Upload coverage
uses: codecov/codecov-action@v1
with:
name: Python ${{ matrix.python-version }}
7 changes: 7 additions & 0 deletions CHANGELOG.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CHANGELOG
=========

1.0.0 (unreleased)
------------------

- Nothing changed yet.
4 changes: 4 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
include *.in
include *.txt
recursive-exclude news *
exclude news

4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,12 @@ You can create a view to expose it in JSON Schema like this:

```python
from .forms import MyForm
from django_remote_jsonschema_forms.forms import RemoteJSONSChemaForm
from django_remote_jsonschema_forms.forms import RemoteJSONSchemaForm
from django.http import JsonResponse

def json_schema_form_view(request):
form = MyForm()
remote_form = RemoteJSONSChemaForm(form)
remote_form = RemoteJSONSchemaForm(form)
return JsonResponse(remote_form.as_dict())

```
Expand Down
8 changes: 4 additions & 4 deletions django_remote_jsonschema_forms/fields.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# -*- coding: utf-8 -*-
import datetime

from collections import OrderedDict

from django.conf import settings

from django_remote_jsonschema_forms import logger, widgets
from django_remote_jsonschema_forms import logger


class RemoteField(object):
Expand Down Expand Up @@ -52,8 +52,8 @@ def as_dict(self):
if self.field.widget.attrs["cols"]:
update_fields["maxLength"] = 750
update_fields["widget"] = "textarea"
except:
pass
except Exception as e:
logger.warning(e)

field_dict.update(update_fields)

Expand Down
11 changes: 6 additions & 5 deletions django_remote_jsonschema_forms/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from django_remote_jsonschema_forms.utils import resolve_promise


class RemoteJSONSChemaForm(object):
class RemoteJSONSchemaForm(object):
def __init__(self, form, *args, **kwargs):
self.form = form

Expand Down Expand Up @@ -148,11 +148,13 @@ def as_dict(self):

try:
form_dict["title"] = self.form.title
except:
except Exception as e:
logger.info(e)
form_dict["title"] = ""
try:
form_dict["description"] = self.form.description
except:
except Exception as e:
logger.info(e)
form_dict["description"] = ""
form_dict["properties"] = OrderedDict()
form_dict["required"] = []
Expand All @@ -164,7 +166,6 @@ def as_dict(self):
form_dict["required"].append(field)

# Get properties' values
initial_data = {}
for name, field in [(x, self.form.fields[x]) for x in self.fields]:
# Retrieve the initial data from the form itself if it exists so
# that we properly handle which initial data should be returned in
Expand All @@ -183,7 +184,7 @@ def as_dict(self):
remote_field = remote_field_class(
field, form_initial_field_data, field_name=name
)
except Exception(e):
except Exception as e:
logger.warning(
"Error serializing field %s: %s", remote_field_class_name, str(e)
)
Expand Down
11 changes: 8 additions & 3 deletions django_remote_jsonschema_forms/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from django.utils.functional import Promise
from django.utils.encoding import force_str
from django.utils.functional import Promise

from django_remote_jsonschema_forms import logger


def resolve_promise(o):
Expand All @@ -11,10 +13,13 @@ def resolve_promise(o):
elif isinstance(o, Promise):
try:
o = force_str(o)
except:
except Exception as e:
logger.warning(e)

try:
o = [resolve_promise(x) for x in o]
except:
except Exception as ex:
logger.warning(ex)
raise Exception("Unable to resolve lazy object %s" % o)
elif callable(o):
o = o()
Expand Down
Empty file added news/.gitkeep
Empty file.
1 change: 1 addition & 0 deletions news/1.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Initial release [Gorka Garcia]
61 changes: 61 additions & 0 deletions runtests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
#! /usr/bin/env python3
import os
import sys

import pytest


def split_class_and_function(string):
class_string, function_string = string.split(".", 1)
return "%s and %s" % (class_string, function_string)


def is_function(string):
# `True` if it looks like a test function is included in the string.
return string.startswith("test_") or ".test_" in string


def is_class(string):
# `True` if first character is uppercase - assume it's a class name.
return string[0] == string[0].upper()


if __name__ == "__main__":
if len(sys.argv) > 1:
pytest_args = sys.argv[1:]
first_arg = pytest_args[0]

try:
pytest_args.remove("--coverage")
except ValueError:
pass
else:
pytest_args = [
"--cov",
".",
"--cov-report",
"xml",
] + pytest_args

try:
pytest_args.remove("--no-pkgroot")
except ValueError:
pass
else:
sys.path.pop(0)

if first_arg.startswith("-"):
# `runtests.py [flags]`
pytest_args = ["tests"] + pytest_args
elif is_class(first_arg) and is_function(first_arg):
# `runtests.py TestCase.test_function [flags]`
expression = split_class_and_function(first_arg)
pytest_args = ["tests", "-k", expression] + pytest_args[1:]
elif is_class(first_arg) or is_function(first_arg):
# `runtests.py TestCase [flags]`
# `runtests.py test_function [flags]`
pytest_args = ["tests", "-k", pytest_args[0]] + pytest_args[1:]
else:
pytest_args = []

sys.exit(pytest.main(pytest_args))
7 changes: 7 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[flake8]
# E501: line too long
ignore = E501,W503
exclude = .venv,.git,.tox,.direnv

[isort]
profile = black
9 changes: 8 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,15 @@
author_email="[email protected]",
url="http://github.com/codesyntax/django_remote_jsonschema_forms/",
long_description=open("README.md", "r").read(),
long_description_content_type="text/markdown",
packages=[
"django_remote_jsonschema_forms",
],
package_data={},
zip_safe=False,
requires=[],
install_requires=[],
install_requires=["django>=4.2"],
python_requires=">=3.8",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
Expand All @@ -31,6 +33,11 @@
"License :: MIT",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Topic :: Utilities",
],
)
Empty file added tests/__init__.py
Empty file.
14 changes: 14 additions & 0 deletions tests/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# -*- coding: utf-8 -*-
from django import forms
from django.db import models


class Task(models.Model):
text = models.TextField("Text")
email = models.TextField("Text")


class MyForm(forms.ModelForm):

class Meta:
model = Task
17 changes: 17 additions & 0 deletions tests/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# -*- coding: utf-8 -*-


from django.test import TestCase

from django_remote_jsonschema_forms import RemoteJSONSchemaForm

from .models import MyForm


class FormTest(TestCase):

def test_form_returns_dict(self):
form = MyForm()
remote_form = RemoteJSONSchemaForm(form)

self.assertTrue(isinstance(remote_form, dict))
30 changes: 30 additions & 0 deletions tox.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
[tox]
minversion = 1.9
envlist =
py{38,39,310,311}-dj{41,42}
py{310,311}-djmain

[gh-actions]
python =
3.8: py38
3.9: py39
3.10: py310
3.11: py311

[testenv]
deps =
dj41: Django>=4.1,<4.2
dj42: Django>=4.2,<5.0
djmain: https://github.com/django/django/archive/main.tar.gz
coverage
setenv =
PYTHONWARNINGS=all
commands =
coverage run -m django test {posargs}
coverage report
coverage xml
ignore_outcome =
djmain: True
ignore_errors =
djmain: True

Loading