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())
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_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 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_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_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_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_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 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 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 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 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_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 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 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 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_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_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_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 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 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_none(self): a = Article(title='Some Title', body=None) self.assertEqual(a.body, None)
def test_assign_splittext(self): a = Article(title='Some Title') a.body = self.post.body self.assertEqual(a.body.excerpt, 'summary\n')
def testNdbObjectType_instanciation(self): instance = Article(headline="test123") h = ArticleType(**instance.to_dict(exclude=["tags", "author_key"])) self.assertEqual(instance.headline, h.headline)