def test_connectionField_keysOnly(self): a1 = Article(headline="Test1", summary="1").put() a2 = Article(headline="Test2", summary="2").put() a3 = Article(headline="Test3", summary="3").put() Comment(parent=a1, body="c1").put() Comment(parent=a2, body="c2").put() Comment(parent=a3, body="c3").put() result = schema.execute(""" query Articles { articles(keysOnly: true) { edges { cursor, node { id } } } } """) self.assertEmpty(result.errors) articles = result.data.get('articles', {}).get('edges') self.assertLength(articles, 3)
def testQuery_keyProperty(self): author_key = Author(name="john dow", email="*****@*****.**").put() article_key = Article(headline="h1", summary="s1", author_key=author_key).put() result = schema.execute(''' query ArticleWithAuthorID { articles { ndbId headline authorId authorNdbId: authorId(ndb: true) author { name, email } } } ''') self.assertEmpty(result.errors) article = dict(result.data['articles'][0]) self.assertEqual(article['ndbId'], str(article_key.id())) self.assertEqual(article['authorNdbId'], str(author_key.id())) author = dict(article['author']) self.assertDictEqual(author, { 'name': u'john dow', 'email': u'*****@*****.**' }) self.assertEqual('h1', article['headline']) self.assertEqual(to_global_id('AuthorType', author_key.urlsafe()), article['authorId'])
def testQuery_keyProperty(self): author_key = Author(name="john dow", email="*****@*****.**").put() article_key = Article(headline="h1", summary="s1", author_key=author_key).put() result = schema.execute(''' query ArticleWithAuthorID { articles { ndbId headline authorId authorNdbId: authorId(ndb: true) author { name, email } } } ''') self.assertEmpty(result.errors) article = dict(result.data['articles'][0]) self.assertEqual(article['ndbId'], str(article_key.id())) self.assertEqual(article['authorNdbId'], str(author_key.id())) author = dict(article['author']) self.assertDictEqual(author, {'name': u'john dow', 'email': u'*****@*****.**'}) self.assertEqual('h1', article['headline']) self.assertEqual(to_global_id('AuthorType', author_key.urlsafe()), article['authorId'])
def setUp(self): self.article = Article(title="Test Title") self.author_1 = Author.objects.create(name="Author 1") self.author_2 = Author.objects.create(name="Author 2") self.article.authors = [self.author_1, self.author_2] self.category_1 = Category.objects.create(name="Category 1") self.category_2 = Category.objects.create(name="Category 2") self.article.categories = [self.category_1, self.category_2]
def testNdbNode_getNode_validID_entityDoes_shouldReturnEntity(self): article_key = Article( headline="TestGetNode", summary="1", author_key=Author(name="John Dow", email="*****@*****.**").put(), ).put() result = ArticleType.get_node(article_key.urlsafe()) self.assertIsNotNone(result) self.assertEqual(result.instance, article_key.get())
def setUp(self): # Create 10 articles with 10 authors each. authors = Author.objects.bulk_create( Author(id=i, name=str(i)) for i in range(10)) authors = Author.objects.all() for i in range(10): article = Article(title=str(i)) article.authors = authors article.save()
def test_prefetch_from_fake_queryset(self): article = Article(title='Article with related articles') article.related_articles = list(Article.objects.all()) with self.assertNumQueries(10): names = self.get_author_names(article.related_articles.all()) with self.assertNumQueries(1): prefetched_names = self.get_author_names( article.related_articles.prefetch_related('authors')) self.assertEqual(names, prefetched_names)
def test_serialize_m2m(self): george_orwell = Author.objects.create(name='George Orwell') charles_dickens = Author.objects.create(name='Charles Dickens') article = Article( title='Down and Out in Paris and London', authors=[george_orwell, charles_dickens], ) article_serialised = article.serializable_data() self.assertEqual(article_serialised['title'], 'Down and Out in Paris and London') self.assertIn(george_orwell.pk, article_serialised['authors']) self.assertEqual(article_serialised['categories'], [])
def testNdbNode_getNode_validID_entityDoes_shouldReturnEntity(self): article_key = Article( headline="TestGetNode", summary="1", author_key=Author(name="John Dow", email="*****@*****.**").put(), ).put() result = ArticleType.get_node(None, article_key.urlsafe()) article = article_key.get() self.assertIsNotNone(result) self.assertEqual(result.headline, article.headline) self.assertEqual(result.summary, article.summary)
def testQuery_repeatedKeyProperty(self): tk1 = Tag(name="t1").put() tk2 = Tag(name="t2").put() tk3 = Tag(name="t3").put() tk4 = Tag(name="t4").put() Article(headline="h1", summary="s1", tags=[tk1, tk2, tk3, tk4]).put() result = schema.execute(''' query ArticleWithAuthorID { articles { headline authorId tagIds tags { name } } } ''') self.assertEmpty(result.errors) article = dict(result.data['articles'][0]) self.assertListEqual( map(lambda k: to_global_id('TagType', k.urlsafe()), [tk1, tk2, tk3, tk4]), article['tagIds']) self.assertLength(article['tags'], 4) for i in range(0, 3): self.assertEqual(article['tags'][i]['name'], 't%s' % (i + 1))
def test_ordering(self): # our fake querysets should respect the ordering defined on the target model bela_bartok = Author.objects.create(name='Bela Bartok') graham_greene = Author.objects.create(name='Graham Greene') janis_joplin = Author.objects.create(name='Janis Joplin') simon_sharma = Author.objects.create(name='Simon Sharma') william_wordsworth = Author.objects.create(name='William Wordsworth') article3 = Article(title="Test article 3") article3.authors = [ janis_joplin, william_wordsworth, bela_bartok, simon_sharma, graham_greene ] self.assertEqual( list(article3.authors.all()), [bela_bartok, graham_greene, janis_joplin, simon_sharma, william_wordsworth] )
def test_connectionField_empty(self): Article(headline="Test1", summary="1").put() result = schema.execute(""" query Articles { articles { edges { cursor, node { headline, createdAt, comments { edges { node { body } } } } } } } """) articles = result.data.get('articles', {}).get('edges') self.assertLength(articles, 1) article = articles[0]['node'] self.assertLength(article.keys(), 3) self.assertIsNotNone(article.get('headline')) self.assertIsNotNone(article.get('createdAt')) comments = article['comments']['edges'] self.assertEmpty(comments)
def testQuery_structuredProperty(self): mobile = PhoneNumber(area="650", number="12345678") author_key = Author(name="John Dow", email="*****@*****.**", mobile=mobile).put() Article(headline="Test1", author_key=author_key).put() result = schema.execute(""" query Articles { articles { headline, authorId author { name email mobile { area, number } } } } """) self.assertEmpty(result.errors, msg=str(result.errors)) article = result.data['articles'][0] self.assertEqual(article["headline"], "Test1") author = article['author'] self.assertEqual(author["name"], "John Dow") self.assertEqual(author["email"], "*****@*****.**") self.assertDictEqual(dict(area="650", number="12345678"), dict(author["mobile"]))
def test_deserialize(self): beatles = Band.from_serializable_data({ 'pk': 9, 'albums': [], 'name': 'The Beatles', 'members': [ {'pk': None, 'name': 'John Lennon', 'band': None}, {'pk': None, 'name': 'Paul McCartney', 'band': None}, ] }) self.assertEqual(9, beatles.id) self.assertEqual('The Beatles', beatles.name) self.assertEqual(2, beatles.members.count()) self.assertEqual(BandMember, beatles.members.all()[0].__class__) authors = {} categories = {} for ii in range(1, 6): authors[ii] = Author.objects.create(name="Author " + str(ii)) categories[ii] = Category.objects.create(name="Category " + str(ii)) article = Article.from_serializable_data({ 'pk': 1, 'title': 'Article Title 1', 'authors': [authors[1].pk, authors[2].pk], 'categories': [categories[2].pk, categories[3].pk, categories[4].pk] }) self.assertEqual(article.id, 1) self.assertEqual(article.title, 'Article Title 1') self.assertEqual(article.authors.count(), 2) self.assertEqual([author.name for author in article.authors.all()], ['Author 1', 'Author 2']) self.assertEqual(article.categories.count(), 3)
def testQuery_excludedField(self): Article(headline="h1", summary="s1").put() class ArticleType(NdbObjectType): class Meta: model = Article exclude_fields = ['summary'] class QueryType(graphene.ObjectType): articles = graphene.List(ArticleType) @graphene.resolve_only_args def resolve_articles(self): return Article.query() schema = graphene.Schema(query=QueryType) query = ''' query ArticlesQuery { articles { headline, summary } } ''' result = schema.execute(query) self.assertIsNotNone(result.errors) self.assertTrue( 'Cannot query field "summary"' in result.errors[0].message)
def test_connectionField(self): a1 = Article(headline="Test1", summary="1").put() a2 = Article(headline="Test2", summary="2").put() a3 = Article(headline="Test3", summary="3").put() Comment(parent=a1, body="c1").put() Comment(parent=a2, body="c2").put() Comment(parent=a3, body="c3").put() result = schema.execute(""" query Articles { articles(first:2) { edges { cursor, node { headline, summary, comments { edges { cursor, node { body } } } } } } } """) self.assertEmpty(result.errors) articles = result.data.get('articles', {}).get('edges') self.assertLength(articles, 2) for articleNode in articles: article = articleNode['node'] self.assertLength(article.keys(), 3) self.assertIsNotNone(article.get('headline')) self.assertIsNotNone(article.get('summary')) comments = article['comments']['edges'] self.assertLength(comments, 1) self.assertEqual(comments[0]['node']['body'], "c" + article['summary'])
def test_reverse_m2m_field(self): # article is unsaved, so should not be returned by the reverse relation on author self.assertEqual(self.author_1.articles_by_author.count(), 0) self.article.save() # should now be able to look up on the reverse relation self.assertEqual(self.author_1.articles_by_author.count(), 1) self.assertEqual(self.author_1.articles_by_author.get(), self.article) article_2 = Article(title="Test Title 2") article_2.authors = [self.author_1] article_2.save() self.assertEqual(self.author_1.articles_by_author.all().count(), 2) self.assertEqual( list(self.author_1.articles_by_author.order_by('title').values_list('title', flat=True)), ['Test Title', 'Test Title 2'] )
def test_reverse_m2m_field(self): # article is unsaved, so should not be returned by the reverse relation on author self.assertEqual(self.author_1.articles_by_author.count(), 0) self.article.save() # should now be able to look up on the reverse relation self.assertEqual(self.author_1.articles_by_author.count(), 1) self.assertEqual(self.author_1.articles_by_author.get(), self.article) article_2 = Article(title="Test Title 2") article_2.authors = [self.author_1] article_2.save() self.assertEqual(self.author_1.articles_by_author.all().count(), 2) self.assertEqual( list( self.author_1.articles_by_author.order_by('title').values_list( 'title', flat=True)), ['Test Title', 'Test Title 2'])
def test_uninitialised_m2m_relation(self): # Reading an m2m relation of a newly created object should return an empty queryset new_article = Article(title="Test title") self.assertEqual([], list(new_article.authors.all())) self.assertEqual(new_article.authors.count(), 0) # the manager should have a 'model' property pointing to the target model self.assertEqual(Author, new_article.authors.model)
def testQuery_list(self): Article(headline="Test1", summary="1").put() Article(headline="Test2", summary="2").put() Article(headline="Test3", summary="3").put() result = schema.execute(""" query Articles { articles { headline } } """) self.assertEmpty(result.errors) self.assertLength(result.data['articles'], 3) for article in result.data['articles']: self.assertLength(article.keys(), 1) self.assertEqual(article.keys()[0], 'headline')
def test_constructor(self): # Test passing values for M2M relations as kwargs to the constructor article2 = Article( title="Test article 2", authors=[self.author_1], categories=[self.category_2], ) self.assertEqual( ['Author 1'], [author.name for author in article2.authors.order_by('name')]) self.assertEqual(article2.authors.count(), 1)
def testQuery_repeatedProperty(self): keywords = ["a", "b", "c"] a = Article(headline="Test1", keywords=keywords).put() result = schema.execute(""" query Articles { articles { headline, keywords, createdAt } } """) self.assertEmpty(result.errors) self.assertLength(result.data['articles'], 1) article = result.data['articles'][0] self.assertEqual(article["createdAt"], str(a.get().created_at.isoformat())) self.assertEqual(article["headline"], "Test1") self.assertListEqual(article["keywords"], keywords)
def test_connectionFieldWithTransformEdges_continualEdgeGeneration(self): dead1_reader_key = Reader(name="John Doe 1", email="*****@*****.**", is_alive=False).put() dead2_reader_key = Reader(name="John Doe 2", email="*****@*****.**", is_alive=False).put() alive_reader_key = Reader(name="Chuck Norris", email="*****@*****.**").put() article_key = Article(headline="Test1", summary="1").put() ArticleReader(reader_key=dead1_reader_key, article_key=article_key).put() ArticleReader(reader_key=dead2_reader_key, article_key=article_key).put() ArticleReader(reader_key=alive_reader_key, article_key=article_key).put() result = schema.execute(""" query Articles { articles { edges { node { readers(first:1) { edges { cursor node { ndbId name email isAlive } } } } } } } """) articles = result.data.get('articles', {}).get('edges') self.assertLength(articles, 1) article = articles[0]['node'] readers = article.get('readers', {}).get('edges') self.assertLength(readers, 1) reader = readers[0]['node'] self.assertLength(reader.keys(), 4) self.assertEquals(reader['ndbId'], str(alive_reader_key.id()))
def test_reverse_m2m_field(self): article = Article(title="Test Title") author_1 = Author(name="Author 1") author_2 = Author(name="Author 2") article.authors = [author_1, author_2] category_1 = Category(name="Category 1") category_2 = Category(name="Category 2") article.categories = [category_1, category_2] article.save() author_1 = Author.objects.get(name="Author 1") self.assertEqual(author_1.articles_by_author.all().count(), 1) self.assertEqual(author_1.articles_by_author.get(), Article.objects.filter(title="Test Title").get()) article_2 = Article(title="Test Title 2") article_2.authors = [author_1] article_2.save() author_1 = Author.objects.get(name="Author 1") self.assertEqual(author_1.articles_by_author.all().count(), 2) self.assertEqual(list(author_1.articles_by_author.values_list('title', flat=True)), ['Test Title', 'Test Title 2'])
def test_connectionFieldWithTransformEdges(self): alive_reader_key = Reader(name="Chuck Norris", email="*****@*****.**").put() dead_reader_key = Reader(name="John Doe", email="*****@*****.**", is_alive=False).put() article_key = Article(headline="Test1", summary="1").put() ArticleReader(reader_key=alive_reader_key, article_key=article_key).put() ArticleReader(reader_key=dead_reader_key, article_key=article_key).put() result = schema.execute(""" query Articles { articles { edges { node { readers { edges { cursor node { name email } } } } } } } """) articles = result.data.get('articles', {}).get('edges') self.assertLength(articles, 1) article = articles[0]['node'] readers = article.get('readers', {}).get('edges') self.assertLength(readers, 1) reader = readers[0]['node'] self.assertLength(reader.keys(), 2) self.assertIsNotNone(reader.get('name')) self.assertIsNotNone(reader.get('email'))
def populate_db(): from tests.models import Article if Article.objects.all().count() > 0: print('Some records found; skipping') return Article.objects.all().delete() date = timezone.now() # change to range(5) to create 5M records for n in range(1): articles = [] for i in range(1_000_000): seconds = datetime.timedelta(microseconds=i + 1_000_000 * n) articles.append( Article(title="%s" % (i + 1_000_000 * n), date=date, date_unique=date + seconds)) Article.objects.bulk_create(articles)
def test_keyProperty(self): Article( headline="Test1", summary="1", author_key=Author(name="John Dow", email="*****@*****.**").put(), tags=[ Tag(name="tag1").put(), Tag(name="tag2").put(), Tag(name="tag3").put(), ] ).put() result = schema.execute(""" query Articles { articles(first:2) { edges { cursor, node { headline, summary, author { name }, tags { name } } } } } """) self.assertEmpty(result.errors, msg=str(result.errors)) articles = result.data.get('articles', {}).get('edges', []) self.assertLength(articles, 1) article = articles[0]['node'] self.assertEqual(article['headline'], 'Test1') self.assertEqual(article['summary'], '1') author = article['author'] self.assertLength(author.keys(), 1) self.assertEqual(author['name'], 'John Dow') tags = article['tags'] tag_names = [t['name'] for t in tags] self.assertListEqual(tag_names, ['tag1', 'tag2', 'tag3'])
def testQuery_structuredProperty_repeated(self): address1 = Address(address1="address1", address2="apt 1", city="Mountain View") address2 = Address(address1="address2", address2="apt 2", city="Mountain View") author_key = Author(name="John Dow", email="*****@*****.**", addresses=[address1, address2]).put() Article(headline="Test1", author_key=author_key).put() result = schema.execute(""" query Articles { articles { headline, author { name email addresses { address1 address2 city } } } } """) self.assertEmpty(result.errors) article = result.data['articles'][0] self.assertEqual(article["headline"], "Test1") author = article['author'] self.assertEqual(author["name"], "John Dow") self.assertEqual(author["email"], "*****@*****.**") self.assertLength(author["addresses"], 2) addresses = [dict(d) for d in author["addresses"]] self.assertIn(address1.to_dict(), addresses) self.assertIn(address2.to_dict(), addresses)
def test_deserialize_m2m(self): authors = {} categories = {} for i in range(1, 6): authors[i] = Author.objects.create(name="Author %d" % i) categories[i] = Category.objects.create(name="Category %d" % i) article = Article.from_serializable_data({ 'pk': 1, 'title': 'Article Title 1', 'authors': [authors[1].pk, authors[2].pk], 'categories': [categories[2].pk, categories[3].pk, categories[4].pk] }) self.assertEqual(article.id, 1) self.assertEqual(article.title, 'Article Title 1') self.assertEqual(article.authors.count(), 2) self.assertEqual( [author.name for author in article.authors.order_by('name')], ['Author 1', 'Author 2'] ) self.assertEqual(article.categories.count(), 3)
def test_parentalm2mfield(self): article = Article(title="Test Title") author_1 = Author(name="Author 1") author_2 = Author(name="Author 2") article.authors = [author_1, author_2] category_1 = Category(name="Category 1") category_2 = Category(name="Category 2") article.categories = [category_1, category_2] self.assertEqual( ['Author 1', 'Author 2'], [author.name for author in article.authors.all().order_by('name')] ) self.assertEqual(article.authors.count(), 2) author_3 = Author(name="Author 3") article.authors.add(author_3) self.assertEqual( ['Author 1', 'Author 2', 'Author 3'], [author.name for author in article.authors.all().order_by('name')] ) self.assertEqual(article.authors.count(), 3) article.authors.remove(author_3) self.assertEqual( ['Author 1', 'Author 2'], [author.name for author in article.authors.all().order_by('name')] ) self.assertEqual(article.authors.count(), 2) article.authors.clear() self.assertEqual( [], [author.name for author in article.authors.all().order_by('name')] ) self.assertEqual(article.authors.count(), 0) article.authors = [author_1, author_2] article.save() article = Article.objects.get(title="Test Title") self.assertEqual( ['Author 1', 'Author 2'], [author.name for author in article.authors.all().order_by('name')] ) self.assertEqual(article.authors.count(), 2)
def testQuery_onlyFields(self): Article(headline="h1", summary="s1").put() class ArticleType(NdbObjectType): class Meta: model = Article only_fields = ['headline'] class QueryType(graphene.ObjectType): articles = graphene.List(ArticleType) def resolve_articles(self, info): return Article.query() schema = graphene.Schema(query=QueryType) query = ''' query ArticlesQuery { articles { headline } } ''' result = schema.execute(query) self.assertIsNotNone(result.data) self.assertEqual(result.data['articles'][0]['headline'], 'h1') query = ''' query ArticlesQuery { articles { headline, summary } } ''' result = schema.execute(query) self.assertIsNotNone(result.errors) self.assertTrue( 'Cannot query field "summary"' in result.errors[0].message)
def test_assign_splittext(self): a = Article(title='Some Title') a.body = self.post.body self.assertEqual(a.body.excerpt, 'summary\n')
class ParentalM2MTest(TestCase): def setUp(self): self.article = Article(title="Test Title") self.author_1 = Author.objects.create(name="Author 1") self.author_2 = Author.objects.create(name="Author 2") self.article.authors = [self.author_1, self.author_2] self.category_1 = Category.objects.create(name="Category 1") self.category_2 = Category.objects.create(name="Category 2") self.article.categories = [self.category_1, self.category_2] def test_uninitialised_m2m_relation(self): # Reading an m2m relation of a newly created object should return an empty queryset new_article = Article(title="Test title") self.assertEqual([], list(new_article.authors.all())) self.assertEqual(new_article.authors.count(), 0) # the manager should have a 'model' property pointing to the target model self.assertEqual(Author, new_article.authors.model) def test_parentalm2mfield(self): # Article should not exist in the database yet self.assertFalse(Article.objects.filter(title='Test Title').exists()) # Test lookup on parental M2M relation self.assertEqual( ['Author 1', 'Author 2'], [author.name for author in self.article.authors.order_by('name')]) self.assertEqual(self.article.authors.count(), 2) # the manager should have a 'model' property pointing to the target model self.assertEqual(Author, self.article.authors.model) # Test adding to the relation author_3 = Author.objects.create(name="Author 3") self.article.authors.add(author_3) self.assertEqual(['Author 1', 'Author 2', 'Author 3'], [ author.name for author in self.article.authors.all().order_by('name') ]) self.assertEqual(self.article.authors.count(), 3) # Test removing from the relation self.article.authors.remove(author_3) self.assertEqual( ['Author 1', 'Author 2'], [author.name for author in self.article.authors.order_by('name')]) self.assertEqual(self.article.authors.count(), 2) # Test clearing the relation self.article.authors.clear() self.assertEqual( [], [author.name for author in self.article.authors.order_by('name')]) self.assertEqual(self.article.authors.count(), 0) # Test the 'set' operation self.article.authors.set([self.author_2]) self.assertEqual(self.article.authors.count(), 1) self.assertEqual( ['Author 2'], [author.name for author in self.article.authors.order_by('name')]) # Test saving to / restoring from DB self.article.authors = [self.author_1, self.author_2] self.article.save() self.article = Article.objects.get(title="Test Title") self.assertEqual( ['Author 1', 'Author 2'], [author.name for author in self.article.authors.order_by('name')]) self.assertEqual(self.article.authors.count(), 2) def test_constructor(self): # Test passing values for M2M relations as kwargs to the constructor article2 = Article( title="Test article 2", authors=[self.author_1], categories=[self.category_2], ) self.assertEqual( ['Author 1'], [author.name for author in article2.authors.order_by('name')]) self.assertEqual(article2.authors.count(), 1) def test_ordering(self): # our fake querysets should respect the ordering defined on the target model bela_bartok = Author.objects.create(name='Bela Bartok') graham_greene = Author.objects.create(name='Graham Greene') janis_joplin = Author.objects.create(name='Janis Joplin') simon_sharma = Author.objects.create(name='Simon Sharma') william_wordsworth = Author.objects.create(name='William Wordsworth') article3 = Article(title="Test article 3") article3.authors = [ janis_joplin, william_wordsworth, bela_bartok, simon_sharma, graham_greene ] self.assertEqual(list(article3.authors.all()), [ bela_bartok, graham_greene, janis_joplin, simon_sharma, william_wordsworth ]) def test_save_m2m_with_update_fields(self): self.article.save() # modify both relations, but only commit the change to authors self.article.authors.clear() self.article.categories.clear() self.article.title = 'Updated title' self.article.save(update_fields=['title', 'authors']) self.updated_article = Article.objects.get(pk=self.article.pk) self.assertEqual(self.updated_article.title, 'Updated title') self.assertEqual(self.updated_article.authors.count(), 0) self.assertEqual(self.updated_article.categories.count(), 2) def test_reverse_m2m_field(self): # article is unsaved, so should not be returned by the reverse relation on author self.assertEqual(self.author_1.articles_by_author.count(), 0) self.article.save() # should now be able to look up on the reverse relation self.assertEqual(self.author_1.articles_by_author.count(), 1) self.assertEqual(self.author_1.articles_by_author.get(), self.article) article_2 = Article(title="Test Title 2") article_2.authors = [self.author_1] article_2.save() self.assertEqual(self.author_1.articles_by_author.all().count(), 2) self.assertEqual( list( self.author_1.articles_by_author.order_by('title').values_list( 'title', flat=True)), ['Test Title', 'Test Title 2']) def test_value_from_object(self): authors_field = Article._meta.get_field('authors') self.assertEqual(set(authors_field.value_from_object(self.article)), set([self.author_1, self.author_2])) self.article.save() self.assertEqual(set(authors_field.value_from_object(self.article)), set([self.author_1, self.author_2]))
def testNdbObjectType_instanciation(self): instance = Article(headline="test123") h = ArticleType(**instance.to_dict(exclude=["tags", "author_key"])) self.assertEqual(instance.headline, h.headline)
def resolve_articles(self, info): return Article.query()
def resolve_articles(self): return Article.query()
def test_ignored_relations(self): balys_sruoga = Reviewer.objects.create(name='Balys Sruoga') george_orwell = Author.objects.create(name='George Orwell') charles_dickens = Author.objects.create(name='Charles Dickens') rel_article = Article( title='Round and round wherever', authors=[george_orwell], ) article = Article( title='Down and Out in Paris and London', authors=[george_orwell, charles_dickens], reviewer=balys_sruoga, related_articles=[rel_article], ) article_serialised = article.serializable_data() # check that reviewer and related_articles are not serialized (marked with serialize=False) self.assertNotIn('reviewer', article_serialised) self.assertNotIn('related_articles', article_serialised) rel_article.save() article.save() article_json = article.to_json() restored_article = Article.from_json(article_json) restored_article.save() restored_article = Article.objects.get(pk=restored_article.pk) # check that reviewer and related_articles haven't been touched self.assertEqual(balys_sruoga, restored_article.reviewer) self.assertIn(rel_article, restored_article.related_articles.all())
class ParentalM2MTest(TestCase): def setUp(self): self.article = Article(title="Test Title") self.author_1 = Author.objects.create(name="Author 1") self.author_2 = Author.objects.create(name="Author 2") self.article.authors = [self.author_1, self.author_2] self.category_1 = Category.objects.create(name="Category 1") self.category_2 = Category.objects.create(name="Category 2") self.article.categories = [self.category_1, self.category_2] def test_uninitialised_m2m_relation(self): # Reading an m2m relation of a newly created object should return an empty queryset new_article = Article(title="Test title") self.assertEqual([], list(new_article.authors.all())) self.assertEqual(new_article.authors.count(), 0) # the manager should have a 'model' property pointing to the target model self.assertEqual(Author, new_article.authors.model) def test_parentalm2mfield(self): # Article should not exist in the database yet self.assertFalse(Article.objects.filter(title='Test Title').exists()) # Test lookup on parental M2M relation self.assertEqual( ['Author 1', 'Author 2'], [author.name for author in self.article.authors.order_by('name')] ) self.assertEqual(self.article.authors.count(), 2) # the manager should have a 'model' property pointing to the target model self.assertEqual(Author, self.article.authors.model) # Test adding to the relation author_3 = Author.objects.create(name="Author 3") self.article.authors.add(author_3) self.assertEqual( ['Author 1', 'Author 2', 'Author 3'], [author.name for author in self.article.authors.all().order_by('name')] ) self.assertEqual(self.article.authors.count(), 3) # Test removing from the relation self.article.authors.remove(author_3) self.assertEqual( ['Author 1', 'Author 2'], [author.name for author in self.article.authors.order_by('name')] ) self.assertEqual(self.article.authors.count(), 2) # Test clearing the relation self.article.authors.clear() self.assertEqual( [], [author.name for author in self.article.authors.order_by('name')] ) self.assertEqual(self.article.authors.count(), 0) # Test the 'set' operation self.article.authors.set([self.author_2]) self.assertEqual(self.article.authors.count(), 1) self.assertEqual( ['Author 2'], [author.name for author in self.article.authors.order_by('name')] ) # Test saving to / restoring from DB self.article.authors = [self.author_1, self.author_2] self.article.save() self.article = Article.objects.get(title="Test Title") self.assertEqual( ['Author 1', 'Author 2'], [author.name for author in self.article.authors.order_by('name')] ) self.assertEqual(self.article.authors.count(), 2) def test_constructor(self): # Test passing values for M2M relations as kwargs to the constructor article2 = Article( title="Test article 2", authors=[self.author_1], categories=[self.category_2], ) self.assertEqual( ['Author 1'], [author.name for author in article2.authors.order_by('name')] ) self.assertEqual(article2.authors.count(), 1) def test_ordering(self): # our fake querysets should respect the ordering defined on the target model bela_bartok = Author.objects.create(name='Bela Bartok') graham_greene = Author.objects.create(name='Graham Greene') janis_joplin = Author.objects.create(name='Janis Joplin') simon_sharma = Author.objects.create(name='Simon Sharma') william_wordsworth = Author.objects.create(name='William Wordsworth') article3 = Article(title="Test article 3") article3.authors = [ janis_joplin, william_wordsworth, bela_bartok, simon_sharma, graham_greene ] self.assertEqual( list(article3.authors.all()), [bela_bartok, graham_greene, janis_joplin, simon_sharma, william_wordsworth] ) def test_save_m2m_with_update_fields(self): self.article.save() # modify both relations, but only commit the change to authors self.article.authors.clear() self.article.categories.clear() self.article.title = 'Updated title' self.article.save(update_fields=['title', 'authors']) self.updated_article = Article.objects.get(pk=self.article.pk) self.assertEqual(self.updated_article.title, 'Updated title') self.assertEqual(self.updated_article.authors.count(), 0) self.assertEqual(self.updated_article.categories.count(), 2) def test_reverse_m2m_field(self): # article is unsaved, so should not be returned by the reverse relation on author self.assertEqual(self.author_1.articles_by_author.count(), 0) self.article.save() # should now be able to look up on the reverse relation self.assertEqual(self.author_1.articles_by_author.count(), 1) self.assertEqual(self.author_1.articles_by_author.get(), self.article) article_2 = Article(title="Test Title 2") article_2.authors = [self.author_1] article_2.save() self.assertEqual(self.author_1.articles_by_author.all().count(), 2) self.assertEqual( list(self.author_1.articles_by_author.order_by('title').values_list('title', flat=True)), ['Test Title', 'Test Title 2'] ) def test_value_from_object(self): authors_field = Article._meta.get_field('authors') self.assertEqual( set(authors_field.value_from_object(self.article)), set([self.author_1, self.author_2]) ) self.article.save() self.assertEqual( set(authors_field.value_from_object(self.article)), set([self.author_1, self.author_2]) )