我目前正在测试数据库的可访问性,但遇到了严重的问题。我在模拟数据库并插入一个具有注册日期的用户对象。该日期首先被写入变量,然后传递给数据,其结果应为完全相同的值。好吧,那不是...
data.py
class User(Document):
email = EmailField(required=True)
first_name = StringField(max_length=50)
last_name = StringField(required=True, max_length=50)
registration_date = DateTimeField(default=datetime.utcnow())
last_login = DateTimeField()
test_storage.py
import datetime
import pytest
from mongoengine.connection import (
connect,
get_connection,
)
from mongodb.data import User
from storage.users import get_users
FMT = "%Y-%m-%d %H:%M"
@pytest.fixture(scope='module')
def mock_db():
connect('mongoenginetest', host='mongomock://localhost')
@pytest.fixture(scope='module')
def mock_user(mock_db):
user = {
'email': 'wijgowol@kogun.gi',
'registration_date': datetime.datetime.utcnow(),
'last_name': 'Bowen',
'first_name': 'Charlie',
}
db_user = User (**user)
db_user.save()
return user, db_user
def test_storage_get_user(mock_user):
user, db_user = mock_user
users = get_users()
assert len(users) == 1
assert type(users[0]) == User
u = users[0]
assert u == db_user
assert u.email == user['email']
assert u.registration_date == user['registration_date']
assert u.last_name == user['last_name']
assert u.first_name == user['first_name']
运行测试时,我得到以下结果:
_____________________________________________________________________________________________________________________ test_storage_get_user _____________________________________________________________________________________________________________________
mock_user = ({'email': 'wijgowol@kogun.gi', 'first_name': 'Charlie', 'last_name': 'Bowen', 'registration_date': datetime.datetime(2018, 10, 4, 10, 49, 56, 814025)}, <User: User object>)
def test_storage_get_user(mock_user):
user, db_user = mock_user
users = get_users()
assert len(users) == 1
assert type(users[0]) == User
u = users[0]
assert u == db_user
assert u.email == user['email']
> assert u.registration_date == user['registration_date']
E assert datetime.datetime(2018, 10, 4, 10, 49, 56, 814000) == datetime.datetime(2018, 10, 4, 10, 49, 56, 814025)
E + where datetime.datetime(2018, 10, 4, 10, 49, 56, 814000) == <User: User object>.registration_date
app/test/test_impl.py:53: AssertionError
为什么时间在那里变化?
答案 0 :(得分:1)
如果您在data.py
中默认注册日期,那么为什么在创建用户字典时还要进行设置呢?也许这就是造成它的原因。另外,为什么不创建User
呢?
您拥有这个:
user = {
'email': 'wijgowol@kogun.gi',
'registration_date': datetime.datetime.utcnow(),
'last_name': 'Bowen',
'first_name': 'Charlie',
}
db_user = User (**user)
db_user.save()
我将改用它:
db_user = User(
email = 'wijgowol@kogun.gi',
last_name = 'Bowen',
first_name = 'Charlie'
).save()
编辑: 根据我的评论。
如果创建用户时总是设置注册日期,那为什么不只使用_id
的{{3}}呢?
Edit2:
根据API参考,您需要使用timestamp,常规DatetimeField
不能很好地处理微秒。
来自 DatetimeField
参考:
注意:微秒四舍五入到最接近的毫秒数。
UTC之前的微秒支持已被有效破坏。如果需要精确的微秒支持,请使用ComplexDateTimeField。