Skip to content

Commit

Permalink
Merge pull request #164 from stphivos/deprecations
Browse files Browse the repository at this point in the history
Drop Python 2 code and avoid deprecated code
  • Loading branch information
stefan6419846 committed May 9, 2023
2 parents 0856f4f + 16950e2 commit d6feded
Show file tree
Hide file tree
Showing 13 changed files with 36 additions and 77 deletions.
5 changes: 1 addition & 4 deletions django_mock_queries/asserts.py
@@ -1,7 +1,4 @@
try:
from unittest.mock import patch, Mock
except ImportError:
from mock import patch, Mock
from unittest.mock import patch, Mock

from model_bakery import baker

Expand Down
11 changes: 4 additions & 7 deletions django_mock_queries/mocks.py
Expand Up @@ -9,10 +9,7 @@
from django.db.utils import ConnectionHandler, NotSupportedError
from functools import partial
from itertools import chain
try:
from unittest.mock import Mock, MagicMock, patch, PropertyMock
except ImportError:
from mock import Mock, MagicMock, patch, PropertyMock
from unittest.mock import Mock, MagicMock, patch, PropertyMock

from types import MethodType

Expand Down Expand Up @@ -107,7 +104,7 @@ def compiler(queryset, connection, using, **kwargs):
Model.refresh_from_db = Mock() # Make this into a noop.


class MockMap(object):
class MockMap:
def __init__(self, original):
""" Wrap a mock mapping around the original one-to-many relation. """
self.map = {}
Expand Down Expand Up @@ -254,7 +251,7 @@ def test_dataset(self):
return PatcherChain(patchers, pass_mocks=False)


class PatcherChain(object):
class PatcherChain:
""" Chain a list of mock patchers into one.
The resulting patcher can be used just like one from the mock module:
Expand Down Expand Up @@ -328,7 +325,7 @@ def stop(self):
patcher.stop()


class Mocker(object):
class Mocker:
"""
A decorator that patches multiple class methods with a magic mock instance that does nothing.
"""
Expand Down
12 changes: 4 additions & 8 deletions django_mock_queries/query.py
@@ -1,11 +1,7 @@
import datetime
import random
from collections import OrderedDict, namedtuple
from six import with_metaclass
try:
from unittest.mock import Mock, MagicMock, PropertyMock
except ImportError:
from mock import Mock, MagicMock, PropertyMock
from unittest.mock import Mock, MagicMock, PropertyMock

from .constants import *
from .exceptions import *
Expand All @@ -21,7 +17,7 @@ def __call__(cls, *initial_items, **kwargs):
return obj


class MockSet(with_metaclass(MockSetMeta, MagicMock)):
class MockSet(MagicMock, metaclass=MockSetMeta):
EVENT_ADDED = 'added'
EVENT_UPDATED = 'updated'
EVENT_SAVED = 'saved'
Expand Down Expand Up @@ -472,7 +468,7 @@ def create_model(*fields):
return MockModel(**{f: None for f in fields})


class MockOptions(object):
class MockOptions:
def __init__(self, *field_names):
self.load_fields(*field_names)
self.get_latest_by = None
Expand All @@ -494,7 +490,7 @@ def load_fields(self, *field_names):
self.__dict__[key].append(obj)


class MockField(object):
class MockField:
def __init__(self, field):
for key in ('name', 'attname'):
self.__dict__[key] = field
5 changes: 1 addition & 4 deletions django_mock_queries/utils.py
@@ -1,9 +1,6 @@
from datetime import datetime, date
from django.core.exceptions import FieldError
try:
from unittest.mock import Mock
except ImportError:
from mock import Mock
from unittest.mock import Mock

from .comparisons import *
from .constants import *
Expand Down
2 changes: 1 addition & 1 deletion examples/users/analytics/api.py
Expand Up @@ -3,7 +3,7 @@
from django.db.models import Count


class AnalyticsApi(object):
class AnalyticsApi:
def active_users(self):
return User.objects.filter(is_active=True).all()

Expand Down
4 changes: 1 addition & 3 deletions requirements/core.txt
@@ -1,5 +1,3 @@
mock; python_version < '3.3'
Django
djangorestframework
model-bakery~=1.1.0; python_version < '3'
model-bakery>=1.0.0,<1.4.0; python_version >= '3'
model-bakery>=1.0.0
2 changes: 0 additions & 2 deletions requirements/dev.txt
Expand Up @@ -9,5 +9,3 @@ virtualenv==14.0.6
pypandoc==1.4
setuptools==39.2.0
twine==1.11.0
more-itertools<6.0.0; python_version < '3'
configparser<5.0.0; python_version < '3'
8 changes: 1 addition & 7 deletions setup.py
Expand Up @@ -32,13 +32,7 @@ def parse_requirements(filename):
'Topic :: Software Development :: Testing :: Unit',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3 :: Only',
],
keywords='django orm mocking unit-testing tdd',
packages=['django_mock_queries'],
Expand Down
7 changes: 2 additions & 5 deletions tests/test_asserts.py
@@ -1,10 +1,7 @@
try:
from unittest.mock import patch
except ImportError:
from mock import patch
from unittest import TestCase, skipIf
from unittest.mock import patch

from model_bakery import baker
from unittest import TestCase, skipIf

import django
from django_mock_queries.asserts import assert_serializer, SerializerAssert
Expand Down
26 changes: 10 additions & 16 deletions tests/test_mocks.py
@@ -1,35 +1,29 @@
import sys
from unittest import TestCase
from unittest.mock import patch, MagicMock, PropertyMock

import django
from django.db import connection
from django.db.utils import NotSupportedError
from django.db.backends.base.creation import BaseDatabaseCreation
try:
from unittest.mock import patch, MagicMock, PropertyMock
except ImportError:
from mock import patch, MagicMock, PropertyMock

from unittest import TestCase

from django_mock_queries import mocks
from django_mock_queries.mocks import monkey_patch_test_db, mock_django_connection, \
MockOneToOneMap, MockOneToManyMap, PatcherChain, mocked_relations, ModelMocker, Mocker
from django_mock_queries.query import MockSet
from tests.mock_models import Car, Sedan, Manufacturer, CarVariation

BUILTINS = 'builtins' if sys.version_info[0] >= 3 else '__builtin__'


class TestMocks(TestCase):
def test_mock_sql_raises_error(self):
""" Get a clear error if you forget to mock a database query. """
with self.assertRaisesRegexp(
with self.assertRaisesRegex(
NotSupportedError,
"Mock database tried to execute SQL for Car model."):
Car.objects.count()

def test_exists_raises_error(self):
""" Get a clear error if you forget to mock a database query. """
with self.assertRaisesRegexp(
with self.assertRaisesRegex(
NotSupportedError,
"Mock database tried to execute SQL for Car model."):
Car.objects.exists()
Expand Down Expand Up @@ -111,7 +105,7 @@ class MockOneToManyTests(TestCase):
def test_not_mocked(self):
m = Manufacturer()

with self.assertRaisesRegexp(
with self.assertRaisesRegex(
NotSupportedError,
'Mock database tried to execute SQL for Car model'):
m.car_set.count()
Expand All @@ -123,7 +117,7 @@ def test_mock_is_removed(self):
m.car_set = MockSet(Car(speed=95))
self.assertEqual(1, m.car_set.count())

with self.assertRaisesRegexp(
with self.assertRaisesRegex(
NotSupportedError,
'Mock database tried to execute SQL for Car model'):
m.car_set.count()
Expand Down Expand Up @@ -189,8 +183,8 @@ def zero_sum(items):


class PatcherChainTest(TestCase):
patch_mock_max = patch(BUILTINS + '.max')
patch_zero_sum = patch(BUILTINS + '.sum', zero_sum)
patch_mock_max = patch('builtins.max')
patch_zero_sum = patch('builtins.sum', zero_sum)

@patch_zero_sum
def test_patch_dummy(self):
Expand Down Expand Up @@ -255,7 +249,7 @@ def test_start(self):
self.assertIs(zero_sum, mocked[1])


@PatcherChain([patch(BUILTINS + '.max'), patch(BUILTINS + '.sum', zero_sum)],
@PatcherChain([patch('builtins.max'), patch('builtins.sum', zero_sum)],
pass_mocks=False)
class PatcherChainOnClassTest(TestCase):
test_example_attribute = 42
Expand Down
9 changes: 2 additions & 7 deletions tests/test_query.py
@@ -1,12 +1,7 @@
import datetime
import warnings

try:
from unittest.mock import MagicMock
except ImportError:
from mock import MagicMock

from unittest import TestCase
from unittest.mock import MagicMock

from django.core.exceptions import FieldError
from django.core.paginator import Paginator
Expand Down Expand Up @@ -196,7 +191,7 @@ def test_query_filters_model_objects_by_bad_field(self):
item_2.sedan = item_2

self.mock_set.add(item_1, item_2, item_3)
with self.assertRaisesRegexp(
with self.assertRaisesRegex(
FieldError,
r"Cannot resolve keyword 'bad_field' into field\. "
r"Choices are 'id', 'make', 'make_id', 'model', 'passengers', 'sedan', 'speed', 'variations'\."):
Expand Down
6 changes: 1 addition & 5 deletions tests/test_utils.py
@@ -1,10 +1,6 @@
from datetime import date, datetime
try:
from unittest.mock import patch, MagicMock
except ImportError:
from mock import patch, MagicMock

from unittest import TestCase
from unittest.mock import patch, MagicMock

from django_mock_queries import utils, constants

Expand Down
16 changes: 8 additions & 8 deletions tox.ini
@@ -1,16 +1,17 @@
[tox]
# See https://docs.djangoproject.com/en/2.0/faq/install/#what-python-version-can-i-use-with-django
envlist =
py{27}-dj{19,110}-drf33
py{27,35,36,37}-dj{111}-drf{37,39}
py{35,36,37}-dj{20,21,22}-drf{37,39}
py{36,37}-dj{111}-drf{37,39}
py{36,37}-dj{20,21,22}-drf{37,39}
py{36,37}-dj{30}-drf{310}
requires = virtualenv >= 20.0

[pytest]
norecursedirs = examples
flake8-ignore = *.py F403 F405 E731
flake8-max-line-length = 120

[flake8]
ignore = *.py F403 F405 E731
max-line-length = 120

[testenv]
download = true
Expand All @@ -19,8 +20,6 @@ setenv =
VIRTUALENV_DOWNLOAD=1
deps =
-rrequirements/dev.txt
dj19: Django~=1.9.12
dj110: Django~=1.10.5
dj111: Django~=1.11.17
dj20: Django~=2.0.2
dj21: Django~=2.1.0
Expand All @@ -32,8 +31,9 @@ deps =
drf310: djangorestframework~=3.10.3

commands =
py.test django_mock_queries/ tests/ --cov-report term-missing --cov=django_mock_queries --flake8
pytest django_mock_queries/ tests/ --cov-report term-missing --cov=django_mock_queries
python -c "import subprocess; subprocess.check_call(['./manage.py', 'test', '--settings=users.settings_mocked'], cwd='examples/users')"
python -c "import subprocess; subprocess.check_call(['./manage.py', 'test'], cwd='examples/users')"
python -c "import subprocess; subprocess.check_call(['pytest', '--ds=users.settings_mocked'], cwd='examples/users')"
python -c "import subprocess; subprocess.check_call(['pytest'], cwd='examples/users')"
flake8 django_mock_queries/ tests/

0 comments on commit d6feded

Please sign in to comment.