-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtests.py
93 lines (69 loc) · 2.66 KB
/
tests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
"""The Test is require mongodb running on localhost:27017."""
import muffin
import pytest
from motor import motor_asyncio as aiomotor
@pytest.fixture
def aiolib():
return 'asyncio'
@pytest.fixture
def app():
return muffin.Application(debug=True)
async def test_mongo(app, client):
from muffin_mongo import Plugin as Mongo
mongo = Mongo(app, database='tests')
assert mongo.client
async with client.lifespan():
# Get a collection
assert isinstance(mongo.items, aiomotor.AsyncIOMotorCollection)
assert mongo.items.database.name == 'tests'
# Clear the collection
await mongo.items.drop()
# Insert a document
res = await mongo.items.insert_one({'key': 'value'})
assert res
assert res.inserted_id
# Insert many
await mongo.items.insert_many([{'key': str(n)} for n in range(10)])
# Get a count
total = await mongo.items.count_documents({})
assert total == 11
# Get a single document
res2 = await mongo.items.find_one({'key': 'value'})
assert res2
assert res2['_id'] == res.inserted_id
# Find all
docs = await mongo.items.find().to_list(100)
assert docs
assert len(docs) == 11
# Update the document
await mongo.items.replace_one({'_id': res2['_id']}, {'key': 'value2'})
res3 = await mongo.items.find_one({'_id': res2['_id']})
assert res3['key'] == 'value2'
async def test_readme(app, client):
from muffin_mongo import Plugin as Mongo
mongo = Mongo(app, database='tests')
@app.route('/items', methods=['GET'])
async def get_items(request):
"""Return a JSON with items from the database."""
documents = await mongo.items.find().sort('key').to_list(100)
return [dict(dd.items(), _id=str(dd['_id'])) for dd in documents]
@app.route('/items', methods=['POST'])
async def insert_item(request):
"""Store items from JSON into database. Return ids."""
data = await request.data() # parse formdata/json from the request
res = await mongo.items.insert_many(data)
return [str(key) for key in res.inserted_ids]
async with client.lifespan():
await mongo.items.drop()
res = await client.post('/items', json=[{'key': n} for n in range(10)])
assert res.status_code == 200
json = await res.json()
assert json
assert len(json) == 10
res = await client.get('/items')
assert res.status_code == 200
json = await res.json()
assert json
assert len(json) == 10
assert json[0]['_id']
assert json[0]['key'] == 0