How to use reporter method in SeleniumLibrary

Best Python code snippet using SeleniumLibrary

tests.py

Source:tests.py Github

copy

Full Screen

1from datetime import datetime2from django.test import TestCase3from django.core.exceptions import FieldError4from models import Article, Reporter5class ManyToOneTests(TestCase):6 def setUp(self):7 # Create a few Reporters.8 self.r = Reporter(first_name='John', last_name='Smith', email='john@example.com')9 self.r.save()10 self.r2 = Reporter(first_name='Paul', last_name='Jones', email='paul@example.com')11 self.r2.save()12 # Create an Article.13 self.a = Article(id=None, headline="This is a test",14 pub_date=datetime(2005, 7, 27), reporter=self.r)15 self.a.save()16 def test_get(self):17 # Article objects have access to their related Reporter objects.18 r = self.a.reporter19 self.assertEqual(r.id, self.r.id)20 # These are strings instead of unicode strings because that's what was used in21 # the creation of this reporter (and we haven't refreshed the data from the22 # database, which always returns unicode strings).23 self.assertEqual((r.first_name, self.r.last_name), ('John', 'Smith'))24 def test_create(self):25 # You can also instantiate an Article by passing the Reporter's ID26 # instead of a Reporter object.27 a3 = Article(id=None, headline="Third article",28 pub_date=datetime(2005, 7, 27), reporter_id=self.r.id)29 a3.save()30 self.assertEqual(a3.reporter.id, self.r.id)31 # Similarly, the reporter ID can be a string.32 a4 = Article(id=None, headline="Fourth article",33 pub_date=datetime(2005, 7, 27), reporter_id=str(self.r.id))34 a4.save()35 self.assertEqual(repr(a4.reporter), "<Reporter: John Smith>")36 def test_add(self):37 # Create an Article via the Reporter object.38 new_article = self.r.article_set.create(headline="John's second story",39 pub_date=datetime(2005, 7, 29))40 self.assertEqual(repr(new_article), "<Article: John's second story>")41 self.assertEqual(new_article.reporter.id, self.r.id)42 # Create a new article, and add it to the article set.43 new_article2 = Article(headline="Paul's story", pub_date=datetime(2006, 1, 17))44 self.r.article_set.add(new_article2)45 self.assertEqual(new_article2.reporter.id, self.r.id)46 self.assertQuerysetEqual(self.r.article_set.all(),47 [48 "<Article: John's second story>",49 "<Article: Paul's story>",50 "<Article: This is a test>",51 ])52 # Add the same article to a different article set - check that it moves.53 self.r2.article_set.add(new_article2)54 self.assertEqual(new_article2.reporter.id, self.r2.id)55 self.assertQuerysetEqual(self.r2.article_set.all(), ["<Article: Paul's story>"])56 # Adding an object of the wrong type raises TypeError.57 self.assertRaises(TypeError, self.r.article_set.add, self.r2)58 self.assertQuerysetEqual(self.r.article_set.all(),59 [60 "<Article: John's second story>",61 "<Article: This is a test>",62 ])63 def test_assign(self):64 new_article = self.r.article_set.create(headline="John's second story",65 pub_date=datetime(2005, 7, 29))66 new_article2 = self.r2.article_set.create(headline="Paul's story",67 pub_date=datetime(2006, 1, 17))68 # Assign the article to the reporter directly using the descriptor.69 new_article2.reporter = self.r70 new_article2.save()71 self.assertEqual(repr(new_article2.reporter), "<Reporter: John Smith>")72 self.assertEqual(new_article2.reporter.id, self.r.id)73 self.assertQuerysetEqual(self.r.article_set.all(), [74 "<Article: John's second story>",75 "<Article: Paul's story>",76 "<Article: This is a test>",77 ])78 self.assertQuerysetEqual(self.r2.article_set.all(), [])79 # Set the article back again using set descriptor.80 self.r2.article_set = [new_article, new_article2]81 self.assertQuerysetEqual(self.r.article_set.all(), ["<Article: This is a test>"])82 self.assertQuerysetEqual(self.r2.article_set.all(),83 [84 "<Article: John's second story>",85 "<Article: Paul's story>",86 ])87 # Funny case - assignment notation can only go so far; because the88 # ForeignKey cannot be null, existing members of the set must remain.89 self.r.article_set = [new_article]90 self.assertQuerysetEqual(self.r.article_set.all(),91 [92 "<Article: John's second story>",93 "<Article: This is a test>",94 ])95 self.assertQuerysetEqual(self.r2.article_set.all(), ["<Article: Paul's story>"])96 # Reporter cannot be null - there should not be a clear or remove method97 self.assertFalse(hasattr(self.r2.article_set, 'remove'))98 self.assertFalse(hasattr(self.r2.article_set, 'clear'))99 def test_selects(self):100 new_article = self.r.article_set.create(headline="John's second story",101 pub_date=datetime(2005, 7, 29))102 new_article2 = self.r2.article_set.create(headline="Paul's story",103 pub_date=datetime(2006, 1, 17))104 # Reporter objects have access to their related Article objects.105 self.assertQuerysetEqual(self.r.article_set.all(), [106 "<Article: John's second story>",107 "<Article: This is a test>",108 ])109 self.assertQuerysetEqual(self.r.article_set.filter(headline__startswith='This'),110 ["<Article: This is a test>"])111 self.assertEqual(self.r.article_set.count(), 2)112 self.assertEqual(self.r2.article_set.count(), 1)113 # Get articles by id114 self.assertQuerysetEqual(Article.objects.filter(id__exact=self.a.id),115 ["<Article: This is a test>"])116 self.assertQuerysetEqual(Article.objects.filter(pk=self.a.id),117 ["<Article: This is a test>"])118 # Query on an article property119 self.assertQuerysetEqual(Article.objects.filter(headline__startswith='This'),120 ["<Article: This is a test>"])121 # The API automatically follows relationships as far as you need.122 # Use double underscores to separate relationships.123 # This works as many levels deep as you want. There's no limit.124 # Find all Articles for any Reporter whose first name is "John".125 self.assertQuerysetEqual(Article.objects.filter(reporter__first_name__exact='John'),126 [127 "<Article: John's second story>",128 "<Article: This is a test>",129 ])130 # Check that implied __exact also works131 self.assertQuerysetEqual(Article.objects.filter(reporter__first_name='John'),132 [133 "<Article: John's second story>",134 "<Article: This is a test>",135 ])136 # Query twice over the related field.137 self.assertQuerysetEqual(138 Article.objects.filter(reporter__first_name__exact='John',139 reporter__last_name__exact='Smith'),140 [141 "<Article: John's second story>",142 "<Article: This is a test>",143 ])144 # The underlying query only makes one join when a related table is referenced twice.145 queryset = Article.objects.filter(reporter__first_name__exact='John',146 reporter__last_name__exact='Smith')147 self.assertNumQueries(1, list, queryset)148 self.assertEqual(queryset.query.get_compiler(queryset.db).as_sql()[0].count('INNER JOIN'), 1)149 # The automatically joined table has a predictable name.150 self.assertQuerysetEqual(151 Article.objects.filter(reporter__first_name__exact='John').extra(152 where=["many_to_one_reporter.last_name='Smith'"]),153 [154 "<Article: John's second story>",155 "<Article: This is a test>",156 ])157 # ... and should work fine with the unicode that comes out of forms.Form.cleaned_data158 self.assertQuerysetEqual(159 Article.objects.filter(reporter__first_name__exact='John'160 ).extra(where=["many_to_one_reporter.last_name='%s'" % u'Smith']),161 [162 "<Article: John's second story>",163 "<Article: This is a test>",164 ])165 # Find all Articles for a Reporter.166 # Use direct ID check, pk check, and object comparison167 self.assertQuerysetEqual(168 Article.objects.filter(reporter__id__exact=self.r.id),169 [170 "<Article: John's second story>",171 "<Article: This is a test>",172 ])173 self.assertQuerysetEqual(174 Article.objects.filter(reporter__pk=self.r.id),175 [176 "<Article: John's second story>",177 "<Article: This is a test>",178 ])179 self.assertQuerysetEqual(180 Article.objects.filter(reporter=self.r.id),181 [182 "<Article: John's second story>",183 "<Article: This is a test>",184 ])185 self.assertQuerysetEqual(186 Article.objects.filter(reporter=self.r),187 [188 "<Article: John's second story>",189 "<Article: This is a test>",190 ])191 self.assertQuerysetEqual(192 Article.objects.filter(reporter__in=[self.r.id,self.r2.id]).distinct(),193 [194 "<Article: John's second story>",195 "<Article: Paul's story>",196 "<Article: This is a test>",197 ])198 self.assertQuerysetEqual(199 Article.objects.filter(reporter__in=[self.r,self.r2]).distinct(),200 [201 "<Article: John's second story>",202 "<Article: Paul's story>",203 "<Article: This is a test>",204 ])205 # You can also use a queryset instead of a literal list of instances.206 # The queryset must be reduced to a list of values using values(),207 # then converted into a query208 self.assertQuerysetEqual(209 Article.objects.filter(210 reporter__in=Reporter.objects.filter(first_name='John').values('pk').query211 ).distinct(),212 [213 "<Article: John's second story>",214 "<Article: This is a test>",215 ])216 # You need two underscores between "reporter" and "id" -- not one.217 self.assertRaises(FieldError, Article.objects.filter, reporter_id__exact=self.r.id)218 # You need to specify a comparison clause219 self.assertRaises(FieldError, Article.objects.filter, reporter_id=self.r.id)220 def test_reverse_selects(self):221 a3 = Article.objects.create(id=None, headline="Third article",222 pub_date=datetime(2005, 7, 27), reporter_id=self.r.id)223 a4 = Article.objects.create(id=None, headline="Fourth article",224 pub_date=datetime(2005, 7, 27), reporter_id=str(self.r.id))225 # Reporters can be queried226 self.assertQuerysetEqual(Reporter.objects.filter(id__exact=self.r.id),227 ["<Reporter: John Smith>"])228 self.assertQuerysetEqual(Reporter.objects.filter(pk=self.r.id),229 ["<Reporter: John Smith>"])230 self.assertQuerysetEqual(Reporter.objects.filter(first_name__startswith='John'),231 ["<Reporter: John Smith>"])232 # Reporters can query in opposite direction of ForeignKey definition233 self.assertQuerysetEqual(Reporter.objects.filter(article__id__exact=self.a.id),234 ["<Reporter: John Smith>"])235 self.assertQuerysetEqual(Reporter.objects.filter(article__pk=self.a.id),236 ["<Reporter: John Smith>"])237 self.assertQuerysetEqual(Reporter.objects.filter(article=self.a.id),238 ["<Reporter: John Smith>"])239 self.assertQuerysetEqual(Reporter.objects.filter(article=self.a),240 ["<Reporter: John Smith>"])241 self.assertQuerysetEqual(242 Reporter.objects.filter(article__in=[self.a.id,a3.id]).distinct(),243 ["<Reporter: John Smith>"])244 self.assertQuerysetEqual(245 Reporter.objects.filter(article__in=[self.a.id,a3]).distinct(),246 ["<Reporter: John Smith>"])247 self.assertQuerysetEqual(248 Reporter.objects.filter(article__in=[self.a,a3]).distinct(),249 ["<Reporter: John Smith>"])250 self.assertQuerysetEqual(251 Reporter.objects.filter(article__headline__startswith='T'),252 ["<Reporter: John Smith>", "<Reporter: John Smith>"])253 self.assertQuerysetEqual(254 Reporter.objects.filter(article__headline__startswith='T').distinct(),255 ["<Reporter: John Smith>"])256 # Counting in the opposite direction works in conjunction with distinct()257 self.assertEqual(258 Reporter.objects.filter(article__headline__startswith='T').count(), 2)259 self.assertEqual(260 Reporter.objects.filter(article__headline__startswith='T').distinct().count(), 1)261 # Queries can go round in circles.262 self.assertQuerysetEqual(263 Reporter.objects.filter(article__reporter__first_name__startswith='John'),264 [265 "<Reporter: John Smith>",266 "<Reporter: John Smith>",267 "<Reporter: John Smith>",268 ])269 self.assertQuerysetEqual(270 Reporter.objects.filter(article__reporter__first_name__startswith='John').distinct(),271 ["<Reporter: John Smith>"])272 self.assertQuerysetEqual(273 Reporter.objects.filter(article__reporter__exact=self.r).distinct(),274 ["<Reporter: John Smith>"])275 # Check that implied __exact also works.276 self.assertQuerysetEqual(277 Reporter.objects.filter(article__reporter=self.r).distinct(),278 ["<Reporter: John Smith>"])279 # It's possible to use values() calls across many-to-one relations.280 # (Note, too, that we clear the ordering here so as not to drag the281 # 'headline' field into the columns being used to determine uniqueness)282 d = {'reporter__first_name': u'John', 'reporter__last_name': u'Smith'}283 self.assertEqual([d],284 list(Article.objects.filter(reporter=self.r).distinct().order_by()285 .values('reporter__first_name', 'reporter__last_name')))286 def test_select_related(self):287 # Check that Article.objects.select_related().dates() works properly when288 # there are multiple Articles with the same date but different foreign-key289 # objects (Reporters).290 r1 = Reporter.objects.create(first_name='Mike', last_name='Royko', email='royko@suntimes.com')291 r2 = Reporter.objects.create(first_name='John', last_name='Kass', email='jkass@tribune.com')292 a1 = Article.objects.create(headline='First', pub_date=datetime(1980, 4, 23), reporter=r1)293 a2 = Article.objects.create(headline='Second', pub_date=datetime(1980, 4, 23), reporter=r2)294 self.assertEqual(list(Article.objects.select_related().dates('pub_date', 'day')),295 [296 datetime(1980, 4, 23, 0, 0),297 datetime(2005, 7, 27, 0, 0),298 ])299 self.assertEqual(list(Article.objects.select_related().dates('pub_date', 'month')),300 [301 datetime(1980, 4, 1, 0, 0),302 datetime(2005, 7, 1, 0, 0),303 ])304 self.assertEqual(list(Article.objects.select_related().dates('pub_date', 'year')),305 [306 datetime(1980, 1, 1, 0, 0),307 datetime(2005, 1, 1, 0, 0),308 ])309 def test_delete(self):310 new_article = self.r.article_set.create(headline="John's second story",311 pub_date=datetime(2005, 7, 29))312 new_article2 = self.r2.article_set.create(headline="Paul's story",313 pub_date=datetime(2006, 1, 17))314 a3 = Article.objects.create(id=None, headline="Third article",315 pub_date=datetime(2005, 7, 27), reporter_id=self.r.id)316 a4 = Article.objects.create(id=None, headline="Fourth article",317 pub_date=datetime(2005, 7, 27), reporter_id=str(self.r.id))318 # If you delete a reporter, his articles will be deleted.319 self.assertQuerysetEqual(Article.objects.all(),320 [321 "<Article: Fourth article>",322 "<Article: John's second story>",323 "<Article: Paul's story>",324 "<Article: Third article>",325 "<Article: This is a test>",326 ])327 self.assertQuerysetEqual(Reporter.objects.order_by('first_name'),328 [329 "<Reporter: John Smith>",330 "<Reporter: Paul Jones>",331 ])332 self.r2.delete()333 self.assertQuerysetEqual(Article.objects.all(),334 [335 "<Article: Fourth article>",336 "<Article: John's second story>",337 "<Article: Third article>",338 "<Article: This is a test>",339 ])340 self.assertQuerysetEqual(Reporter.objects.order_by('first_name'),341 ["<Reporter: John Smith>"])342 # You can delete using a JOIN in the query.343 Reporter.objects.filter(article__headline__startswith='This').delete()344 self.assertQuerysetEqual(Reporter.objects.all(), [])345 self.assertQuerysetEqual(Article.objects.all(), [])346 def test_regression_12876(self):347 # Regression for #12876 -- Model methods that include queries that348 # recursive don't cause recursion depth problems under deepcopy.349 self.r.cached_query = Article.objects.filter(reporter=self.r)350 from copy import deepcopy...

Full Screen

Full Screen

test_reporter.py

Source:test_reporter.py Github

copy

Full Screen

...25from tornado.ioloop import IOLoop26from tornado.testing import AsyncTestCase, gen_test27from jaeger_client.reporter import Reporter28from jaeger_client.ioloop_util import future_result29def test_null_reporter():30 reporter = jaeger_client.reporter.NullReporter()31 reporter.report_span({})32 f = reporter.close()33 f.result()34def test_in_memory_reporter():35 reporter = jaeger_client.reporter.InMemoryReporter()36 reporter.report_span({})37 f = reporter.close()38 f.result()39 spans = reporter.get_spans()40 assert [{}] == spans41def test_logging_reporter():42 log_mock = mock.MagicMock()43 reporter = jaeger_client.reporter.LoggingReporter(logger=log_mock)44 reporter.report_span({})45 log_mock.info.assert_called_with('Reporting span %s', {})46 reporter.close().result()47class FakeSender(object):48 """49 Mock the _send() method of the reporter by capturing requests50 and returning incomplete futures that can be completed from51 inside the test.52 """53 def __init__(self):54 self.requests = []55 self.futures = []56 def __call__(self, spans):57 # print('ManualSender called', request)58 self.requests.append(spans)59 fut = Future()60 self.futures.append(fut)61 return fut62class HardErrorReporter(object):63 def error(self, name, count, *args):64 raise ValueError(*args)65FakeTrace = collections.namedtuple(66 'FakeTracer', ['ip_address', 'service_name'])67class FakeMetricsFactory(LegacyMetricsFactory):68 def __init__(self):69 super(FakeMetricsFactory, self).__init__(70 Metrics(count=self._incr_count)71 )72 self.counters = {}73 def _incr_count(self, key, value):74 self.counters[key] = value + self.counters.get(key, 0)75class ReporterTest(AsyncTestCase):76 @pytest.fixture77 def thread_loop(self):78 yield79 @staticmethod80 def _new_span(name):81 tracer = FakeTrace(ip_address='127.0.0.1',82 service_name='reporter_test')83 ctx = SpanContext(trace_id=1,84 span_id=1,85 parent_id=None,86 flags=1)87 span = Span(context=ctx,88 tracer=tracer,89 operation_name=name)90 span.start_time = time.time()91 span.end_time = span.start_time + 0.001 # 1ms92 return span93 @staticmethod94 def _new_reporter(batch_size, flush=None, queue_cap=100):95 reporter = Reporter(channel=mock.MagicMock(),96 io_loop=IOLoop.current(),97 batch_size=batch_size,98 flush_interval=flush,99 metrics_factory=FakeMetricsFactory(),100 error_reporter=HardErrorReporter(),101 queue_capacity=queue_cap)102 reporter.set_process('service', {}, max_length=0)103 sender = FakeSender()104 reporter._send = sender105 return reporter, sender106 @tornado.gen.coroutine107 def _wait_for(self, fn):108 """Wait until fn() returns truth, but not longer than 1 second."""109 start = time.time()110 for i in range(1000):111 if fn():112 return113 yield tornado.gen.sleep(0.001)114 print('waited for condition %f seconds' % (time.time() - start))115 @gen_test116 def test_submit_batch_size_1(self):117 reporter, sender = self._new_reporter(batch_size=1)118 reporter.report_span(self._new_span('1'))119 yield self._wait_for(lambda: len(sender.futures) > 0)120 assert 1 == len(sender.futures)121 sender.futures[0].set_result(1)122 yield reporter.close()123 assert 1 == len(sender.futures)124 # send after close125 span_dropped_key = 'jaeger:reporter_spans.result_dropped'126 assert span_dropped_key not in reporter.metrics_factory.counters127 reporter.report_span(self._new_span('1'))128 yield self._wait_for(129 lambda: span_dropped_key in reporter.metrics_factory.counters)130 assert 1 == reporter.metrics_factory.counters[span_dropped_key]131 @gen_test132 def test_submit_failure(self):133 reporter, sender = self._new_reporter(batch_size=1)134 reporter.error_reporter = ErrorReporter(135 metrics=Metrics(), logger=logging.getLogger())136 reporter_failure_key = 'jaeger:reporter_spans.result_err'137 assert reporter_failure_key not in reporter.metrics_factory.counters138 # simulate exception in send139 reporter._send = mock.MagicMock(side_effect=ValueError())140 reporter.report_span(self._new_span('1'))141 yield self._wait_for(142 lambda: reporter_failure_key in reporter.metrics_factory.counters)143 assert 1 == reporter.metrics_factory.counters.get(reporter_failure_key)144 # silly test, for code coverage only145 yield reporter._submit([])146 @gen_test147 def test_submit_queue_full_batch_size_1(self):148 reporter, sender = self._new_reporter(batch_size=1, queue_cap=1)149 reporter.report_span(self._new_span('1'))150 yield self._wait_for(lambda: len(sender.futures) > 0)151 assert 1 == len(sender.futures)152 # the consumer is blocked on a future, so won't drain the queue153 reporter.report_span(self._new_span('2'))154 span_dropped_key = 'jaeger:reporter_spans.result_dropped'155 assert span_dropped_key not in reporter.metrics_factory.counters156 reporter.report_span(self._new_span('3'))157 yield self._wait_for(158 lambda: span_dropped_key in reporter.metrics_factory.counters159 )160 assert 1 == reporter.metrics_factory.counters.get(span_dropped_key)161 # let it drain the queue162 sender.futures[0].set_result(1)163 yield self._wait_for(lambda: len(sender.futures) > 1)164 assert 2 == len(sender.futures)165 sender.futures[1].set_result(1)166 yield reporter.close()167 @gen_test168 def test_submit_batch_size_2(self):169 reporter, sender = self._new_reporter(batch_size=2, flush=0.01)170 reporter.report_span(self._new_span('1'))171 yield tornado.gen.sleep(0.001)172 assert 0 == len(sender.futures)173 reporter.report_span(self._new_span('2'))174 yield self._wait_for(lambda: len(sender.futures) > 0)175 assert 1 == len(sender.futures)176 assert 2 == len(sender.requests[0].spans)177 sender.futures[0].set_result(1)178 # 3rd span will not be submitted right away, but after `flush` interval179 reporter.report_span(self._new_span('3'))180 yield tornado.gen.sleep(0.001)181 assert 1 == len(sender.futures)182 yield tornado.gen.sleep(0.001)183 assert 1 == len(sender.futures)184 yield tornado.gen.sleep(0.01)185 assert 2 == len(sender.futures)186 sender.futures[1].set_result(1)187 yield reporter.close()188 @gen_test189 def test_close_drains_queue(self):190 reporter, sender = self._new_reporter(batch_size=1, flush=0.050)191 reporter.report_span(self._new_span('0'))192 yield self._wait_for(lambda: len(sender.futures) > 0)193 assert 1 == len(sender.futures)194 # now that the consumer is blocked on the first future.195 # let's reset Send to actually respond right away196 # and flood the queue with messages197 count = [0]198 def send(_):199 count[0] += 1200 return future_result(True)201 reporter._send = send202 reporter.batch_size = 3203 for i in range(10):204 reporter.report_span(self._new_span('%s' % i))205 yield self._wait_for(lambda: reporter.queue.qsize() > 0)206 assert reporter.queue.qsize() == 10, 'queued 10 spans'207 # now unblock consumer208 sender.futures[0].set_result(1)209 yield self._wait_for(lambda: count[0] > 2)210 assert count[0] == 3, '9 out of 10 spans submitted in 3 batches'211 assert reporter.queue._unfinished_tasks == 1, 'one span still pending'212 yield reporter.close()213 assert reporter.queue.qsize() == 0, 'all spans drained'214 assert count[0] == 4, 'last span submitted in one extrac batch'215 @gen_test216 def test_composite_reporter(self):217 reporter = jaeger_client.reporter.CompositeReporter(218 jaeger_client.reporter.NullReporter(),219 jaeger_client.reporter.LoggingReporter())220 with mock.patch('jaeger_client.reporter.NullReporter.set_process') \221 as null_mock:222 with mock.patch('jaeger_client.reporter.LoggingReporter.set_process') \223 as log_mock:224 reporter.set_process('x', {}, 123)225 null_mock.assert_called_with('x', {}, 123)226 log_mock.assert_called_with('x', {}, 123)227 with mock.patch('jaeger_client.reporter.NullReporter.report_span') \228 as null_mock:229 with mock.patch('jaeger_client.reporter.LoggingReporter.report_span') \230 as log_mock:...

Full Screen

Full Screen

models.py

Source:models.py Github

copy

Full Screen

1"""24. Many-to-one relationships3To define a many-to-one relationship, use ``ForeignKey()`` .4"""5from django.db import models6class Reporter(models.Model):7 first_name = models.CharField(maxlength=30)8 last_name = models.CharField(maxlength=30)9 email = models.EmailField()10 def __str__(self):11 return "%s %s" % (self.first_name, self.last_name)12class Article(models.Model):13 headline = models.CharField(maxlength=100)14 pub_date = models.DateField()15 reporter = models.ForeignKey(Reporter)16 def __str__(self):17 return self.headline18 class Meta:19 ordering = ('headline',)20__test__ = {'API_TESTS':"""21# Create a few Reporters.22>>> r = Reporter(first_name='John', last_name='Smith', email='john@example.com')23>>> r.save()24>>> r2 = Reporter(first_name='Paul', last_name='Jones', email='paul@example.com')25>>> r2.save()26# Create an Article.27>>> from datetime import datetime28>>> a = Article(id=None, headline="This is a test", pub_date=datetime(2005, 7, 27), reporter=r)29>>> a.save()30>>> a.reporter.id31132>>> a.reporter33<Reporter: John Smith>34# Article objects have access to their related Reporter objects.35>>> r = a.reporter36>>> r.first_name, r.last_name37('John', 'Smith')38# Create an Article via the Reporter object.39>>> new_article = r.article_set.create(headline="John's second story", pub_date=datetime(2005, 7, 29))40>>> new_article41<Article: John's second story>42>>> new_article.reporter.id43144# Create a new article, and add it to the article set.45>>> new_article2 = Article(headline="Paul's story", pub_date=datetime(2006, 1, 17))46>>> r.article_set.add(new_article2)47>>> new_article2.reporter.id48149>>> r.article_set.all()50[<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]51# Add the same article to a different article set - check that it moves.52>>> r2.article_set.add(new_article2)53>>> new_article2.reporter.id54255>>> r.article_set.all()56[<Article: John's second story>, <Article: This is a test>]57>>> r2.article_set.all()58[<Article: Paul's story>]59# Assign the article to the reporter directly using the descriptor60>>> new_article2.reporter = r61>>> new_article2.save()62>>> new_article2.reporter63<Reporter: John Smith>64>>> new_article2.reporter.id65166>>> r.article_set.all()67[<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]68>>> r2.article_set.all()69[]70# Set the article back again using set descriptor.71>>> r2.article_set = [new_article, new_article2]72>>> r.article_set.all()73[<Article: This is a test>]74>>> r2.article_set.all()75[<Article: John's second story>, <Article: Paul's story>]76# Funny case - assignment notation can only go so far; because the77# ForeignKey cannot be null, existing members of the set must remain78>>> r.article_set = [new_article]79>>> r.article_set.all()80[<Article: John's second story>, <Article: This is a test>]81>>> r2.article_set.all()82[<Article: Paul's story>]83# Reporter cannot be null - there should not be a clear or remove method84>>> hasattr(r2.article_set, 'remove')85False86>>> hasattr(r2.article_set, 'clear')87False88# Reporter objects have access to their related Article objects.89>>> r.article_set.all()90[<Article: John's second story>, <Article: This is a test>]91>>> r.article_set.filter(headline__startswith='This')92[<Article: This is a test>]93>>> r.article_set.count()94295>>> r2.article_set.count()96197# Get articles by id98>>> Article.objects.filter(id__exact=1)99[<Article: This is a test>]100>>> Article.objects.filter(pk=1)101[<Article: This is a test>]102# Query on an article property103>>> Article.objects.filter(headline__startswith='This')104[<Article: This is a test>]105# The API automatically follows relationships as far as you need.106# Use double underscores to separate relationships.107# This works as many levels deep as you want. There's no limit.108# Find all Articles for any Reporter whose first name is "John".109>>> Article.objects.filter(reporter__first_name__exact='John')110[<Article: John's second story>, <Article: This is a test>]111# Check that implied __exact also works112>>> Article.objects.filter(reporter__first_name='John')113[<Article: John's second story>, <Article: This is a test>]114# Query twice over the related field.115>>> Article.objects.filter(reporter__first_name__exact='John', reporter__last_name__exact='Smith')116[<Article: John's second story>, <Article: This is a test>]117# The underlying query only makes one join when a related table is referenced twice.118>>> query = Article.objects.filter(reporter__first_name__exact='John', reporter__last_name__exact='Smith')119>>> null, sql, null = query._get_sql_clause()120>>> sql.count('INNER JOIN')1211122# The automatically joined table has a predictable name.123>>> Article.objects.filter(reporter__first_name__exact='John').extra(where=["many_to_one_article__reporter.last_name='Smith'"])124[<Article: John's second story>, <Article: This is a test>]125# Find all Articles for the Reporter whose ID is 1.126# Use direct ID check, pk check, and object comparison 127>>> Article.objects.filter(reporter__id__exact=1)128[<Article: John's second story>, <Article: This is a test>]129>>> Article.objects.filter(reporter__pk=1)130[<Article: John's second story>, <Article: This is a test>]131>>> Article.objects.filter(reporter=1)132[<Article: John's second story>, <Article: This is a test>]133>>> Article.objects.filter(reporter=r)134[<Article: John's second story>, <Article: This is a test>]135>>> Article.objects.filter(reporter__in=[1,2]).distinct()136[<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]137>>> Article.objects.filter(reporter__in=[r,r2]).distinct()138[<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]139# You need two underscores between "reporter" and "id" -- not one.140>>> Article.objects.filter(reporter_id__exact=1)141Traceback (most recent call last):142 ...143TypeError: Cannot resolve keyword 'reporter_id' into field144# You need to specify a comparison clause145>>> Article.objects.filter(reporter_id=1)146Traceback (most recent call last):147 ...148TypeError: Cannot resolve keyword 'reporter_id' into field149# You can also instantiate an Article by passing150# the Reporter's ID instead of a Reporter object.151>>> a3 = Article(id=None, headline="This is a test", pub_date=datetime(2005, 7, 27), reporter_id=r.id)152>>> a3.save()153>>> a3.reporter.id1541155>>> a3.reporter156<Reporter: John Smith>157# Similarly, the reporter ID can be a string.158>>> a4 = Article(id=None, headline="This is a test", pub_date=datetime(2005, 7, 27), reporter_id="1")159>>> a4.save()160>>> a4.reporter161<Reporter: John Smith>162# Reporters can be queried163>>> Reporter.objects.filter(id__exact=1)164[<Reporter: John Smith>]165>>> Reporter.objects.filter(pk=1)166[<Reporter: John Smith>]167>>> Reporter.objects.filter(first_name__startswith='John')168[<Reporter: John Smith>]169# Reporters can query in opposite direction of ForeignKey definition170>>> Reporter.objects.filter(article__id__exact=1)171[<Reporter: John Smith>]172>>> Reporter.objects.filter(article__pk=1)173[<Reporter: John Smith>]174>>> Reporter.objects.filter(article=1)175[<Reporter: John Smith>]176>>> Reporter.objects.filter(article=a)177[<Reporter: John Smith>]178>>> Reporter.objects.filter(article__in=[1,4]).distinct()179[<Reporter: John Smith>]180>>> Reporter.objects.filter(article__in=[1,a3]).distinct()181[<Reporter: John Smith>]182>>> Reporter.objects.filter(article__in=[a,a3]).distinct()183[<Reporter: John Smith>]184>>> Reporter.objects.filter(article__headline__startswith='This')185[<Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>]186>>> Reporter.objects.filter(article__headline__startswith='This').distinct()187[<Reporter: John Smith>]188# Counting in the opposite direction works in conjunction with distinct()189>>> Reporter.objects.filter(article__headline__startswith='This').count()1903191>>> Reporter.objects.filter(article__headline__startswith='This').distinct().count()1921193# Queries can go round in circles.194>>> Reporter.objects.filter(article__reporter__first_name__startswith='John')195[<Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>]196>>> Reporter.objects.filter(article__reporter__first_name__startswith='John').distinct()197[<Reporter: John Smith>]198>>> Reporter.objects.filter(article__reporter__exact=r).distinct()199[<Reporter: John Smith>]200# Check that implied __exact also works201>>> Reporter.objects.filter(article__reporter=r).distinct()202[<Reporter: John Smith>]203# If you delete a reporter, his articles will be deleted.204>>> Article.objects.all()205[<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>, <Article: This is a test>, <Article: This is a test>]206>>> Reporter.objects.order_by('first_name')207[<Reporter: John Smith>, <Reporter: Paul Jones>]208>>> r2.delete()209>>> Article.objects.all()210[<Article: John's second story>, <Article: This is a test>, <Article: This is a test>, <Article: This is a test>]211>>> Reporter.objects.order_by('first_name')212[<Reporter: John Smith>]213# Deletes using a join in the query214>>> Reporter.objects.filter(article__headline__startswith='This').delete()215>>> Reporter.objects.all()216[]217>>> Article.objects.all()218[]...

Full Screen

Full Screen

routes.py

Source:routes.py Github

copy

Full Screen

...19reporter_schema = ReporterSchema()20reporters_schema = ReporterSchema(many=True)21@reporters.route('/reporter', methods=['GET'])22@token_required23def reporter(current_user):24 reporters = None25 if not current_user.admin:26 return jsonify({'message': 'Cannot perform that function!', 'success': False})27 if request.method == 'GET':28 reporter_results = []29 users = User.query.all()30 if users:31 for reporter in users:32 if reporter.post == 'reporter':33 reporter_object = {34 'id': reporter.id,35 'public_id': reporter.public_id,36 'first_name': reporter.first_name,37 'last_name': reporter.last_name,38 'phone_number': reporter.phone_number,39 'post': reporter.post,40 'commune': commune_schema.dump(db.session.query(Commune).get(reporter.commune.id)),41 }42 reporter_results.append(reporter_object)43 # results = reporters_schema.dump(reporters)44 return jsonify({'count': len(reporter_results), 'reporters': reporter_results, 'success': True})45 else:46 return jsonify({'message': 'no reporters are found', 'success': False})47@reporters.route('/reporter/<int:id>', methods=['GET', 'PUT', 'DELETE'])48@token_required49def handle_reporter(current_user, id):50 if not current_user.admin:51 return jsonify({'message': 'Cannot perform that function!','success': False})52 reporter = User.query.get(id)53 if not reporter:54 return jsonify({'message': 'reporter not found','success': False})55 if request.method == 'GET':56 if reporter.post == 'reporter':57 return jsonify({'reporter': reporter_schema.dump(reporter), 'success': True})58 else:59 return jsonify({'message': 'reporter not found', 'success': False})60 elif request.method == 'PUT':61 if request.is_json:62 data = request.get_json()63 reporter.name = data['last_name'] + ' ' + data['first_name']...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run SeleniumLibrary automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful