Skip to content

Commit

Permalink
add more test
Browse files Browse the repository at this point in the history
  • Loading branch information
long2ice committed May 24, 2020
1 parent 3a76486 commit 354e861
Show file tree
Hide file tree
Showing 13 changed files with 277 additions and 138 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
checkfiles = aerich/ tests/
checkfiles = aerich/ tests/ conftest.py
black_opts = -l 100 -t py38
py_warn = PYTHONDEVMODE=1
MYSQL_HOST ?= "127.0.0.1"
Expand Down
4 changes: 4 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,10 @@ Init db
Success create app migrate location ./migrations/models
Success generate schema for app "models"
.. note::

If your Tortoise-ORM app is not default ``models``, you must specify ``--app`` like ``aerich --app other_models init-db``.

Update models and make migrate
------------------------------

Expand Down
3 changes: 2 additions & 1 deletion aerich/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

from aerich.migrate import Migrate
from aerich.utils import get_app_connection, get_app_connection_name, get_tortoise_config

from . import __version__
from .models import Aerich

Expand Down Expand Up @@ -158,7 +159,7 @@ def history(ctx):
)
@click.pass_context
async def init(
ctx: Context, tortoise_orm, location,
ctx: Context, tortoise_orm, location,
):
config_file = ctx.obj["config_file"]
name = ctx.obj["name"]
Expand Down
10 changes: 6 additions & 4 deletions aerich/migrate.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,10 +111,9 @@ async def migrate(cls, name) -> str:
apps = Tortoise.apps
diff_models = apps.get(cls.diff_app)
app_models = apps.get(cls.app)
app_models.pop(cls._aerich, None)

cls._diff_models(diff_models, app_models)
cls._diff_models(app_models, diff_models, False)
cls.diff_models(diff_models, app_models)
cls.diff_models(app_models, diff_models, False)

cls._merge_operators()

Expand Down Expand Up @@ -198,7 +197,7 @@ def write_old_models(cls, config: dict, app: str, location: str):
cls.cp_models(app, old_model_files, os.path.join(location, app, cls.get_old_model_file()))

@classmethod
def _diff_models(
def diff_models(
cls, old_models: Dict[str, Type[Model]], new_models: Dict[str, Type[Model]], upgrade=True
):
"""
Expand All @@ -208,6 +207,9 @@ def _diff_models(
:param upgrade:
:return:
"""
old_models.pop(cls._aerich, None)
new_models.pop(cls._aerich, None)

for new_model_str, new_model in new_models.items():
if new_model_str not in old_models.keys():
cls._add_operator(cls.add_model(new_model), upgrade)
Expand Down
62 changes: 56 additions & 6 deletions conftest.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,61 @@
import asyncio
import os

import pytest
from tortoise.contrib.test import finalizer, initializer
from tortoise import Tortoise, expand_db_url, generate_schema_for_client
from tortoise.backends.asyncpg.schema_generator import AsyncpgSchemaGenerator
from tortoise.backends.mysql.schema_generator import MySQLSchemaGenerator
from tortoise.backends.sqlite.schema_generator import SqliteSchemaGenerator

from aerich.ddl.mysql import MysqlDDL
from aerich.ddl.postgres import PostgresDDL
from aerich.ddl.sqlite import SqliteDDL
from aerich.migrate import Migrate

@pytest.fixture(scope="module", autouse=True)
def initialize_tests(request):
db_url = os.getenv("TEST_DB", "sqlite://:memory:")
initializer(["tests.models"], db_url=db_url)
request.addfinalizer(finalizer)
db_url = os.getenv("TEST_DB", "sqlite://:memory:")
tortoise_orm = {
"connections": {"default": expand_db_url(db_url, True)},
"apps": {
"models": {
"models": ["tests.models", "aerich.models"],
"default_connection": "default",
},
},
}


@pytest.fixture(scope="function", autouse=True)
def reset_migrate():
Migrate.upgrade_operators = []
Migrate.downgrade_operators = []
Migrate._upgrade_fk_m2m_index_operators = []
Migrate._downgrade_fk_m2m_index_operators = []
Migrate._upgrade_m2m = []
Migrate._downgrade_m2m = []


@pytest.fixture(scope="session")
def loop():
loop = asyncio.get_event_loop()
return loop


@pytest.fixture(scope="session", autouse=True)
def initialize_tests(loop, request):
tortoise_orm['connections']['diff_models'] = "sqlite://:memory:"
tortoise_orm['apps']['diff_models'] = {"models": ["tests.diff_models"], "default_connection": "diff_models"}

loop.run_until_complete(Tortoise.init(config=tortoise_orm, _create_db=True))
loop.run_until_complete(
generate_schema_for_client(Tortoise.get_connection("default"), safe=True)
)

client = Tortoise.get_connection("default")
if client.schema_generator is MySQLSchemaGenerator:
Migrate.ddl = MysqlDDL(client)
elif client.schema_generator is SqliteSchemaGenerator:
Migrate.ddl = SqliteDDL(client)
elif client.schema_generator is AsyncpgSchemaGenerator:
Migrate.ddl = PostgresDDL(client)

request.addfinalizer(lambda: loop.run_until_complete(Tortoise._drop_databases()))
53 changes: 28 additions & 25 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@ authors = ["long2ice <[email protected]>"]

[tool.poetry.dependencies]
python = "^3.8"
tortoise-orm = {git = "https://github.com/tortoise-orm/tortoise-orm.git", branch = "develop"}
tortoise-orm = "*"
asyncclick = "*"
pydantic = "*"

[tool.poetry.dev-dependencies]
taskipy = "*"
asynctest = "*"
flake8 = "*"
isort = "*"
black = "^19.10b0"
Expand All @@ -21,6 +20,7 @@ aiomysql = "*"
asyncpg = "*"
pytest-xdist = "*"
mypy = "*"
pytest-asyncio = "*"

[tool.taskipy.tasks]
export = "poetry export -f requirements.txt --without-hashes > requirements.txt"
Expand Down
8 changes: 4 additions & 4 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ appdirs==1.4.4
async-generator==1.10
asyncclick==7.0.9
asyncpg==0.20.1
asynctest==0.13.0
atomicwrites==1.4.0; sys_platform == "win32"
attrs==19.3.0
black==19.10b0
Expand All @@ -16,7 +15,7 @@ click==7.1.2
colorama==0.4.3; sys_platform == "win32"
cryptography==2.9.2
execnet==1.7.1
flake8==3.8.1
flake8==3.8.2
iso8601==0.1.12; sys_platform == "win32" or implementation_name != "cpython"
isort==4.3.21
mccabe==0.6.1
Expand All @@ -35,14 +34,15 @@ pymysql==0.9.2
pyparsing==2.4.7
pypika==0.37.6
pytest==5.4.2
pytest-asyncio==0.12.0
pytest-forked==1.1.3
pytest-xdist==1.32.0
regex==2020.5.14
six==1.14.0
six==1.15.0
sniffio==1.1.0
taskipy==1.2.1
toml==0.10.1
-e git+https://github.com/long2ice/tortoise-orm.git@1f67b7a0ca1384365d6ff89d9e245e733166d1a6#egg=tortoise-orm
tortoise-orm==0.16.12
typed-ast==1.4.1
typing-extensions==3.7.4.2
wcwidth==0.1.9
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ iso8601==0.1.12; sys_platform == "win32" or implementation_name != "cpython"
pydantic==1.5.1
pypika==0.37.6
sniffio==1.1.0
tortoise-orm==0.16.12
typing-extensions==3.7.4.2
6 changes: 0 additions & 6 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +0,0 @@
TORTOISE_ORM = {
"connections": {"default": "mysql://root:[email protected]:3306/test"},
"apps": {
"models": {"models": ["tests.models", "aerich.models"], "default_connection": "default"}
},
}
56 changes: 56 additions & 0 deletions tests/diff_models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import datetime
from enum import IntEnum

from tortoise import Model, fields


class ProductType(IntEnum):
article = 1
page = 2


class PermissionAction(IntEnum):
create = 1
delete = 2
update = 3
read = 4


class Status(IntEnum):
on = 1
off = 0


class User(Model):
username = fields.CharField(max_length=20,)
password = fields.CharField(max_length=200)
last_login = fields.DatetimeField(description="Last Login", default=datetime.datetime.now)
is_active = fields.BooleanField(default=True, description="Is Active")
is_superuser = fields.BooleanField(default=False, description="Is SuperUser")
avatar = fields.CharField(max_length=200, default="")
intro = fields.TextField(default="")


class Category(Model):
slug = fields.CharField(max_length=200)
user = fields.ForeignKeyField("diff_models.User", description="User")
created_at = fields.DatetimeField(auto_now_add=True)


class Product(Model):
categories = fields.ManyToManyField("diff_models.Category")
name = fields.CharField(max_length=50)
view_num = fields.IntField(description="View Num")
sort = fields.IntField()
is_reviewed = fields.BooleanField(description="Is Reviewed")
type = fields.IntEnumField(ProductType, description="Product Type")
image = fields.CharField(max_length=200)
body = fields.TextField()
created_at = fields.DatetimeField(auto_now_add=True)


class Config(Model):
label = fields.CharField(max_length=200)
key = fields.CharField(max_length=20)
value = fields.JSONField()
status: Status = fields.IntEnumField(Status, default=Status.on)
Loading

0 comments on commit 354e861

Please sign in to comment.