How to use Reporter method in istanbul

Best JavaScript code snippet using istanbul

tests.py

Source:tests.py Github

copy

Full Screen

...4from 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):...

Full Screen

Full Screen

test_reporter.py

Source:test_reporter.py Github

copy

Full Screen

...26from 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:231 reporter.report_span({})232 null_mock.assert_called_with({})233 log_mock.assert_called_with({})...

Full Screen

Full Screen

models.py

Source:models.py Github

copy

Full Screen

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....

Full Screen

Full Screen

routes.py

Source:routes.py Github

copy

Full Screen

1import datetime2import jwt3import uuid4from flask import Blueprint5from flask import request, jsonify, make_response6from flask_cors import CORS7from functools import wraps8from werkzeug.security import generate_password_hash, check_password_hash9from rnd_api import app10from rnd_api import db11from rnd_api.models import User, GlobalResult, Commune, Wilaya12from rnd_api.schema import ReporterSchema, ReporterWilayaSchema, CommuneSchema, WilayaSchema13from rnd_api.util import token_required14reporters = Blueprint('reporters', __name__, url_prefix='/api')15cors = CORS(reporters)16commune_schema = CommuneSchema()17wilaya_schema = WilayaSchema()18# verbs implementation for reporter routes-----------------------------------------------------------------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']64 reporter.first_name = data['first_name']65 reporter.last_name = data['last_name']66 reporter.phone_number = data['phone_number']67 if data['commune']:68 reporter.commune = data['commune']69 db.session.add(reporter)70 db.session.commit()71 return jsonify({'message': f'reporter {reporter.name} has been updated successfully.', 'success': True})72 elif request.method == 'DELETE':73 db.session.delete(reporter)74 db.session.commit()75 return jsonify({"message": f"reporter {reporter.name} successfully deleted.", 'success': True})76# verbs implementation for reporter wilaya routes-----------------------------------------------------------------77reporter_wilaya_schema = ReporterWilayaSchema()78reporters_wilaya_schema = ReporterWilayaSchema(many=True)79@reporters.route('/reporter_wilaya', methods=['GET'])80@token_required81def reporter_wilaya(current_user):82 if not current_user.admin:83 return jsonify({'message': 'Cannot perform that function!', 'success': False})84 reporters = User.query.all()85 if reporters:86 if reporter.post == 'reporter_wilaya':87 results = reporters_wilaya_schema.dump(reporters)88 return jsonify({'count': len(results), 'result': results, 'success': True})89 else:90 return jsonify({'message': 'no wilaya reporters are found', 'success': False})91@reporters.route('/reporter_wilaya/<int:id>', methods=['GET', 'PUT', 'DELETE'])92@token_required93def handle_reporter_wilaya(current_user, id):94 if not current_user.admin:95 return jsonify({'message': 'Cannot perform that function!', 'success': False})96 reporter = User.query.get(id)97 if not reporter:98 return jsonify({'message': 'wilaya reporter not found', 'success': False})99 if request.method == 'GET':100 if reporter.post == 'reporter_wilaya':101 return jsonify({'reporter': reporter_wilaya_schema.dump(reporter)})102 else:103 return jsonify({'message': 'wilaya reporter not found'})104 elif request.method == 'PUT':105 if request.is_json:106 data = request.get_json()107 reporter.name = data['last_name'] + ' ' + data['first_name']108 reporter.first_name = data['first_name']109 reporter.last_name = data['last_name']110 reporter.phone_number = data['phone_number']111 if data['wilaya']:112 reporter.wilaya = data['wilaya']113 db.session.add(reporter)114 db.session.commit()115 return jsonify({'message': f'wilaya reporter {reporter.name} has been updated successfully.', 'success': True})116 elif request.method == 'DELETE':117 db.session.delete(reporter)118 db.session.commit()119 return jsonify({"message": f"reporter {reporter.name} successfully deleted.", 'success': True})...

Full Screen

Full Screen

reporters.py

Source:reporters.py Github

copy

Full Screen

...3import logging4import re5import time6from kensu.utils.helpers import singleton, to_snake_case7class Reporter(object):8 def __init__(self, config):9 self.config = config10 # function taking three args: the entity, the api client, and the reporting method (e.g. `report_datastats`)11 @abstractmethod12 def apply(self, obj, kensu_api, method):13 pass 14 def entity_to_json_event(self, entity, kensu_api):15 # FIXME: check if there's a nicer way than to call kensu_api.api_client.sanitize_for_serialization16 sanitized_body = kensu_api.api_client.sanitize_for_serialization(entity)17 # p.s. serialization based on existing rules in kensu-client-scala18 now = round(1000.0 * time.time())19 offline_entity = {20 "action": "add_entity",21 "entity": re.sub(r'(.)([A-Z])', r'\1_\2', entity.__class__.__name__).upper(),22 "generatedEntityGUID": "empty",23 "schemaVersion": "0.1",24 "jsonPayload": sanitized_body,25 "context": {26 "clientId": "",27 # FIXME: make this configurable for reporting events in past28 "clientEventTimestamp": now,29 "serverReceivedTimestamp": now30 }31 }32 return json.dumps(offline_entity) + "\n"33 34 @staticmethod35 def create(config, name = None):36 name = name or config.get("name", None)37 reporter = None38 # if name == "GenericReporter":39 # reporter = GenericReporter(config)40 if name == "DoNothingReporter":41 reporter = DoNothingReporter(config)42 elif name == "PrintReporter":43 reporter = PrintReporter(config)44 elif name == "LoggingReporter":45 reporter = LoggingReporter(config)46 elif name == "FileReporter":47 reporter = FileReporter(config)48 elif name == "ApiReporter":49 reporter = ApiReporter(config)50 elif name == "KafkaReporter":51 reporter = KafkaReporter(config)52 elif name == "MultiReporter":53 reporter = MultiReporter(config)54 return reporter55class GenericReporter(Reporter):56 def __init__(self, config, fun):57 super().__init__(config)58 self.fun = fun59 def apply(self, obj, kensu_api, method):60 return self.fun(obj, kensu_api, method)61class DoNothingReporter(Reporter):62 def apply(self, obj, kensu_api, method):63 return obj64class PrintReporter(Reporter):65 def apply(self, obj, kensu_api, method):66 json = self.entity_to_json_event(obj, kensu_api)67 print(json)68 return obj69class LoggingReporter(Reporter):70 def __init__(self, config, level=None):71 super().__init__(config)72 self.level = level73 if self.level is None and config is not None and config["level"] is not None:74 self.level = config["level"]75 self.level = self.level.lower()76 if self.level == "info":77 self.log = logging.info78 elif self.level == "warn":79 self.log = logging.warning80 elif self.level == "error":81 self.log = logging.error82 elif self.level == "debug":83 self.log = logging.debug84 else:85 print('No logging level was specified for LoggingReporter, using ERROR log level')86 self.log = logging.error87 def apply(self, obj, kensu_api, method):88 json = self.entity_to_json_event(obj, kensu_api)89 if self.log:90 res = self.log(obj)91 return obj92class FileReporter(Reporter):93 def __init__(self, config, file_name=None):94 super().__init__(config)95 if config is not None:96 file_name = file_name or config["file_name"]97 self.file = open(file_name, "a")98 import atexit99 atexit.register(self.close_gracefully)100 def close(self):101 if self.file is not None:102 self.file.close()103 def close_gracefully(self):104 try:105 self.close()106 except IOError as ex:107 print('Failed closing the output file', ex)108 def apply(self, obj, kensu_api, method):109 self.file.write(self.entity_to_json_event(obj, kensu_api))110 self.file.flush()111 return obj112class ApiReporter(Reporter):113 def apply(self, obj, kensu_api, method):114 method(obj)115 return obj116class KafkaReporter(Reporter):117 def __init__(self, config):118 super().__init__(config)119 if config is not None:120 from confluent_kafka import Producer121 import socket122 self.bootstrap_servers = ",".join(json.loads(config["bootstrap_servers"]))123 conf = {'bootstrap.servers': self.bootstrap_servers,124 'client.id': socket.gethostname()}125 self.topic = config["topic"]126 self.producer = Producer(conf)127 def apply(self, obj, kensu_api, method):128 guid = obj.to_guid()129 token_and_entity = {130 "token": kensu_api.api_client.default_headers["X-Auth-Token"],131 "entity": self.entity_to_json_event(obj, kensu_api)132 }133 s = json.dumps(token_and_entity)134 self.producer.produce(self.topic, key=guid, value=s)135 return obj136class MultiReporter(Reporter):137 def __init__(self, config):138 super().__init__(config)139 reporters_names = json.loads(config.get("reporters"))140 self.reporters = [Reporter.create(config, name = name) for name in reporters_names]141 def apply(self, obj, kensu_api, method):142 for r in self.reporters:...

Full Screen

Full Screen

text.py

Source:text.py Github

copy

Full Screen

...22from pylint.interfaces import IReporter23from pylint.reporters import BaseReporter24import six25TITLE_UNDERLINES = ['', '=', '-', '.']26class TextReporter(BaseReporter):27 """reports messages and layouts in plain text"""28 __implements__ = IReporter29 name = 'text'30 extension = 'txt'31 line_format = '{C}:{line:3d},{column:2d}: {msg} ({symbol})'32 def __init__(self, output=None):33 BaseReporter.__init__(self, output)34 self._modules = set()35 self._template = None36 def on_set_current_module(self, module, filepath):37 self._template = six.text_type(self.linter.config.msg_template or self.line_format)38 def write_message(self, msg):39 """Convenience method to write a formated message with class default template"""40 self.writeln(msg.format(self._template))41 def handle_message(self, msg):42 """manage message of different type and in the context of path"""43 if msg.module not in self._modules:44 if msg.module:45 self.writeln('************* Module %s' % msg.module)46 self._modules.add(msg.module)47 else:48 self.writeln('************* ')49 self.write_message(msg)50 def _display(self, layout):51 """launch layouts display"""52 print(file=self.out)53 TextWriter().format(layout, self.out)54class ParseableTextReporter(TextReporter):55 """a reporter very similar to TextReporter, but display messages in a form56 recognized by most text editors :57 <filename>:<linenum>:<msg>58 """59 name = 'parseable'60 line_format = '{path}:{line}: [{msg_id}({symbol}), {obj}] {msg}'61 def __init__(self, output=None):62 warnings.warn('%s output format is deprecated. This is equivalent '63 'to --msg-template=%s' % (self.name, self.line_format),64 DeprecationWarning)65 TextReporter.__init__(self, output)66class VSTextReporter(ParseableTextReporter):67 """Visual studio text reporter"""68 name = 'msvs'69 line_format = '{path}({line}): [{msg_id}({symbol}){obj}] {msg}'70class ColorizedTextReporter(TextReporter):71 """Simple TextReporter that colorizes text output"""72 name = 'colorized'73 COLOR_MAPPING = {74 "I" : ("green", None),75 'C' : (None, "bold"),76 'R' : ("magenta", "bold, italic"),77 'W' : ("blue", None),78 'E' : ("red", "bold"),79 'F' : ("red", "bold, underline"),80 'S' : ("yellow", "inverse"), # S stands for module Separator81 }82 def __init__(self, output=None, color_mapping=None):83 TextReporter.__init__(self, output)84 self.color_mapping = color_mapping or \...

Full Screen

Full Screen

twisted_trial.py

Source:twisted_trial.py Github

copy

Full Screen

2from zope.interface import implementer3from twisted.trial.itrial import IReporter4from twisted.plugin import IPlugin5@implementer(IPlugin, IReporter)6class _Reporter(object):7 def __init__(self, name, module, description, longOpt, shortOpt, klass):8 self.name = name9 self.module = module10 self.description = description11 self.longOpt = longOpt12 self.shortOpt = shortOpt13 self.klass = klass14Tree = _Reporter("Tree Reporter",15 "twisted.trial.reporter",16 description="verbose color output (default reporter)",17 longOpt="verbose",18 shortOpt="v",19 klass="TreeReporter")20BlackAndWhite = _Reporter("Black-And-White Reporter",21 "twisted.trial.reporter",22 description="Colorless verbose output",23 longOpt="bwverbose",24 shortOpt="o",25 klass="VerboseTextReporter")26Minimal = _Reporter("Minimal Reporter",27 "twisted.trial.reporter",28 description="minimal summary output",29 longOpt="summary",30 shortOpt="s",31 klass="MinimalReporter")32Classic = _Reporter("Classic Reporter",33 "twisted.trial.reporter",34 description="terse text output",35 longOpt="text",36 shortOpt="t",37 klass="TextReporter")38Timing = _Reporter("Timing Reporter",39 "twisted.trial.reporter",40 description="Timing output",41 longOpt="timing",42 shortOpt=None,43 klass="TimingTextReporter")44Subunit = _Reporter("Subunit Reporter",45 "twisted.trial.reporter",46 description="subunit output",47 longOpt="subunit",48 shortOpt=None,...

Full Screen

Full Screen

many_to_one_null.py

Source:many_to_one_null.py Github

copy

Full Screen

...3To define a many-to-one relationship that can have a null foreign key, use4``ForeignKey()`` with ``null=True`` .5"""6from django.core import meta7class Reporter(meta.Model):8 name = meta.CharField(maxlength=30)9 def __repr__(self):10 return self.name11class Article(meta.Model):12 headline = meta.CharField(maxlength=100)13 reporter = meta.ForeignKey(Reporter, null=True)14 def __repr__(self):15 return self.headline16API_TESTS = """17# Create a Reporter.18>>> r = reporters.Reporter(name='John Smith')19>>> r.save()20# Create an Article.21>>> a = articles.Article(headline="First", reporter=r)22>>> a.save()23>>> a.reporter_id24125>>> a.get_reporter()26John Smith27# Article objects have access to their related Reporter objects.28>>> r = a.get_reporter()29# Create an Article via the Reporter object.30>>> a2 = r.add_article(headline="Second")31>>> a232Second...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var istanbul = require('istanbul');2var collector = new istanbul.Collector();3collector.add(global.__coverage__ || {});4var reporter = new istanbul.Reporter();5reporter.add('lcov');6reporter.write(collector, true, function () {7 console.log('All reports generated');8});

Full Screen

Using AI Code Generation

copy

Full Screen

1var istanbul = require('istanbul');2var collector = new istanbul.Collector();3var reporter = new istanbul.Reporter();4var sync = false;5collector.add(global.__coverage__);6reporter.add('lcov');7reporter.write(collector, sync, function () {8 console.log('All reports generated');9});10 at LcovReport.Report.mix.writeReport (/Users/abhinav.aggarwal/Desktop/Projects/NodeJs/CodeCoverage/node_modules/istanbul/lib/report/lcovonly.js:29:14)11 at LcovReport.Report.mix.writeReports (/Users/abhinav.aggarwal/Desktop/Projects/NodeJs/CodeCoverage/node_modules/istanbul/lib/report/index.js:172:24)12 at Array.forEach (native)13 at Report.mix.writeReports (/Users/abhinav.aggarwal/Desktop/Projects/NodeJs/CodeCoverage/node_modules/istanbul/lib/report/index.js:475:14)14 at Array.forEach (native)15 at Collector.mix.add (/Users/abhinav.aggarwal/Desktop/Projects/NodeJs/CodeCoverage/node_modules/istanbul/lib/collector.js:43:17)16 at Object.<anonymous> (/Users/abhinav.aggarwal/Desktop/Projects/NodeJs/CodeCoverage/test.js:7:8)17 at Module._compile (module.js:460:26)18"scripts": {

Full Screen

Using AI Code Generation

copy

Full Screen

1var istanbul = require('istanbul');2var reporter = new istanbul.Reporter();3reporter.add('text');4reporter.addAll(['lcov', 'json', 'html']);5reporter.write(collector, true, function () {6 console.log('All reports generated');7});

Full Screen

Using AI Code Generation

copy

Full Screen

1var istanbul = require('istanbul');2var collector = new istanbul.Collector();3var reporter = new istanbul.Reporter();4var sync = false;5collector.add(coverage);6reporter.add('html');7reporter.write(collector, sync, function () {8 console.log('All reports generated');9});

Full Screen

Using AI Code Generation

copy

Full Screen

1var istanbul = require('istanbul');2var reporter = new istanbul.Reporter();3reporter.add('text-summary');4reporter.addAll(['html', 'lcov']);5reporter.write(istanbul.collector, true, function () {6 console.log('All reports generated');7});8process.env.NODE_ENV = 'test';9var istanbul = require('istanbul');10var reporter = new istanbul.Reporter();11reporter.add('text-summary');12reporter.addAll(['html', 'lcov']);13reporter.write(istanbul.collector, true, function () {14 console.log('All reports generated');15});16reporter.write(istanbul.collector, true, function () {17at Object. (C:\Users\abc\Desktop\Jenkins\Jenkins_home\workspace\JenkinsTest\test.js:7:1)18at Module._compile (module.js:571:32)19at Object.Module._extensions..js (module.js:580:10)20at Module.load (module.js:488:32)21at tryModuleLoad (module.js:447:12)22at Function.Module._load (module.js:439:3)23at Function.Module.runMain (module.js:605:10)24at startup (bootstrap_node.js:158:16)25node {26 stage('Checkout') {27 }28 stage('Install') {29 }30 stage('Test') {31 }32 stage('Build') {33 }34 stage('Deploy') {35 }36}37node {38 stage('Checkout') {39 }

Full Screen

Using AI Code Generation

copy

Full Screen

1var istanbul = require('istanbul');2var collector = new istanbul.Collector();3var reporter = new istanbul.Reporter();4reporter.write(collector, sync, function () { console.log('All reports generated'); });5var istanbul = require('istanbul');6var collector = new istanbul.Collector();7var reporter = new istanbul.Reporter();8reporter.write(collector, sync, function () { console.log('All reports generated'); });9gulp.task('coverage', function () {10 return gulp.src(['./test/**/*.js'])11 .pipe(istanbul())12 .on('finish', function () {13 gulp.src(['./test/**/*.js'])14 .pipe(mocha())15 .pipe(istanbul.writeReports({16 }))17 .pipe(istanbul.enforceThresholds({ thresholds: { global: 90 } }));18 });19});20gulp.task('coverage', function () {21 return gulp.src(['./test/**/*.js'])

Full Screen

Using AI Code Generation

copy

Full Screen

1var istanbul = require('istanbul');2var reporter = new istanbul.Reporter();3reporter.addAll(['text-summary', 'lcov', 'html']);4reporter.write(coverage, true, function() {5 console.log('write completed');6});

Full Screen

Using AI Code Generation

copy

Full Screen

1var istanbul = require('istanbul');2var collector = new istanbul.Collector();3var reporter = new istanbul.Reporter();4collector.add(global.__coverage__ || {});5reporter.add('text');6reporter.write(collector, sync, function () {7 console.log('All reports generated');8});9var istanbul = require('istanbul');10var collector = new istanbul.Collector();11var reporter = new istanbul.Reporter();12collector.add(global.__coverage__ || {});13reporter.add('text');14reporter.write(collector, sync, function () {15 console.log('All reports generated');16});

Full Screen

Using AI Code Generation

copy

Full Screen

1var istanbul = require('istanbul');2var collector = new istanbul.Collector();3var reporter = new istanbul.Reporter();4var sync = false;5var coverage = { ... };6collector.add(coverage);7reporter.add('text-summary');8reporter.add('html');9reporter.write(collector, sync, function () {10 console.log('reports generated');11});

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 istanbul 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