Skip to content
Merged
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
8 changes: 2 additions & 6 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ You can install this package using pypi: ``pip install flask-mongoengine``
Tests
=====
To run the test suite, ensure you are running a local copy of Flask-MongoEngine
and run: ``python setup.py nosetests``.
and simply run: ``pytest``.

To run the test suite on every supported versions of Python, PyPy and MongoEngine you can use ``tox``.
Ensure tox and each supported Python, PyPy versions are installed in your environment:
Expand All @@ -38,11 +38,7 @@ Ensure tox and each supported Python, PyPy versions are installed in your enviro
# Run the test suites
$ tox

To run a single or selected test suits, use the nosetest convention. E.g.

.. code-block:: shell

$ python setup.py nosetests --tests tests/example_test.py:ExampleTestClass.example_test_method
To run a single or selected test suits, use pytest `-k` option.

Contributing
============
Expand Down
1 change: 0 additions & 1 deletion requirements-dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,3 @@ black
pre-commit
pytest
pytest-cov
nose
15 changes: 1 addition & 14 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -1,23 +1,10 @@
[nosetests]
rednose = 1
verbosity = 2
detailed-errors = 1
cover-erase = 1
cover-branches = 1
cover-package = flask_mongoengine
tests = tests

[tool:pytest]
addopts = --cov=flask_mongoengine --cov-config=setup.cfg
testpaths = tests
env_override_existing_values = 1
filterwarnings =
ignore::UserWarning
ignore::DeprecationWarning
ignore::PendingDeprecationWarning

[flake8]
ignore=E501,F403,F405,I201,W503,E203
max-line-length = 90
max-line-length=90
exclude=build,dist,docs,examples,venv,.tox,.eggs
max-complexity=17
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def get_version(version_tuple):
version_line = list(filter(lambda l: l.startswith("VERSION"), open(init)))[0]
version = get_version(eval(version_line.split("=")[-1]))

test_requirements = ["coverage", "nose", "pytest", "pytest-cov"]
test_requirements = ["coverage", "pytest", "pytest-cov"]

setup(
name="flask-mongoengine",
Expand Down
25 changes: 0 additions & 25 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -1,25 +0,0 @@
import unittest

import flask
import mongoengine


class FlaskMongoEngineTestCase(unittest.TestCase):
"""Parent class of all test cases"""

def setUp(self):
self.app = flask.Flask(__name__)
self.app.config["MONGODB_DB"] = "test_db"
self.app.config["TESTING"] = True
self.ctx = self.app.app_context()
self.ctx.push()
# Mongoengine keep a global state of the connections that must be
# reset before each test.
# Given it doesn't expose any method to get the list of registered
# connections, we have to do the cleaning by hand...
mongoengine.connection._connection_settings.clear()
mongoengine.connection._connections.clear()
mongoengine.connection._dbs.clear()

def tearDown(self):
self.ctx.pop()
52 changes: 52 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
from datetime import datetime

import mongoengine
import pytest
from flask import Flask

from flask_mongoengine import MongoEngine


@pytest.fixture()
def app():
app = Flask(__name__)
app.config["TESTING"] = True
app.config["WTF_CSRF_ENABLED"] = False

with app.app_context():
yield app

mongoengine.connection.disconnect_all()


@pytest.fixture()
def db(app):
app.config["MONGODB_HOST"] = "mongodb://localhost:27017/flask_mongoengine_test_db"
test_db = MongoEngine(app)
db_name = test_db.connection.get_database("flask_mongoengine_test_db").name

if not db_name.endswith("_test_db"):
raise RuntimeError(
f"DATABASE_URL must point to testing db, not to master db ({db_name})"
)

# Clear database before tests, for cases when some test failed before.
test_db.connection.drop_database(db_name)

yield test_db

# Clear database after tests, for graceful exit.
test_db.connection.drop_database(db_name)


@pytest.fixture()
def todo(db):
class Todo(db.Document):
title = mongoengine.StringField(max_length=60)
text = mongoengine.StringField()
done = mongoengine.BooleanField(default=False)
pub_date = mongoengine.DateTimeField(default=datetime.utcnow)
comments = mongoengine.ListField(mongoengine.StringField())
comment_count = mongoengine.IntField()

return Todo
19 changes: 19 additions & 0 deletions tests/test_base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"""Tests for base MongoEngine class."""
from flask_mongoengine import MongoEngine
import pytest


def test_mongoengine_class__should_raise_type_error__if_config_not_dict():
"""MongoEngine will handle None values, but will pass anything else as app."""
input_value = "Not dict type"
with pytest.raises(TypeError) as error:
MongoEngine(input_value)
assert str(error.value) == "Invalid Flask application instance"


@pytest.mark.parametrize("input_value", [None, "Not dict type"])
def test_init_app__should_raise_type_error__if_config_not_dict(input_value):
db = MongoEngine()
with pytest.raises(TypeError) as error:
db.init_app(input_value)
assert str(error.value) == "Invalid Flask application instance"
94 changes: 32 additions & 62 deletions tests/test_basic_app.py
Original file line number Diff line number Diff line change
@@ -1,75 +1,45 @@
import datetime

import flask
import pytest
from bson import ObjectId

from flask_mongoengine import MongoEngine
from tests import FlaskMongoEngineTestCase


class BasicAppTestCase(FlaskMongoEngineTestCase):
def setUp(self):
super(BasicAppTestCase, self).setUp()
db = MongoEngine()

class Todo(db.Document):
title = db.StringField(max_length=60)
text = db.StringField()
done = db.BooleanField(default=False)
pub_date = db.DateTimeField(default=datetime.datetime.now)

db.init_app(self.app)

Todo.drop_collection()
self.Todo = Todo

@self.app.route("/")
def index():
return "\n".join(x.title for x in self.Todo.objects)

@self.app.route("/add", methods=["POST"])
def add():
form = flask.request.form
todo = self.Todo(title=form["title"], text=form["text"])
todo.save()
return "added"
@pytest.fixture(autouse=True)
def setup_endpoints(app, todo):
Todo = todo

@self.app.route("/show/<id>/")
def show(id):
todo = self.Todo.objects.get_or_404(id=id)
return "\n".join([todo.title, todo.text])
@app.route("/")
def index():
return "\n".join(x.title for x in Todo.objects)

self.db = db
@app.route("/add", methods=["POST"])
def add():
form = flask.request.form
todo = Todo(title=form["title"], text=form["text"])
todo.save()
return "added"

def test_connection_default(self):
self.app.config["MONGODB_SETTINGS"] = {}
self.app.config["TESTING"] = True
@app.route("/show/<id>/")
def show(id):
todo = Todo.objects.get_or_404(id=id)
return "\n".join([todo.title, todo.text])

db = MongoEngine()
# Disconnect to drop connection from setup.
db.disconnect()
db.init_app(self.app)

def test_with_id(self):
c = self.app.test_client()
resp = c.get("/show/%s/" % ObjectId())
self.assertEqual(resp.status_code, 404)
def test_with_id(app, todo):
Todo = todo
client = app.test_client()
response = client.get("/show/%s/" % ObjectId())
assert response.status_code == 404

c.post("/add", data={"title": "First Item", "text": "The text"})
client.post("/add", data={"title": "First Item", "text": "The text"})

resp = c.get("/show/%s/" % self.Todo.objects.first_or_404().id)
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.data.decode("utf-8"), "First Item\nThe text")
response = client.get("/show/%s/" % Todo.objects.first_or_404().id)
assert response.status_code == 200
assert response.data.decode("utf-8") == "First Item\nThe text"

def test_basic_insert(self):
c = self.app.test_client()
c.post("/add", data={"title": "First Item", "text": "The text"})
c.post("/add", data={"title": "2nd Item", "text": "The text"})
rv = c.get("/")
self.assertEqual(rv.data.decode("utf-8"), "First Item\n2nd Item")

def test_request_context(self):
with self.app.test_request_context():
todo = self.Todo(title="Test", text="test")
todo.save()
self.assertEqual(self.Todo.objects.count(), 1)
def test_basic_insert(app):
client = app.test_client()
client.post("/add", data={"title": "First Item", "text": "The text"})
client.post("/add", data={"title": "2nd Item", "text": "The text"})
response = client.get("/")
assert response.data.decode("utf-8") == "First Item\n2nd Item"
Loading