西维蜀黍

【Python】pytest - 运行错误

  ...


【Python】单元测试框架 - pytest

一个实例

# content of test_sample.py
 
def func(x):
    return x+1
 
def test_func():
    assert func(3) == 5

再一个实例

当需要编写多个测试样例的时候,我们可以将其放到一个测试类当中,如:

# content of test_class.py

class TestClass:
    def test_one(self):
        x = "this"
        assert 'h' in x

    def test_two(self):
        x = "hello"
        assert hasattr(x, 'check')

我们可以通过执行测试文件的方法,执行上面的测试:

$ py.test -q test_class.py
.F                                                                                                                                                  [100%]
======================================================================== FAILURES =========================================================================
___________________________________________________________________ TestClass.test_two ____________________________________________________________________

self = <testAA.TestClass instance at 0x10dd68d40>

    def test_two(self):
        x = "hello"
>       assert hasattr(x, 'check')
E       AssertionError: assert False
E        +  where False = hasattr('hello', 'check')

testAA.py:8: AssertionError
1 failed, 1 passed in 0.05 seconds
  ...


【Django】Django ORM - 文档整理

DB Doc

Index for DB: https://docs.djangoproject.com/en/2.2/topics/db/

API Doc

QuerySet API reference:https://docs.djangoproject.com/en/1.11/ref/models/querysets/

Performance and optimization - https://docs.djangoproject.com/en/1.11/topics/performance/

  ...


【Django】Django ORM - 性能优化

你可以使用 python manage.py shell 来让 ORM 执行查询以玩耍:

$ python manage.py shell
>>> from core import models
>>> a = models.User.objects[0:5]
...

如果你使用 MySQL,还可以结合General Log来实时查看 MySQL的 SQL 执行日志以进行验证(Visit 【MySQL】日志记录 for more details)。

最重要的原则: Work at the appropriate level

意思就是说要在对应的 level (M V C) 做对应的事。e.g. 如果计算 court, 在最低的数据库 level 里是最快的(如果只需要知道此记录是否存在的话,用 exists() 会更快)。 但要 注意 : queryset 是 lazy 的,所以有时候在 higher level (例如模板)里控制 queryset 是否真的执行,说不定会更高效。

下面这段代码很好的解释了不同 level 的意思:

# QuerySet operation on the database
# fast, because that's what databases are good at
my_bicycles.count()

# counting Python objects
# slower, because it requires a database query anyway, and processing
# of the Python objects
len(my_bicycles)

# Django template filter
# slower still, because it will have to count them in Python anyway,
# and because of template language overheads
\{\{ my_bicycles|length \}\}
  ...


【Django】Django ORM - 使 DB Schema 生效

当通过 Model 声明完表结构后,Django 可以自动将 Model 声明转换成DB Schema,进而自动写入 DB 中。

在>=1.7 的 Django 中,可以使用以下方法来生成 DB schema:

$ python manage.py makemigrations
$ python manage.py migrate

The makemigrations command looks at all your available models and creates migrations for whichever tables don’t already exist. migrate runs the migrations and creates tables in your database, as well as optionally providing much richer schema control.

在 1.7 之前的版本,使用:

$ python manage.py syncdb
  ...