Ensure that a list field only accepts lists with valid elements.
(self)
| 442 | name = StringField(db_field="name\0") |
| 443 | |
| 444 | def test_list_validation(self): |
| 445 | """Ensure that a list field only accepts lists with valid elements.""" |
| 446 | access_level_choices = ( |
| 447 | ("a", "Administration"), |
| 448 | ("b", "Manager"), |
| 449 | ("c", "Staff"), |
| 450 | ) |
| 451 | |
| 452 | class User(Document): |
| 453 | pass |
| 454 | |
| 455 | class Comment(EmbeddedDocument): |
| 456 | content = StringField() |
| 457 | |
| 458 | class BlogPost(Document): |
| 459 | content = StringField() |
| 460 | comments = ListField(EmbeddedDocumentField(Comment)) |
| 461 | tags = ListField(StringField()) |
| 462 | authors = ListField(ReferenceField(User)) |
| 463 | authors_as_lazy = ListField(LazyReferenceField(User)) |
| 464 | generic = ListField(GenericReferenceField()) |
| 465 | generic_as_lazy = ListField(GenericLazyReferenceField()) |
| 466 | access_list = ListField(choices=access_level_choices, display_sep=", ") |
| 467 | |
| 468 | User.drop_collection() |
| 469 | BlogPost.drop_collection() |
| 470 | |
| 471 | post = BlogPost(content="Went for a walk today...") |
| 472 | post.validate() |
| 473 | |
| 474 | post.tags = "fun" |
| 475 | with pytest.raises(ValidationError): |
| 476 | post.validate() |
| 477 | post.tags = [1, 2] |
| 478 | with pytest.raises(ValidationError): |
| 479 | post.validate() |
| 480 | |
| 481 | post.tags = ["fun", "leisure"] |
| 482 | post.validate() |
| 483 | post.tags = ("fun", "leisure") |
| 484 | post.validate() |
| 485 | |
| 486 | post.access_list = "a,b" |
| 487 | with pytest.raises(ValidationError): |
| 488 | post.validate() |
| 489 | |
| 490 | post.access_list = ["c", "d"] |
| 491 | with pytest.raises(ValidationError): |
| 492 | post.validate() |
| 493 | |
| 494 | post.access_list = ["a", "b"] |
| 495 | post.validate() |
| 496 | |
| 497 | assert post.get_access_list_display() == "Administration, Manager" |
| 498 | |
| 499 | post.comments = ["a"] |
| 500 | with pytest.raises(ValidationError): |
| 501 | post.validate() |