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 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
|
import warnings
from datetime import datetime, timedelta, timezone
from random import randint
from typing import List
import pytest
from beanie.odm.utils.init import init_beanie
from tests.odm.models import (
ADocument,
BDocument,
Bicycle,
Bike,
BsonRegexDoc,
Bus,
Car,
Doc2NonRoot,
DocNonRoot,
DocumentForEncodingTest,
DocumentForEncodingTestDate,
DocumentMultiModelOne,
DocumentMultiModelTwo,
DocumentTestModel,
DocumentTestModelFailInspection,
DocumentTestModelIndexFlagsAnnotated,
DocumentTestModelWithComplexIndex,
DocumentTestModelWithCustomCollectionName,
DocumentTestModelWithIndexFlags,
DocumentTestModelWithIndexFlagsAliases,
DocumentTestModelWithLink,
DocumentTestModelWithModelConfigExtraAllow,
DocumentTestModelWithSimpleIndex,
DocumentTestModelWithSoftDelete,
DocumentToBeLinked,
DocumentToTestSync,
DocumentUnion,
DocumentWithActions,
DocumentWithActions2,
DocumentWithBackLink,
DocumentWithBackLinkForNesting,
DocumentWithBsonBinaryField,
DocumentWithBsonEncodersFiledsTypes,
DocumentWithComplexDictKey,
DocumentWithCustomFiledsTypes,
DocumentWithCustomIdInt,
DocumentWithCustomIdUUID,
DocumentWithCustomInit,
DocumentWithDecimalField,
DocumentWithDeprecatedHiddenField,
DocumentWithEnumKeysDict,
DocumentWithExtras,
DocumentWithHttpUrlField,
DocumentWithIndexedObjectId,
DocumentWithIndexMerging1,
DocumentWithIndexMerging2,
DocumentWithKeepNullsFalse,
DocumentWithLink,
DocumentWithLinkForNesting,
DocumentWithList,
DocumentWithListBackLink,
DocumentWithListLink,
DocumentWithListOfLinks,
DocumentWithOptionalBackLink,
DocumentWithOptionalListBackLink,
DocumentWithPydanticConfig,
DocumentWithRevisionTurnedOn,
DocumentWithRootModelAsAField,
DocumentWithStringField,
DocumentWithTextIndexAndLink,
DocumentWithTimeStampToTestConsistency,
DocumentWithTurnedOffStateManagement,
DocumentWithTurnedOnReplaceObjects,
DocumentWithTurnedOnSavePrevious,
DocumentWithTurnedOnStateManagement,
DocumentWithTurnedOnStateManagementWithCustomId,
DocumentWithValidationOnSave,
DocWithCallWrapper,
Door,
GeoObject,
House,
HouseWithRevision,
InheritedDocumentWithActions,
LinkDocumentForTextSeacrh,
Lock,
LockWithRevision,
LongSelfLink,
LoopedLinksA,
LoopedLinksB,
NativeRegexDoc,
Nested,
Option1,
Option2,
Owner,
PackageElemMatch,
Region,
Roof,
RootDocument,
Sample,
SampleLazyParsing,
SampleWithMutableObjects,
SelfLinked,
StateAndDecimalFieldModel,
SubDocument,
UsersAddresses,
Vehicle,
Window,
WindowWithRevision,
WindowWithValidationOnSave,
Yard,
YardWithRevision,
)
from tests.odm.views import ViewForTest, ViewForTestWithLink
TESTING_MODELS = [
DocumentWithExtras,
DocumentWithPydanticConfig,
DocumentTestModel,
DocumentTestModelWithSoftDelete,
DocumentTestModelWithLink,
DocumentTestModelWithCustomCollectionName,
DocumentTestModelWithModelConfigExtraAllow,
DocumentTestModelWithSimpleIndex,
DocumentTestModelWithIndexFlags,
DocumentTestModelWithIndexFlagsAliases,
DocumentTestModelIndexFlagsAnnotated,
DocumentTestModelWithComplexIndex,
DocumentTestModelFailInspection,
DocumentWithBsonEncodersFiledsTypes,
DocumentWithCustomFiledsTypes,
DocumentWithCustomIdUUID,
DocumentWithCustomIdInt,
Sample,
DocumentWithActions,
DocumentWithTurnedOnStateManagement,
DocumentWithTurnedOnReplaceObjects,
DocumentWithTurnedOnSavePrevious,
DocumentWithTurnedOffStateManagement,
DocumentWithValidationOnSave,
DocumentWithRevisionTurnedOn,
DocumentWithHttpUrlField,
House,
Window,
WindowWithValidationOnSave,
Door,
Roof,
Yard,
Lock,
InheritedDocumentWithActions,
DocumentForEncodingTest,
DocumentForEncodingTestDate,
DocumentWithStringField,
ViewForTest,
ViewForTestWithLink,
DocumentMultiModelOne,
DocumentMultiModelTwo,
DocumentUnion,
HouseWithRevision,
WindowWithRevision,
LockWithRevision,
YardWithRevision,
DocumentWithActions2,
Vehicle,
Bicycle,
Bike,
Car,
Bus,
Owner,
SampleWithMutableObjects,
DocNonRoot,
Doc2NonRoot,
SampleLazyParsing,
RootDocument,
ADocument,
BDocument,
StateAndDecimalFieldModel,
Region,
UsersAddresses,
SelfLinked,
LoopedLinksA,
LoopedLinksB,
DocumentWithTurnedOnStateManagementWithCustomId,
DocumentWithDecimalField,
DocumentWithKeepNullsFalse,
PackageElemMatch,
DocumentWithLink,
DocumentWithBackLink,
DocumentWithListLink,
DocumentWithListBackLink,
DocumentWithListOfLinks,
DocumentToBeLinked,
DocumentWithTimeStampToTestConsistency,
DocumentWithIndexMerging1,
DocumentWithIndexMerging2,
DocumentWithCustomInit,
DocumentWithTextIndexAndLink,
LinkDocumentForTextSeacrh,
DocumentWithList,
DocumentWithBsonBinaryField,
DocumentWithRootModelAsAField,
DocWithCallWrapper,
DocumentWithOptionalBackLink,
DocumentWithOptionalListBackLink,
DocumentWithComplexDictKey,
DocumentWithIndexedObjectId,
DocumentToTestSync,
DocumentWithLinkForNesting,
DocumentWithBackLinkForNesting,
DocumentWithEnumKeysDict,
LongSelfLink,
BsonRegexDoc,
NativeRegexDoc,
]
@pytest.fixture
def point():
return {
"longitude": 13.404954,
"latitude": 52.520008,
}
@pytest.fixture
async def preset_documents(point):
docs = []
for i in range(10):
timestamp = datetime.now(tz=timezone.utc) - timedelta(days=i)
integer_1: int = i // 3
integer_2: int = i // 2
float_num = integer_1 + 0.3
string: str = f"test_{integer_1}"
option_1 = Option1(s="TEST")
option_2 = Option2(f=3.14)
union = option_1 if i % 2 else option_2
optional = option_2 if not i % 3 else None
geo = GeoObject(
coordinates=[
point["longitude"] + i / 10,
point["latitude"] + i / 10,
]
)
nested = Nested(
integer=integer_2,
option_1=option_1,
union=union,
optional=optional,
)
const = "TEST"
sample = Sample(
timestamp=timestamp,
increment=i,
integer=integer_1,
float_num=float_num,
string=string,
nested=nested,
optional=optional,
union=union,
geo=geo,
const=const,
)
docs.append(sample)
await Sample.insert_many(documents=docs)
@pytest.fixture()
def sample_doc_not_saved(point):
nested = Nested(
integer=0,
option_1=Option1(s="TEST"),
union=Option1(s="TEST"),
optional=None,
)
geo = GeoObject(
coordinates=[
point["longitude"],
point["latitude"],
]
)
return Sample(
timestamp=datetime.now(tz=timezone.utc),
increment=0,
integer=0,
float_num=0,
string="TEST_NOT_SAVED",
nested=nested,
optional=None,
union=Option1(s="TEST"),
geo=geo,
)
@pytest.fixture
async def session(cli):
async with cli.start_session() as s:
yield s
@pytest.fixture
def recwarn_always(recwarn):
warnings.simplefilter("always")
# ResourceWarnings about unclosed sockets can occur nondeterministically
# (during GC) which throws off the tests
warnings.simplefilter("ignore", ResourceWarning)
return recwarn
@pytest.fixture()
async def deprecated_init_beanie(db, recwarn_always):
await init_beanie(
database=db,
document_models=[DocumentWithDeprecatedHiddenField],
)
assert len(recwarn_always) == 1
assert issubclass(recwarn_always[0].category, DeprecationWarning)
assert (
"DocumentWithDeprecatedHiddenField: 'hidden=True' is deprecated, please use 'exclude=True'"
in str(recwarn_always[0].message)
)
yield
for model in TESTING_MODELS:
await model.get_pymongo_collection().drop()
await model.get_pymongo_collection().drop_indexes()
@pytest.fixture(autouse=True)
async def init(db):
await init_beanie(
database=db,
document_models=TESTING_MODELS,
)
yield
for model in TESTING_MODELS:
await model.get_pymongo_collection().drop()
await model.get_pymongo_collection().drop_indexes()
@pytest.fixture
def document_not_inserted():
return DocumentTestModel(
test_int=42,
test_list=[SubDocument(test_str="foo"), SubDocument(test_str="bar")],
test_doc=SubDocument(test_str="foobar"),
test_str="kipasa",
)
@pytest.fixture
def documents_not_inserted():
def generate_documents(
number: int, test_str: str = None, random: bool = False
) -> List[DocumentTestModel]:
return [
DocumentTestModel(
test_int=randint(0, 1000000) if random else i,
test_list=[
SubDocument(test_str="foo"),
SubDocument(test_str="bar"),
],
test_doc=SubDocument(test_str="foobar"),
test_str="kipasa" if test_str is None else test_str,
)
for i in range(number)
]
return generate_documents
@pytest.fixture
def document_soft_delete_not_inserted():
return DocumentTestModelWithSoftDelete(
test_int=randint(0, 1000000),
test_str="kipasa",
)
@pytest.fixture
def documents_soft_delete_not_inserted():
docs = []
for i in range(3):
docs.append(
DocumentTestModelWithSoftDelete(
test_int=randint(0, 1000000),
test_str="kipasa",
)
)
return docs
@pytest.fixture
async def document(document_not_inserted) -> DocumentTestModel:
return await document_not_inserted.insert()
@pytest.fixture
def documents(documents_not_inserted):
async def generate_documents(
number: int, test_str: str = None, random: bool = False
):
result = await DocumentTestModel.insert_many(
documents_not_inserted(number, test_str, random)
)
return result.inserted_ids
return generate_documents
@pytest.fixture
def documents_with_links(documents):
async def generate_documents():
await documents(15)
results = await DocumentTestModel.all().to_list()
for document in results:
await DocumentTestModelWithLink(test_link=document).insert()
return generate_documents
|