id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
145,448
Linaro/squad
Linaro_squad/test/core/test_test_data.py
test.core.test_test_data.JSONTestDataParserTest
class JSONTestDataParserTest(TestCase): def test_empty(self): self.assertEqual([], json_parser(None)) self.assertEqual([], json_parser('')) self.assertEqual([], json_parser('{}')) def test_basic(self): data = json_parser(TEST_DATA) self.assertEqual(6, len(data)) def test_test_name(self): test_names = [t['test_name'] for t in json_parser(TEST_DATA)] self.assertIn("ungrouped_pass", test_names) self.assertIn("pass", test_names) def test_group_name(self): group_names = [t['group_name'] for t in json_parser(TEST_DATA)] self.assertIn('group1', group_names) self.assertIn('group2', group_names) def test_group_and_test_name(self): data = json_parser(TEST_DATA) test = [ t for t in data if t['group_name'] == 'group1' and t['test_name'] == "pass" ][0] self.assertTrue(test['pass']) def test_group_name_defaults_to_slash(self): data = json_parser('{"/mytest0": "pass", "mytest1": "fail"}') test0 = [t for t in data if t['test_name'] == 'mytest0'][0] self.assertEqual('/', test0['group_name']) self.assertEqual("mytest0", test0['test_name']) test1 = [t for t in data if t['test_name'] == 'mytest1'][0] self.assertEqual('/', test1['group_name']) self.assertEqual("mytest1", test1['test_name'])
class JSONTestDataParserTest(TestCase): def test_empty(self): pass def test_basic(self): pass def test_test_name(self): pass def test_group_name(self): pass def test_group_and_test_name(self): pass def test_group_name_defaults_to_slash(self): pass
7
0
5
0
5
0
1
0
1
0
0
0
6
0
6
78
39
8
31
15
24
0
28
15
21
1
2
0
6
145,449
Linaro/squad
Linaro_squad/test/core/test_statistics.py
test.core.test_statistics.GeomeanTest
class GeomeanTest(TestCase): def test_basic(self): self.assertAlmostEqual(3.1622, geomean([1, 10]), 3) def test_exclude_zeroes(self): self.assertAlmostEqual(4, geomean([4, 0, 4])) def test_exclude_negative_numbers(self): self.assertAlmostEqual(4, geomean([4, -1, 4])) def test_empty_set(self): self.assertAlmostEqual(0, geomean([])) def test_set_with_only_invalid_values(self): self.assertAlmostEqual(0, geomean([0]))
class GeomeanTest(TestCase): def test_basic(self): pass def test_exclude_zeroes(self): pass def test_exclude_negative_numbers(self): pass def test_empty_set(self): pass def test_set_with_only_invalid_values(self): pass
6
0
2
0
2
0
1
0
1
0
0
0
5
0
5
77
16
5
11
6
5
0
11
6
5
1
2
0
5
145,450
Linaro/squad
Linaro_squad/test/test_pending_migrations.py
test.test_pending_migrations.TestPendingMigrations
class TestPendingMigrations(TestCase): def test_pending_migrations(self): output = StringIO() management.call_command('makemigrations', '--dry-run', stdout=output) expected_output = 'No changes detected\n' pending_migrations = output.getvalue() if expected_output != pending_migrations: print('There are pending migrations:') print(pending_migrations) self.assertEqual(expected_output, pending_migrations)
class TestPendingMigrations(TestCase): def test_pending_migrations(self): pass
2
0
11
2
9
0
2
0
1
0
0
0
1
0
1
73
12
2
10
5
8
0
10
5
8
2
2
1
2
145,451
Linaro/squad
Linaro_squad/test/test_mail.py
test.test_mail.TestMessage
class TestMessage(TestCase): def setUp(self): self.msg = Message('mail subject', 'mail body', 'sender@example.com', ['recipient@example.com']) def test_precedence(self): self.assertEqual('bulk', self.msg.extra_headers["Precedence"]) def test_auto_submitted(self): self.assertEqual('auto-generated', self.msg.extra_headers['Auto-Submitted']) def test_x_auto_response_supress(self): self.assertEqual('All', self.msg.extra_headers['X-Auto-Response-Suppress'])
class TestMessage(TestCase): def setUp(self): pass def test_precedence(self): pass def test_auto_submitted(self): pass def test_x_auto_response_supress(self): pass
5
0
2
0
2
0
1
0
1
1
1
0
4
1
4
4
13
4
9
6
4
0
9
6
4
1
1
0
4
145,452
Linaro/squad
Linaro_squad/test/test_i18n.py
test.test_i18n.TestI18N
class TestI18N(TestCase): def test_locales_supported_by_django(self): django_languages = set(lng for lng, _ in global_settings.LANGUAGES) languages = glob('%s/squad/*/locale/*/LC_MESSAGES' % settings.BASE_DIR) languages = set(basename(dirname(lng.lower().replace('_', '-'))) for lng in languages) intersection = django_languages & languages self.assertEqual(intersection, languages, 'language code not supported by Django. Must be one of %r' % sorted(django_languages))
class TestI18N(TestCase): def test_locales_supported_by_django(self): pass
2
0
6
0
6
0
1
0
1
1
0
0
1
0
1
1
8
1
7
5
5
0
7
5
5
1
1
0
1
145,453
Linaro/squad
Linaro_squad/test/test_cors.py
test.test_cors.CrossOriginResourceSharingTest
class CrossOriginResourceSharingTest(TestCase): def setUp(self): client = Client() self.response = client.options('/', {}, **{'HTTP_ORIGIN': 'https://www.example.com/'}) def test_allow_origin(self): self.assertEqual('*', self.response['Access-Control-Allow-Origin']) def test_allow_methods(self): self.assertEqual('GET, HEAD', self.response['Access-Control-Allow-Methods'])
class CrossOriginResourceSharingTest(TestCase): def setUp(self): pass def test_allow_origin(self): pass def test_allow_methods(self): pass
4
0
2
0
2
0
1
0
1
0
0
0
3
1
3
3
11
3
8
6
4
0
8
6
4
1
1
0
3
145,454
Linaro/squad
Linaro_squad/test/plugins/test_plugin.py
test.plugins.test_plugin.TestGetPuginInstance
class TestGetPuginInstance(TestCase): def test_example(self): plugin = get_plugin_instance('example') self.assertIsInstance(plugin, Plugin) def test_nonexisting(self): with self.assertRaises(PluginNotFound): get_plugin_instance('nonexisting')
class TestGetPuginInstance(TestCase): def test_example(self): pass def test_nonexisting(self): pass
3
0
3
0
3
0
1
0
1
2
2
0
2
0
2
2
9
2
7
4
4
0
7
4
4
1
1
1
2
145,455
Linaro/squad
Linaro_squad/test/core/test_tasks.py
test.core.test_tasks.CommonTestCase
class CommonTestCase(TestCase): def setUp(self): group = Group.objects.create(slug='mygroup') project = group.projects.create(slug='mygroup') self.build = project.builds.create(version='1.0.0') self.environment = project.environments.create(slug='myenv') self.testrun = TestRun.objects.create( build=self.build, environment=self.environment, ) tests_file = '{"test0": "fail", "foobar/test1": "pass", "onlytests/test1": "pass", "missing/mytest": "skip", "special/case.for[result/variants]": "pass"}' metrics_file = '{"metric0": {"value": 1, "unit": ""}, "foobar/metric1": {"value": 10, "unit": "kb"}, "foobar/metric2": {"value": "10.5", "unit": "kb"}}' self.testrun.save_tests_file(tests_file) self.testrun.save_metrics_file(metrics_file)
class CommonTestCase(TestCase): def setUp(self): pass
2
0
14
1
13
0
1
0
1
1
1
6
1
3
1
1
16
2
14
9
12
0
11
9
9
1
1
0
1
145,456
Linaro/squad
Linaro_squad/test/core/test_tasks.py
test.core.test_tasks.ParseTestRunDataTest
class ParseTestRunDataTest(CommonTestCase): def test_basics(self): ParseTestRunData()(self.testrun) self.assertEqual(5, self.testrun.tests.count()) self.assertEqual(3, self.testrun.metrics.count()) def test_name_with_variant(self): ParseTestRunData()(self.testrun) special_case = self.testrun.tests.filter(metadata__name="case.for[result/variants]") self.assertEqual(1, special_case.count()) def test_does_not_process_twice(self): ParseTestRunData()(self.testrun) ParseTestRunData()(self.testrun) self.assertEqual(5, self.testrun.tests.count()) self.assertEqual(3, self.testrun.metrics.count()) def test_creates_suite_metadata(self): ParseTestRunData()(self.testrun) suite = self.testrun.tests.last().suite metadata = suite.metadata self.assertEqual('suite', metadata.kind) def test_creates_test_metadata(self): ParseTestRunData()(self.testrun) test = self.testrun.tests.last() metadata = test.metadata self.assertIsNotNone(metadata) self.assertEqual(test.name, metadata.name) self.assertEqual(test.suite.slug, metadata.suite) self.assertEqual('test', metadata.kind) def test_creates_metric_metadata(self): ParseTestRunData()(self.testrun) self.testrun.refresh_from_db() metric = self.testrun.metrics.last() metadata = metric.metadata self.assertIsNotNone(metadata) self.assertEqual(metric.name, metadata.name) self.assertEqual(metric.suite.slug, metadata.suite) self.assertEqual('metric', metadata.kind) def test_name_too_long(self): really_long_name = 'longname' * 100 testrun = TestRun.objects.create( build=self.build, environment=self.environment, ) tests_file = '{"' + really_long_name + '": "fail", "foobar/test1": "pass", "onlytests/test1": "pass", "missing/mytest": "skip", "special/case.for[result/variants]": "pass"}' metrics_file = '{"' + really_long_name + '": {"value": 1, "unit": "seconds"}, "foobar/metric1": {"value": 10, "unit": ""}, "foobar/metric2": {"value": "10.5", "unit": "cycles"}}' testrun.save_tests_file(tests_file) testrun.save_metrics_file(metrics_file) ParseTestRunData()(testrun) self.assertEqual(4, testrun.tests.count()) self.assertEqual(2, testrun.metrics.count())
class ParseTestRunDataTest(CommonTestCase): def test_basics(self): pass def test_name_with_variant(self): pass def test_does_not_process_twice(self): pass def test_creates_suite_metadata(self): pass def test_creates_test_metadata(self): pass def test_creates_metric_metadata(self): pass def test_name_too_long(self): pass
8
0
7
1
7
0
1
0
1
2
2
0
7
1
7
8
59
10
49
20
41
0
46
19
38
1
2
0
7
145,457
Linaro/squad
Linaro_squad/test/core/test_tasks.py
test.core.test_tasks.ProcessAllTestRunsTest
class ProcessAllTestRunsTest(CommonTestCase): def test_processes_all(self): ProcessAllTestRuns()() self.assertEqual(5, self.testrun.tests.count()) self.assertEqual(6, self.testrun.status.count())
class ProcessAllTestRunsTest(CommonTestCase): def test_processes_all(self): pass
2
0
4
0
4
0
1
0
1
1
1
0
1
0
1
2
6
1
5
2
3
0
5
2
3
1
2
0
1
145,458
Linaro/squad
Linaro_squad/test/core/test_tasks.py
test.core.test_tasks.RecordTestRunStatusTest
class RecordTestRunStatusTest(CommonTestCase): def test_basics(self): ParseTestRunData()(self.testrun) RecordTestRunStatus()(self.testrun) # one for each suite + general self.assertEqual(1, Status.objects.filter(suite=None).count()) self.assertEqual(1, Status.objects.filter(suite__slug='/').count()) self.assertEqual(1, Status.objects.filter(suite__slug='foobar').count()) self.assertEqual(1, Status.objects.filter(suite__slug='onlytests').count()) self.assertEqual(1, Status.objects.filter(suite__slug='missing').count()) self.assertEqual(1, Status.objects.filter(suite__slug='special').count()) status = Status.objects.filter(suite=None).last() self.assertEqual(status.tests_pass, 3) self.assertEqual(status.tests_fail, 1) self.assertEqual(status.tests_skip, 1) self.assertEqual(status.has_metrics, True) self.assertIsInstance(status.metrics_summary, float) def test_xfail(self): issue = KnownIssue.objects.create( title='some known issue', test_name='test0', ) issue.environments.add(self.environment) ParseTestRunData()(self.testrun) RecordTestRunStatus()(self.testrun) global_status = Status.objects.filter(suite=None).last() suite_status = Status.objects.filter(suite__slug='/').last() self.assertEqual(global_status.tests_xfail, 1) self.assertEqual(suite_status.tests_xfail, 1) def test_xfail_with_suite_name(self): issue = KnownIssue.objects.create( title='some known issue', test_name='foobar/test1', ) issue.environments.add(self.environment) new_testrun = TestRun.objects.create( build=self.testrun.build, environment=self.testrun.environment) tests_file = re.sub('"pass"', '"fail"', self.testrun.tests_file) new_testrun.save_tests_file(tests_file) ParseTestRunData()(new_testrun) RecordTestRunStatus()(new_testrun) global_status = Status.objects.filter(suite=None).last() suite_status = Status.objects.filter(suite__slug='foobar').last() self.assertEqual(global_status.tests_xfail, 1) self.assertEqual(suite_status.tests_xfail, 1) def test_does_not_process_twice(self): ParseTestRunData()(self.testrun) RecordTestRunStatus()(self.testrun) RecordTestRunStatus()(self.testrun) self.assertEqual(1, Status.objects.filter(suite=None).count()) def test_suite_version_not_informed(self): ParseTestRunData()(self.testrun) RecordTestRunStatus()(self.testrun) self.assertEqual(0, SuiteVersion.objects.filter(suite__slug='/').count()) self.assertEqual(0, SuiteVersion.objects.filter(suite__slug='foobar').count()) self.assertEqual(0, SuiteVersion.objects.filter(suite__slug='onlytests').count()) self.assertEqual(0, SuiteVersion.objects.filter(suite__slug='missing').count()) self.assertEqual(0, SuiteVersion.objects.filter(suite__slug='special').count()) self.assertIsNone(self.testrun.status.by_suite().first().suite_version) def set_suite_versions(self): self.testrun.metadata['suite_versions'] = { '/': '1', 'foobar': '2', 'onlytests': '3', 'missing': '4', 'special': '5', } self.testrun.save() def test_suite_version_informed(self): self.set_suite_versions() ParseTestRunData()(self.testrun) RecordTestRunStatus()(self.testrun) self.assertEqual(1, SuiteVersion.objects.filter(version='1', suite__slug='/').count()) self.assertEqual(1, SuiteVersion.objects.filter(version='2', suite__slug='foobar').count()) self.assertEqual(1, SuiteVersion.objects.filter(version='3', suite__slug='onlytests').count()) self.assertEqual(1, SuiteVersion.objects.filter(version='4', suite__slug='missing').count()) self.assertEqual(1, SuiteVersion.objects.filter(version='5', suite__slug='special').count()) self.assertIsNotNone(self.testrun.status.by_suite().first().suite_version)
class RecordTestRunStatusTest(CommonTestCase): def test_basics(self): pass def test_xfail(self): pass def test_xfail_with_suite_name(self): pass def test_does_not_process_twice(self): pass def test_suite_version_not_informed(self): pass def set_suite_versions(self): pass def test_suite_version_informed(self): pass
8
0
12
1
11
0
1
0.01
1
7
6
0
7
0
7
8
94
15
78
17
70
1
64
17
56
1
2
0
7
145,459
Linaro/squad
Linaro_squad/test/core/test_tasks.py
test.core.test_tasks.TestValidateTestRun
class TestValidateTestRun(TestCase): # ~~~~~~~~~~~~ TESTS FOR METADATA ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def assertInvalidMetadata(self, metadata, exception=exceptions.InvalidMetadata): validate = ValidateTestRun() with self.assertRaises(exception): validate(metadata_file=metadata) def test_invalid_metadata_json(self): self.assertInvalidMetadata('{', exceptions.InvalidMetadataJSON) def test_invalid_metadata_type(self): self.assertInvalidMetadata('[]') def test_invalid_job_id(self): self.assertInvalidMetadata('{"job_id": "foo/bar"}') def test_invalid_job_id_data_type(self): self.assertInvalidMetadata('{"job_id": 1.2}') self.assertInvalidMetadata('{"job_id": [1,2]}') self.assertInvalidMetadata('{"job_id": {"a": 1}}') # ~~~~~~~~~~~~ TESTS FOR METRICS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def assertInvalidMetrics(self, metrics, exception=exceptions.InvalidMetricsData): validate = ValidateTestRun() with self.assertRaises(exception): validate(metrics_file=metrics) def test_invalid_metrics_json(self): self.assertInvalidMetrics('{', exceptions.InvalidMetricsDataJSON) def test_invalid_metrics_type(self): self.assertInvalidMetrics('[]') def test_invalid_metrics_str_as_values(self): self.assertInvalidMetrics('{ "foo" : {"value": "bar", "unit": ""}}') def test_invalid_metrics_list_of_str_as_values(self): self.assertInvalidMetrics('{ "foo" : {"value": ["bar"], "unit": ""}}') def assertValidMetrics(self, metrics): validate = ValidateTestRun() validate(metrics_file=metrics) def test_number_as_string(self): self.assertValidMetrics('{"foo": {"value": "1.00000", "unit": ""}}') # ~~~~~~~~~~~~ TESTS FOR TESTS DATA ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def assertInvalidTests(self, tests, exception=exceptions.InvalidTestsData): validate = ValidateTestRun() with self.assertRaises(exception): validate(tests_file=tests) def test_invalid_tests_json(self): self.assertInvalidTests('{', exceptions.InvalidTestsDataJSON) def test_invalid_tests_type(self): self.assertInvalidTests('[]')
class TestValidateTestRun(TestCase): def assertInvalidMetadata(self, metadata, exception=exceptions.InvalidMetadata): pass def test_invalid_metadata_json(self): pass def test_invalid_metadata_type(self): pass def test_invalid_job_id(self): pass def test_invalid_job_id_data_type(self): pass def assertInvalidMetrics(self, metrics, exception=exceptions.InvalidMetricsData): pass def test_invalid_metrics_json(self): pass def test_invalid_metrics_type(self): pass def test_invalid_metrics_str_as_values(self): pass def test_invalid_metrics_list_of_str_as_values(self): pass def assertValidMetrics(self, metrics): pass def test_number_as_string(self): pass def assertInvalidTests(self, tests, exception=exceptions.InvalidTestsData): pass def test_invalid_tests_json(self): pass def test_invalid_tests_type(self): pass
16
0
3
0
3
0
1
0.07
1
7
7
0
15
0
15
15
58
15
40
20
24
3
40
20
24
1
1
1
15
145,460
Linaro/squad
Linaro_squad/test/core/test_test.py
test.core.test_test.TestConfidenceTest
class TestConfidenceTest(TestCase): def setUp(self): self.group = Group.objects.create(slug="group") self.project = self.group.projects.create(slug="project") self.env = self.project.environments.create(slug="env") self.suite = self.project.suites.create(slug="suite") self.test_name = "test" self.metadata, _ = SuiteMetadata.objects.get_or_create( suite=self.suite.slug, name=self.test_name, kind="test" ) def new_test(self, version, result): build = self.project.builds.create(version=version) self.assertIsNotNone(build) test_run = build.test_runs.create(environment=self.env, job_id="999") self.assertIsNotNone(test_run) test = test_run.tests.create( suite=self.suite, result=result, metadata=self.metadata, build=test_run.build, environment=test_run.environment, ) self.assertIsNotNone(test) return test def test_confidence(self): t1 = self.new_test("1", True) t2 = self.new_test("2", True) t3 = self.new_test("3", True) t4 = self.new_test("4", True) t5 = self.new_test("5", False) t5.set_confidence(self.project.build_confidence_threshold, [t1, t2, t3, t4]) self.assertIsNotNone(t5.confidence) self.assertEqual(t5.confidence.passes, 4) self.assertEqual(t5.confidence.count, 4) self.assertEqual(t5.confidence.threshold, self.project.build_confidence_threshold) self.assertEqual(t5.confidence.score, 100)
class TestConfidenceTest(TestCase): def setUp(self): pass def new_test(self, version, result): pass def test_confidence(self): pass
4
0
13
1
12
0
1
0
1
1
1
0
3
6
3
3
43
7
36
18
32
0
28
18
24
1
1
0
3
145,461
Linaro/squad
Linaro_squad/test/core/test_test.py
test.core.test_test.TestFailureHistoryTest
class TestFailureHistoryTest(TestCase): def setUp(self): group = Group.objects.create(slug='group') self.project = group.projects.create(slug='project') self.suite = self.project.suites.create(slug='suite') self.environment = self.project.environments.create(slug='environment') self.date = timezone.now() def previous_test(self, test, result, environment=None): environment = environment or self.environment build = self.project.builds.create( datetime=self.date, version=self.date.strftime("%Y%m%d"), ) test_run = build.test_runs.create(environment=environment) metadata, _ = SuiteMetadata.objects.get_or_create(suite=self.suite.slug, name=test, kind='test') test = test_run.tests.create(suite=self.suite, result=result, metadata=metadata, build=test_run.build, environment=test_run.environment) self.date = self.date + relativedelta(days=1) return test def test_first(self): first = self.previous_test("mytest", True) current = self.previous_test("mytest", False) self.assertEqual(None, current.history.since) self.assertEqual(0, current.history.count) self.assertEqual(first, current.history.last_different) def test_second(self): passed = self.previous_test("mytest", True) previous = self.previous_test("mytest", False) current = self.previous_test("mytest", False) self.assertEqual(previous, current.history.since) self.assertEqual(1, current.history.count) self.assertEqual(passed, current.history.last_different) def test_third(self): first = self.previous_test("mytest", False) self.previous_test("mytest", False) current = self.previous_test("mytest", False) self.assertEqual(first, current.history.since) self.assertEqual(2, current.history.count) def test_first_after_previous_regression(self): self.previous_test("mytest", False) last = self.previous_test("mytest", True) current = self.previous_test("mytest", False) self.assertEqual(None, current.history.since) self.assertEqual(0, current.history.count) self.assertEqual(last, current.history.last_different) def test_later_tests_dont_influence(self): last_pass = self.previous_test("mytest", True) first = self.previous_test("mytest", False) self.previous_test("mytest", False) current = self.previous_test("mytest", False) self.previous_test("mytest", True) # future! self.previous_test("mytest", False) # future! self.assertEqual(first, current.history.since) self.assertEqual(2, current.history.count) self.assertEqual(last_pass, current.history.last_different) def test_test_from_another_environment_is_not_considered(self): last_pass = self.previous_test("mytest", True) first = self.previous_test("mytest", False) # test results from another environment otherenv = self.project.environments.create(slug='otherenv') self.previous_test("mytest", True, otherenv) self.previous_test("mytest", False, otherenv) current = self.previous_test("mytest", False) self.assertEqual(first, current.history.since) self.assertEqual(1, current.history.count) self.assertEqual(last_pass, current.history.last_different)
class TestFailureHistoryTest(TestCase): def setUp(self): pass def previous_test(self, test, result, environment=None): pass def test_first(self): pass def test_second(self): pass def test_third(self): pass def test_first_after_previous_regression(self): pass def test_later_tests_dont_influence(self): pass def test_test_from_another_environment_is_not_considered(self): pass
9
0
9
1
8
0
1
0.05
1
2
1
0
8
4
8
8
77
12
64
33
55
3
61
33
52
1
1
0
8
145,462
Linaro/squad
Linaro_squad/test/integration/plugins/test_tradefed.py
test_tradefed.TestTradefed
class TestTradefed(TestCase): def setUp(self): self.group = Group.objects.create(slug="mygroup") self.project = self.group.projects.create(slug="myproject", project_settings="PLUGINS_TRADEFED_EXTRACT_AGGREGATED: True") self.build = self.project.builds.create(version="tradefed-build") self.env = self.project.environments.create(slug="myenv") self.testrun = self.build.test_runs.create(environment=self.env) self.backend = Backend.objects.create(url="http://lava.server/api/v0.2/", name="tradefed-backend", implementation_type="lava") self.testjob = self.build.test_jobs.create(definition=definition, target=self.project, backend=self.backend, job_id="123", testrun=self.testrun) self.tradefed = get_plugin_instance('tradefed') def test_parse_cts_results(self): with requests_mock.Mocker() as m: m.get('http://lava.server/api/v0.2/jobs/123/suites/', json=job_suites) m.get('http://lava.server/api/v0.2/jobs/123/suites/1/tests/', json=suite_attachments) m.get('http://attachment.server/artifacts/team/qa/2022/06/08/10/55/tradefed-output-20220608105250.tar.xz', content=tar_contents) self.tradefed.postprocess_testjob(self.testjob) self.testrun.refresh_from_db() # Check that the status has been recorded self.assertTrue(self.testrun.status_recorded) status = Status.objects.get(test_run=self.testrun, suite=None) self.assertEqual(6272, status.tests_pass) self.assertEqual(1, status.tests_fail) # Check that the failed test contain the proper log failed_test = self.testrun.tests.filter(result=False).first() expected_log = 'with config {glformat=rgba8888d24s8ms0,rotation=unspecified,surfacetype=window,required=true}' self.assertIn(expected_log, failed_test.log) # Check that the attachment was saved to the testrun self.assertTrue(self.testrun.attachments.count() > 0)
class TestTradefed(TestCase): def setUp(self): pass def test_parse_cts_results(self): pass
3
0
16
3
12
2
1
0.12
1
2
2
0
2
8
2
2
35
7
25
15
22
3
25
14
22
1
1
1
2
145,463
Linaro/squad
Linaro_squad/test/core/test_notification.py
test.core.test_notification.TestSendApprovedNotification
class TestSendApprovedNotification(TestModeratedNotifications): def setUp(self): super(TestSendApprovedNotification, self).setUp() self.status.approved = True self.status.save() send_status_notification(self.status) def test_mails_users(self): self.assertEqual(['user@example.com'], mail.outbox[0].recipients()) def test_marks_as_notified(self): self.assertTrue(self.status.notified)
class TestSendApprovedNotification(TestModeratedNotifications): def setUp(self): pass def test_mails_users(self): pass def test_marks_as_notified(self): pass
4
0
3
0
3
0
1
0
1
1
0
0
3
0
3
4
13
3
10
4
6
0
10
4
6
1
2
0
3
145,464
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/core/models.py
squad.core.models.Subscription.Meta
class Meta: unique_together = ('project', 'user',)
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
0
0
0
145,465
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/test/test_architecture.py
test.test_architecture.ArchitectureConformanceTest
class ArchitectureConformanceTest(TestCase): def test_architecture(self): data = subprocess.check_output( ['sfood', '--internal-only', 'squad'], stderr=subprocess.DEVNULL, ) for line in data.splitlines(): (path1, file1), (path2, file2) = eval(line) res, msg = check_dependency(file1, file2) self.assertTrue(res, msg)
class ArchitectureConformanceTest(TestCase): def test_architecture(self): pass
2
0
9
0
9
0
2
0
1
0
0
0
1
0
1
73
10
0
10
6
8
0
7
6
5
2
2
1
2
145,466
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.SuiteMetadataSerializer.Meta
class Meta: model = SuiteMetadata fields = '__all__'
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
145,467
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.SuiteSerializer.Meta
class Meta: model = Suite exclude = ('metadata',)
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
145,468
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.SuiteViewSet
class SuiteViewSet(viewsets.ModelViewSet): """ Additional actions: * `api/suites/<id>/tests` GET Returns list of all test belonging to this suite """ queryset = Suite.objects.all() serializer_class = SuiteSerializer filterset_class = SuiteFilter # TODO: remove when django-filters 1.x is not supported anymore filter_class = filterset_class @action(detail=True, methods=['get'], suffix='tests') def tests(self, request, pk=None): suite = self.get_object() tests = Test.objects.filter(suite=suite).prefetch_related( 'metadata', 'suite', 'known_issues').order_by('id') paginator = CursorPaginationWithPageSize() page = paginator.paginate_queryset(tests, request) serializer = TestSerializer(page, many=True, context={ 'request': request}, remove_fields=['suite']) return paginator.get_paginated_response(serializer.data)
class SuiteViewSet(viewsets.ModelViewSet): ''' Additional actions: * `api/suites/<id>/tests` GET Returns list of all test belonging to this suite ''' @action(detail=True, methods=['get'], suffix='tests') def tests(self, request, pk=None): pass
3
1
7
0
7
0
1
0.46
1
3
3
0
1
0
1
1
22
4
13
12
10
6
12
11
10
1
1
0
1
145,469
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.TestFilter.Meta
class Meta: model = Test fields = {'result': ['exact', 'in', 'isnull'], 'suite_id': ['exact', 'in'], 'environment_id': ['exact', 'in'], 'metadata_id': ['exact', 'in'], 'build_id': ['exact', 'in', 'gt', 'lt'], 'has_known_issues': ['exact', 'in']}
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
8
0
8
3
7
0
3
3
2
0
0
0
0
145,470
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.TestJobFilter.Meta
class Meta: model = TestJob fields = {'name': ['exact', 'in', 'startswith', 'contains', 'icontains'], "environment": ['exact', 'in', 'startswith', 'contains', 'icontains'], "submitted": ['exact', 'in'], "fetched": ['exact', 'in'], "fetch_attempts": ['exact', 'in'], "last_fetch_attempt": ['exact', 'in', 'lt', 'gt', 'lte', 'gte'], "created_at": ['exact', 'in', 'lt', 'gt', 'lte', 'gte'], "failure": ['exact', 'in', 'startswith', 'contains', 'icontains'], "can_resubmit": ['exact', 'in'], "resubmitted_count": ['exact', 'in'], "job_status": ['exact', 'in', 'startswith', 'contains', 'icontains'], "job_id": ['exact', 'in', 'startswith', 'contains', 'icontains'], "id": ['exact', 'in']}
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
15
0
15
3
14
0
3
3
2
0
0
0
0
145,471
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.TestJobUpdateSerializer.Meta
class Meta: model = TestJob fields = '__all__'
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
145,472
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.TestJobViewSet
class TestJobViewSet(ModelViewSet): """ List of CI test jobs. Only testjobs for public projects, and for projects you have access to, are available. Additional actions: * `api/testjobs/<id>/definition` GET Presents original test job definition * `api/testjobs/<id>/resubmit` POST Allows to resubmit the job. Will produce new test job using the same backend * `api/testjobs/<id>/force_resubmit` POST Same as 'resubmit' but can be done also on successful jobs * `api/testjobs/<id>/resubmitted_jobs` GET Get a list of all child jobs of this one * `api/testjobs/<id>/cancel` POST Allows to cancel a job * `api/testjobs/<id>/fetch` POST Allows fetching a job """ queryset = TestJob.objects.prefetch_related( 'backend').order_by('-id').defer('definition') project_lookup_key = 'target_build__project__in' serializer_class = TestJobSerializer filterset_fields = ( "name", "environment", "submitted", "fetched", "fetch_attempts", "last_fetch_attempt", "failure", "can_resubmit", "resubmitted_count", "job_status", "job_id", "backend", "target", "testrun", ) # TODO: remove when django-filters 1.x is not supported anymore filter_fields = filterset_fields filterset_class = TestJobFilter # TODO: remove when django-filters 1.x is not supported anymore filter_class = filterset_class search_fields = ("name", "environment", "last_fetch_attempt") ordering_fields = ("id", "name", "environment", "last_fetch_attempt") pagination_class = CursorPaginationWithPageSize ordering = ('id',) def update(self, request, pk=None): self.serializer_class = TestJobUpdateSerializer return super().update(request, pk) @action(detail=True, methods=['get'], suffix='definition') def definition(self, request, pk=None): definition = self.get_object().definition return HttpResponse(definition, content_type='text/plain') @action(detail=True, methods=['post'], suffix='resubmit') def resubmit(self, request, **kwargs): testjob = self.get_object() if testjob.resubmit(): # find latest child of this job new_testjob = testjob.resubmitted_jobs.last() if new_testjob is None: new_testjob = testjob else: log_addition(request, new_testjob, "Created testjob as resubmission") data = {"message": "OK", "url": rest_reverse( 'testjob-detail', args=[new_testjob.pk], request=request)} return Response(data, status=status.HTTP_200_OK) return Response( {"message": "Error resubmitting job.", "url": rest_reverse("testjob-detail", args=[testjob.pk], request=request)}, status=status.HTTP_200_OK) @action(detail=True, methods=['post'], suffix='force_resubmit') def force_resubmit(self, request, **kwargs): testjob = self.get_object() if testjob.force_resubmit(): # find latest child of this job new_testjob = testjob.resubmitted_jobs.last() if new_testjob is None: new_testjob = testjob else: log_addition(request, new_testjob, "Created testjob as resubmission") data = {"message": "OK", "url": rest_reverse( 'testjob-detail', args=[new_testjob.pk], request=request)} return Response(data, status=status.HTTP_200_OK) return Response( {"message": "Error resubmitting job.", "url": rest_reverse("testjob-detail", args=[testjob.pk], request=request)}, status=status.HTTP_200_OK) @action(detail=True, methods=['post'], suffix='cancel') def cancel(self, request, **kwargs): testjob = self.get_object() testjob.cancel() log_change(request, testjob, "Testjob canceled") return Response({'job_id': testjob.job_id, 'status': testjob.job_status}, status=status.HTTP_200_OK) @action(detail=True, methods=['post'], suffix='fetch') def fetch(self, request, **kwargs): testjob = self.get_object() testjob.fetched = False testjob.fetch_attempts = 0 testjob.save() fetch.delay(testjob.id) log_change(request, testjob, "Testjob queued for fetching") return Response({'job_id': testjob.job_id, 'status': 'Queued for fetching'}, status=status.HTTP_200_OK) @action(detail=True, methods=['get'], suffix='resubmitted_jobs') def resubmitted_jobs(self, request, pk=None): jobs = self.get_object().resubmitted_jobs.all() page = self.paginate_queryset(jobs) serializer = TestJobSerializer( page, many=True, context={'request': request}) return self.get_paginated_response(serializer.data)
class TestJobViewSet(ModelViewSet): ''' List of CI test jobs. Only testjobs for public projects, and for projects you have access to, are available. Additional actions: * `api/testjobs/<id>/definition` GET Presents original test job definition * `api/testjobs/<id>/resubmit` POST Allows to resubmit the job. Will produce new test job using the same backend * `api/testjobs/<id>/force_resubmit` POST Same as 'resubmit' but can be done also on successful jobs * `api/testjobs/<id>/resubmitted_jobs` GET Get a list of all child jobs of this one * `api/testjobs/<id>/cancel` POST Allows to cancel a job * `api/testjobs/<id>/fetch` POST Allows fetching a job ''' def update(self, request, pk=None): pass @action(detail=True, methods=['get'], suffix='definition') def definition(self, request, pk=None): pass @action(detail=True, methods=['post'], suffix='resubmit') def resubmit(self, request, **kwargs): pass @action(detail=True, methods=['post'], suffix='force_resubmit') def force_resubmit(self, request, **kwargs): pass @action(detail=True, methods=['post'], suffix='cancel') def cancel(self, request, **kwargs): pass @action(detail=True, methods=['post'], suffix='fetch') def fetch(self, request, **kwargs): pass @action(detail=True, methods=['get'], suffix='resubmitted_jobs') def resubmitted_jobs(self, request, pk=None): pass
14
1
8
0
7
0
2
0.25
1
3
2
0
7
0
7
9
124
20
85
37
71
21
56
31
48
3
2
2
11
145,473
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.TestRunFilter.Meta
class Meta: model = TestRun fields = {'id': ['exact', 'in'], 'job_id': ['exact', 'in', 'startswith'], 'job_status': ['exact', 'in', 'startswith'], 'environment_id': ['exact', 'in'], 'data_processed': ['exact'], 'status_recorded': ['exact'], 'created_at': ['exact', 'lt', 'lte', 'gt', 'gte'], 'datetime': ['exact', 'lt', 'lte', 'gt', 'gte'], 'completed': ['exact']}
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
11
0
11
3
10
0
3
3
2
0
0
0
0
145,474
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.TestRunSerializer.Meta
class Meta: model = TestRun exclude = ['tests_file_storage', 'metrics_file_storage', 'log_file_storage']
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
145,475
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.TestRunViewSet
class TestRunViewSet(ModelViewSet): """ List of test runs. Test runs represent test executions of a given build on a given environment. Only test runs from public projects and from projects accessible to you are available. Additional actions: * `api/testruns/<id>/tests_file` GET Presents tests_file from original submission * `api/testruns/<id>/metrics_file` GET Presents metrics_file from original submission * `api/testruns/<id>/metadata_file` GET Presents metadata_file from original submission * `api/testruns/<id>/log_file` GET Presents log_file from original submission * `api/testruns/<id>/tests` GET Returns list of Test objects belonging to this test run. List is paginated * `api/testruns/<id>/metrics` GET Returns list of Metric objects belonging to this test run. List is paginated * `api/testruns/<id>/status` GET Presents summary view for each suite present in this test run """ queryset = TestRun.objects.prefetch_related( Prefetch("status", queryset=Status.objects.filter(suite=None)) ).order_by("-id") project_lookup_key = 'build__project__in' serializer_class = TestRunSerializer filterset_fields = ( "build", "completed", "job_status", "data_processed", "status_recorded", "environment", ) # TODO: remove when django-filters 1.x is not supported anymore filter_fields = filterset_fields filterset_class = TestRunFilter # TODO: remove when django-filters 1.x is not supported anymore filter_class = filterset_class search_fields = ('environment',) ordering_fields = ('id', 'created_at', 'environment', 'datetime') pagination_class = CursorPaginationWithPageSize ordering = ('id',) @action(detail=True, methods=['get']) def tests_file(self, request, pk=None): testrun = self.get_object() return HttpResponse(testrun.tests_file, content_type='application/json') @action(detail=True, methods=['get']) def metrics_file(self, request, pk=None): testrun = self.get_object() return HttpResponse(testrun.metrics_file, content_type='application/json') @action(detail=True, methods=['get']) def metadata_file(self, request, pk=None): testrun = self.get_object() return HttpResponse(testrun.metadata_file, content_type='application/json') @action(detail=True, methods=['get']) def log_file(self, request, pk=None): testrun = self.get_object() return HttpResponse(testrun.log_file, content_type='text/plain') @action(detail=True, methods=['get'], suffix='tests') def tests(self, request, pk=None): testrun = self.get_object() tests = testrun.tests.prefetch_related( 'suite', 'known_issues', 'metadata').order_by('id') paginator = CursorPaginationWithPageSize() page = paginator.paginate_queryset(tests, request) serializer = TestSerializer(page, many=True, context={ 'request': request}, remove_fields=['test_run']) return paginator.get_paginated_response(serializer.data) @action(detail=True, methods=['get'], suffix='metrics') def metrics(self, request, pk=None): testrun = self.get_object() metrics = testrun.metrics.prefetch_related('suite').order_by('id') paginator = CursorPaginationWithPageSize() page = paginator.paginate_queryset(metrics, request) serializer = MetricSerializer(page, many=True, context={ 'request': request}, remove_fields=['test_run', 'id', 'suite']) return paginator.get_paginated_response(serializer.data) @action(detail=True, methods=['get'], suffix='attachments') def attachments(self, request, pk=None): filename = request.GET.get('filename') testrun = self.get_object() try: attachment = testrun.attachments.get(filename=filename) except Attachment.DoesNotExist: raise NotFound() return HttpResponse(bytes(attachment.data), content_type='text/plain')
class TestRunViewSet(ModelViewSet): ''' List of test runs. Test runs represent test executions of a given build on a given environment. Only test runs from public projects and from projects accessible to you are available. Additional actions: * `api/testruns/<id>/tests_file` GET Presents tests_file from original submission * `api/testruns/<id>/metrics_file` GET Presents metrics_file from original submission * `api/testruns/<id>/metadata_file` GET Presents metadata_file from original submission * `api/testruns/<id>/log_file` GET Presents log_file from original submission * `api/testruns/<id>/tests` GET Returns list of Test objects belonging to this test run. List is paginated * `api/testruns/<id>/metrics` GET Returns list of Metric objects belonging to this test run. List is paginated * `api/testruns/<id>/status` GET Presents summary view for each suite present in this test run ''' @action(detail=True, methods=['get']) def tests_file(self, request, pk=None): pass @action(detail=True, methods=['get']) def metrics_file(self, request, pk=None): pass @action(detail=True, methods=['get']) def metadata_file(self, request, pk=None): pass @action(detail=True, methods=['get']) def log_file(self, request, pk=None): pass @action(detail=True, methods=['get'], suffix='tests') def tests_file(self, request, pk=None): pass @action(detail=True, methods=['get'], suffix='metrics') def metrics_file(self, request, pk=None): pass @action(detail=True, methods=['get'], suffix='attachments') def attachments(self, request, pk=None): pass
15
1
5
0
5
0
1
0.37
1
5
4
0
7
0
7
9
106
23
62
43
47
23
46
36
38
2
2
1
8
145,476
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.TestSerializer.Meta
class Meta: model = Test fields = '__all__'
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
145,477
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/ci/models.py
squad.ci.models.TestJob.Meta
class Meta: # This index speeds up Backend.poll(), where it queries submitted and fetched together indexes = [ models.Index(fields=['submitted', 'fetched']), ]
class Meta: pass
1
0
0
0
0
0
0
0.25
0
0
0
0
0
0
0
0
5
0
4
2
3
1
2
2
1
0
0
0
0
145,478
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/core/admin.py
squad.core.admin.KnownIssueAdminForm.Meta
class Meta: model = models.KnownIssue fields = "__all__"
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
145,479
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/core/admin.py
squad.core.admin.PatchSourceForm.Meta
class Meta: model = models.PatchSource fields = ['name', 'url', 'username', 'password', 'token', 'implementation']
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
145,480
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/core/history.py
squad.core.history.TestResult.TestRunStatus
class TestRunStatus(object): def __init__(self, test_run_id, suite): self.test_run_id = test_run_id self.suite = suite
class TestRunStatus(object): def __init__(self, test_run_id, suite): pass
2
0
3
0
3
0
1
0
1
0
0
0
1
2
1
1
4
0
4
4
2
0
4
4
2
1
1
0
1
145,481
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/core/management/commands/users.py
squad.core.management.commands.users.Command.add_arguments.SubParser
class SubParser(CommandParser): """ Sub-parsers constructor that mimic Django constructor. See http://stackoverflow.com/a/37414551 """ def __init__(self, **kwargs): kwargs.update( { "called_from_command_line": getattr( cmd, "_called_from_command_line", None ) } ) super().__init__(**kwargs)
class SubParser(CommandParser): ''' Sub-parsers constructor that mimic Django constructor. See http://stackoverflow.com/a/37414551 ''' def __init__(self, **kwargs): pass
2
1
9
0
9
0
1
0.4
1
2
1
0
1
0
1
1
15
1
10
2
8
4
4
2
2
1
1
0
1
145,482
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/core/models.py
squad.core.models.Build.Meta
class Meta: unique_together = ('project', 'version',) ordering = ['datetime']
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
145,483
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/core/models.py
squad.core.models.BuildPlaceholder.Meta
class Meta: unique_together = ('project', 'version',)
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
0
0
0
145,484
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/core/models.py
squad.core.models.BuildSummary.Meta
class Meta: unique_together = ('build', 'environment',)
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
0
0
0
145,485
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/core/models.py
squad.core.models.Callback.Meta
class Meta: unique_together = ('object_reference_type', 'object_reference_id', 'url', 'event')
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
0
0
0
145,486
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/core/models.py
squad.core.models.Group.Meta
class Meta: ordering = ['slug']
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
0
0
0
145,487
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/core/models.py
squad.core.models.GroupMember.Meta
class Meta: unique_together = ('group', 'user') verbose_name = N_('Group member') verbose_name_plural = N_('Group members')
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
4
0
4
4
3
0
4
4
3
0
0
0
0
145,488
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/core/models.py
squad.core.models.MetricThreshold.Meta
class Meta: unique_together = ('project', 'environment', 'name',)
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
0
0
0
145,489
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/core/models.py
squad.core.models.NotificationDelivery.Meta
class Meta: unique_together = ('status', 'subject', 'txt', 'html')
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
0
0
0
145,490
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/core/models.py
squad.core.models.Project.Meta
class Meta: unique_together = ('group', 'slug',) ordering = ['group', 'slug']
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
145,491
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/core/models.py
squad.core.models.ProjectStatus.Meta
class Meta: verbose_name_plural = "Project statuses"
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
0
0
0
145,492
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/core/models.py
squad.core.models.Status.Meta
class Meta: unique_together = ('test_run', 'suite',)
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
0
0
0
145,493
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.SuiteMetadataFilter.Meta
class Meta: model = SuiteMetadata fields = {'id': ['exact', 'in'], 'name': ['exact', 'in', 'startswith', 'contains', 'icontains'], 'suite': ['exact', 'in', 'startswith', 'contains', 'icontains'], 'kind': ['exact', 'in', 'startswith', 'contains', 'icontains']}
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
6
0
6
3
5
0
3
3
2
0
0
0
0
145,494
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.SuiteFilter.Meta
class Meta: model = Suite fields = {'id': ['exact', 'in'], 'name': ['exact', 'in', 'startswith', 'contains', 'icontains'], 'slug': ['exact', 'in', 'startswith', 'contains', 'icontains']}
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
5
0
5
3
4
0
3
3
2
0
0
0
0
145,495
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.StatusSerializer.Meta
class Meta: model = Status exclude = ['suite_version']
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
145,496
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.StatusFilter.Meta
class Meta: model = Status fields = {'suite': ['exact', 'isnull'], 'metrics_summary': ['gt', 'lt'], 'tests_pass': ['gt', 'lt'], 'tests_fail': ['gt', 'lt'], 'tests_xfail': ['gt', 'lt'], 'tests_skip': ['gt', 'lt'], 'has_metrics': ['exact'], 'suite_id': ['exact', 'in', 'isnull'], 'test_run_id': ['exact', 'in']}
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
11
0
11
3
10
0
3
3
2
0
0
0
0
145,497
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.AnnotationSerializer.Meta
class Meta: model = Annotation fields = '__all__'
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
145,498
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.AttachmentSerializer.Meta
class Meta: model = Attachment fields = ('download_url', 'filename', 'mimetype', 'length')
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
145,499
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.BackendFilter.Meta
class Meta: model = Backend fields = {'id': ['exact', 'in'], 'name': ['exact', 'in', 'startswith', 'contains', 'icontains'], 'implementation_type': ['exact']}
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
5
0
5
3
4
0
3
3
2
0
0
0
0
145,500
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.BackendSerializer.Meta
class Meta: model = Backend fields = '__all__' extra_kwargs = { 'token': {'write_only': True} }
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
6
0
6
4
5
0
4
4
3
0
0
0
0
145,501
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.BuildFilter.Meta
class Meta: model = Build fields = {'version': ['exact', 'in', 'startswith'], 'id': ['exact', 'in', 'lt', 'lte', 'gt', 'gte'], 'created_at': ['exact', 'lt', 'lte', 'gt', 'gte'], 'is_release': ['exact', 'in'] }
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
7
0
7
3
6
0
3
3
2
0
0
0
0
145,502
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.BuildSerializer.Meta
class Meta: model = Build fields = '__all__'
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
145,503
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.BuildViewSet
class BuildViewSet(NestedViewSetMixin, ModelViewSet): """ List of all builds in the system. Only builds belonging to public projects and to projects you have access to are available. Additional actions: * `api/builds/<id>/metadata` GET Build metadata list * `api/builds/<id>/metadata_by_testrun` GET Build metadata list now separated by testrun * `api/builds/<id>/status` GET Build status and cached test/metric totals * `api/builds/<id>/testruns` GET List of test runs in the build * `api/builds/<id>/testjobs` GET List of test jobs in the build (if any) * `api/builds/<id>/testjobs_summary` GET List of test jobs in the build summarized by job_status. If `per_environment` is specified in the query string, the summary will be split by environments. * `api/builds/<id>/cancel` POST Cancel all test jobs of the build (if any) * `api/builds/<id>/tests` GET Returns list of Test objects belonging to this build. List is paginated * `api/builds/<id>/failures_with_confidence` GET List of failing tests with confidence scores. For each failure SQUAD will look back N builds, where N is defined in project settings. List is paginated. * releases_only - when active, look back only on builds with is_release=True * `api/builds/<id>/metrics` GET Returns list of Metric objects belonging to this build. List is paginated * `api/builds/<id>/email` GET This method produces the body of email notification for the build. By default it uses the project settings for HTML and template. These settings can be overwritten by using GET parameters: * output - sets the output format (text/plan, text/html) * template - sets the template used (id of existing template or "default" for default SQUAD templates) * force - force email report re-generation even if there is existing one cached * `api/builds/<id>/report` GET, POST Similar to 'email' but asynchronous * `api/builds/<id>/callbacks` GET, POST List available callbacks for this build or create one via POST * `api/builds/<id>/compare` GET Compare this build against a target one and report regressions/fixes. <br /> The required args are: <br /> - target: target build id <br /> - target_project: target build project id <br /> Optional args are: <br /> - by: it can be "metrics" or "tests" (default). Please note that <br /> comparing it by metrics will return a list of metrics that regressed <br /> or improved (fixes) and that will be decided upon adding metric thresholds <br /> in &lt;group&gt;/&lt;project&gt;/settings/thresholds. <br /> <br /> - force: Use "force=true" in order to force comparing builds that aren't finished yet. <br /> """ queryset = Build.objects.order_by('-datetime').all() project_lookup_key = 'project__in' serializer_class = BuildSerializer filterset_fields = ('version', 'project') # TODO: remove when django-filters 1.x is not supported anymore filter_fields = filterset_fields filterset_class = BuildFilter # TODO: remove when django-filters 1.x is not supported anymore filter_class = filterset_class search_fields = ('version',) ordering_fields = ('id', 'version', 'created_at', 'datetime') def get_queryset(self): # Squeeze a few ms from this query if user wants less fields fields = self.request.query_params.get('fields') queryset = super().get_queryset() if fields: fields = fields.split(',') basic_fields = ['project', 'version', 'created_at', 'datetime', 'patch_source', 'patch_baseline', 'patch_id', 'keep_data'] for field in basic_fields: if field not in fields: queryset = queryset.defer(field) if 'finished' in fields: queryset = queryset.prefetch_related('status') else: queryset = queryset.prefetch_related('status') return queryset @action(detail=True, methods=['get'], suffix='metadata') def metadata(self, request, pk=None): build = self.get_object() return Response(build.metadata) @action(detail=True, methods=['get'], suffix='metadata_by_testrun') def metadata_by_testrun(self, request, pk=None): build = self.get_object() return Response(build.metadata_by_testrun) def __enrich_status_details__(self, request, queryset): enriched_details = {} for tr in queryset: try: s = tr.status.all()[0] except IndexError: s = None if s: if tr.environment.name not in enriched_details.keys(): enriched_details[tr.environment.name] = {'testruns': 0, 'tests_total': 0, 'tests_pass': 0, 'tests_fail': 0, 'tests_xfail': 0, 'tests_skip': 0} enriched_details[tr.environment.name]['testruns'] += 1 enriched_details[tr.environment.name]['tests_total'] += s.tests_pass + \ s.tests_fail + s.tests_xfail + s.tests_skip enriched_details[tr.environment.name]['tests_pass'] += s.tests_pass enriched_details[tr.environment.name]['tests_fail'] += s.tests_fail enriched_details[tr.environment.name]['tests_xfail'] += s.tests_xfail enriched_details[tr.environment.name]['tests_skip'] += s.tests_skip return enriched_details @action(detail=True, methods=['get'], suffix='status') def status(self, request, pk=None): try: build = self.get_object() qs = build.test_runs.prefetch_related('environment', Prefetch( "status", queryset=Status.objects.filter(suite=None))) enriched_details = self.__enrich_status_details__(request, qs) serializer = ProjectStatusSerializer(build.status, many=False, context={ 'request': request, 'enriched_details': enriched_details}) return Response(serializer.data) except ProjectStatus.DoesNotExist: raise NotFound() @action(detail=True, methods=['get'], suffix='failures_with_confidence') def failures_with_confidence(self, request, pk=None): build = self.get_object() failures = build.tests.filter( result=False, ).exclude( has_known_issues=True, ).order_by( 'id', 'metadata__suite', 'metadata__name', 'environment__slug', ).distinct() page = self.paginate_queryset(failures) releases_only = request.GET.get("releases_only") fwc = failures_with_confidence( build.project, build, page, releases_only=releases_only) serializer = FailuresWithConfidenceSerializer( fwc, many=True, context={'request': request}) return self.get_paginated_response(serializer.data) @action(detail=True, methods=['get'], suffix='test runs') def testruns(self, request, pk=None): testruns = self.get_object().test_runs.prefetch_related( Prefetch("status", queryset=Status.objects.filter(suite=None)) ).order_by("-id") page = self.paginate_queryset(testruns) serializer = TestRunSerializer( page, many=True, context={'request': request}) return self.get_paginated_response(serializer.data) @action(detail=True, methods=['get'], suffix='test jobs') def testjobs(self, request, pk=None): testjobs = self.get_object().test_jobs.prefetch_related('backend').order_by('-id') page = self.paginate_queryset(testjobs) serializer = TestJobSerializer( page, many=True, context={'request': request}) return self.get_paginated_response(serializer.data) @action(detail=True, methods=['get'], suffix='test jobs summary') def testjobs_summary(self, request, pk=None): per_environment = request.query_params.get("per_environment", None) summary = self.get_object().test_jobs_summary(per_environment is not None) return Response({'results': summary}) @action(detail=True, methods=['post'], suffix='cancel') def cancel(self, request, pk=None): to_cancel = 0 for testjob in self.get_object().test_jobs.filter(~Q(job_status='Canceled'), submitted=True, fetched=False): cancel.apply_async(args=[testjob.id]) to_cancel += 1 log_change(request, self.get_object(), "Build canceled") return Response({"status": "canceling %d jobs" % to_cancel, "count": to_cancel}) def __return_delayed_report(self, request, wait=False): force = request.query_params.get("force", False) output_format = request.query_params.get("output", "text/plain") template_id = request.query_params.get("template", None) baseline_id = request.query_params.get("baseline", None) email_recipient = request.query_params.get("email_recipient", None) callback = request.query_params.get("callback", None) callback_token = request.query_params.get("callback_token", None) # keep the cached reports for 1 day by default data_retention_days = request.query_params.get("keep", 1) if request.method == "POST": output_format = request.data.get("output", "text/plain") template_id = request.data.get("template", None) baseline_id = request.data.get("baseline", None) email_recipient = request.data.get("email_recipient", None) callback = request.data.get("callback", None) callback_token = request.data.get("callback_token", None) # keep the cached reports for 1 day by default data_retention_days = request.data.get("keep", 1) template = None if template_id != "default": template = self.get_object().project.custom_email_template if template_id is not None: try: template = EmailTemplate.objects.get(pk=template_id) except EmailTemplate.DoesNotExist: pass baseline = None report_kwargs = { "baseline": baseline, "template": template, "output_format": output_format, "email_recipient": email_recipient, "callback": callback, "callback_token": callback_token, "data_retention_days": data_retention_days } if baseline_id is not None: baseline_ok = False try: previous_build = Build.objects.get(pk=baseline_id) report_kwargs["baseline"] = previous_build.status baseline_ok = True except Build.DoesNotExist: data = {"message": "Baseline build %s does not exist" % baseline_id} except ProjectStatus.DoesNotExist: data = {"message": "Build %s has no status" % baseline_id} if not baseline_ok: report_kwargs.update({"build": self.get_object()}) return update_delayed_report(None, data, status.HTTP_400_BAD_REQUEST, **report_kwargs) if force: delayed_report = self.get_object().delayed_reports.create(**report_kwargs) created = True log_addition(request, delayed_report, "Force create report") else: try: delayed_report, created = self.get_object( ).delayed_reports.get_or_create(**report_kwargs) if created: log_addition(request, delayed_report, "Create report") else: log_change(request, delayed_report, "Update report") except core_exceptions.MultipleObjectsReturned: delayed_report = self.get_object().delayed_reports.last() created = False if created: if wait: delayed_report = prepare_report(delayed_report.pk) else: prepare_report.delay(delayed_report.pk) return delayed_report @action(detail=True, methods=['get'], suffix='email') def email(self, request, pk=None): """ This method produces the body of email notification for the build. By default it uses the project settings for HTML and template. These settings can be overwritten by using GET parameters: * output - sets the output format (text/plan, text/html) * template - sets the template used (id of existing template or "default" for default SQUAD templates) * force - force email report re-generation even if there is existing one cached """ delayed_report = self.__return_delayed_report(request, wait=True) if delayed_report.status_code != status.HTTP_200_OK: return Response(yaml.safe_load(delayed_report.error_message or ''), delayed_report.status_code) if delayed_report.output_format == "text/html" and delayed_report.output_html: return HttpResponse(delayed_report.output_html, content_type=delayed_report.output_format) return HttpResponse(delayed_report.output_text, content_type=delayed_report.output_format) @action(detail=True, methods=['get', 'post'], suffix='report', permission_classes=[AllowAny]) def report(self, request, pk=None): delayed_report = self.__return_delayed_report(request) data = {"message": "OK", "url": rest_reverse( 'delayedreport-detail', args=[delayed_report.pk], request=request)} return Response(data, status=status.HTTP_202_ACCEPTED) @action(detail=True, methods=['get', 'post'], suffix='callbacks') def callbacks(self, request, pk=None): build = self.get_object() if request.method == 'GET': callbacks = build.callbacks.order_by('id') serializer = CallbackSerializer( callbacks, many=True, context={'request': request}) data = {'results': serializer.data} return Response(data, status=status.HTTP_202_ACCEPTED) else: try: callback = create_callback(build, request) if callback is None: raise ValidationError('url is required.') return Response({'message': 'OK'}, status=status.HTTP_202_ACCEPTED) except (ValidationError, IntegrityError) as e: message = "" if hasattr(e, "messages"): message = ', '.join(e.messages) else: message = str(e) return Response({'message': message}, status=status.HTTP_400_BAD_REQUEST) @action(detail=True, methods=['get'], suffix='compare') def compare(self, request, pk=None): by = request.GET.get('by', 'tests') target_id = request.GET.get('target', None) force_unfinished = request.GET.get('force', None) if target_id is None: raise serializers.ValidationError( "Invalid args provided. 'target' build id must NOT be empty") if by not in ['tests', 'metrics']: raise serializers.ValidationError( "Invalid args provided. 'by' should be either 'tests' or 'metrics'") baseline = self.get_object() try: int(target_id) target = Build.objects.get(pk=target_id) if force_unfinished is None and (not baseline.status.finished or not target.status.finished): raise serializers.ValidationError( "Cannot report regressions/fixes on non-finished builds") except Build.DoesNotExist: raise NotFound() except ValueError: raise serializers.ValidationError( "target build id must be integer") if by == 'tests': comparison = TestComparison( baseline, target, regressions_and_fixes_only=True) else: comparison = MetricComparison( baseline, target, regressions_and_fixes_only=True) serializer = BuildsComparisonSerializer(comparison) return Response(serializer.data)
class BuildViewSet(NestedViewSetMixin, ModelViewSet): ''' List of all builds in the system. Only builds belonging to public projects and to projects you have access to are available. Additional actions: * `api/builds/<id>/metadata` GET Build metadata list * `api/builds/<id>/metadata_by_testrun` GET Build metadata list now separated by testrun * `api/builds/<id>/status` GET Build status and cached test/metric totals * `api/builds/<id>/testruns` GET List of test runs in the build * `api/builds/<id>/testjobs` GET List of test jobs in the build (if any) * `api/builds/<id>/testjobs_summary` GET List of test jobs in the build summarized by job_status. If `per_environment` is specified in the query string, the summary will be split by environments. * `api/builds/<id>/cancel` POST Cancel all test jobs of the build (if any) * `api/builds/<id>/tests` GET Returns list of Test objects belonging to this build. List is paginated * `api/builds/<id>/failures_with_confidence` GET List of failing tests with confidence scores. For each failure SQUAD will look back N builds, where N is defined in project settings. List is paginated. * releases_only - when active, look back only on builds with is_release=True * `api/builds/<id>/metrics` GET Returns list of Metric objects belonging to this build. List is paginated * `api/builds/<id>/email` GET This method produces the body of email notification for the build. By default it uses the project settings for HTML and template. These settings can be overwritten by using GET parameters: * output - sets the output format (text/plan, text/html) * template - sets the template used (id of existing template or "default" for default SQUAD templates) * force - force email report re-generation even if there is existing one cached * `api/builds/<id>/report` GET, POST Similar to 'email' but asynchronous * `api/builds/<id>/callbacks` GET, POST List available callbacks for this build or create one via POST * `api/builds/<id>/compare` GET Compare this build against a target one and report regressions/fixes. <br /> The required args are: <br /> - target: target build id <br /> - target_project: target build project id <br /> Optional args are: <br /> - by: it can be "metrics" or "tests" (default). Please note that <br /> comparing it by metrics will return a list of metrics that regressed <br /> or improved (fixes) and that will be decided upon adding metric thresholds <br /> in &lt;group&gt;/&lt;project&gt;/settings/thresholds. <br /> <br /> - force: Use "force=true" in order to force comparing builds that aren't finished yet. <br /> ''' def get_queryset(self): pass @action(detail=True, methods=['get'], suffix='metadata') def metadata(self, request, pk=None): pass @action(detail=True, methods=['get'], suffix='metadata_by_testrun') def metadata_by_testrun(self, request, pk=None): pass def __enrich_status_details__(self, request, queryset): pass @action(detail=True, methods=['get'], suffix='status') def status(self, request, pk=None): pass @action(detail=True, methods=['get'], suffix='failures_with_confidence') def failures_with_confidence(self, request, pk=None): pass @action(detail=True, methods=['get'], suffix='test runs') def testruns(self, request, pk=None): pass @action(detail=True, methods=['get'], suffix='test jobs') def testjobs(self, request, pk=None): pass @action(detail=True, methods=['get'], suffix='test jobs summary') def testjobs_summary(self, request, pk=None): pass @action(detail=True, methods=['post'], suffix='cancel') def cancel(self, request, pk=None): pass def __return_delayed_report(self, request, wait=False): pass @action(detail=True, methods=['get'], suffix='email') def email(self, request, pk=None): ''' This method produces the body of email notification for the build. By default it uses the project settings for HTML and template. These settings can be overwritten by using GET parameters: * output - sets the output format (text/plan, text/html) * template - sets the template used (id of existing template or "default" for default SQUAD templates) * force - force email report re-generation even if there is existing one cached ''' pass @action(detail=True, methods=['get', 'post'], suffix='report', permission_classes=[AllowAny]) def report(self, request, pk=None): pass @action(detail=True, methods=['get', 'post'], suffix='callbacks') def callbacks(self, request, pk=None): pass @action(detail=True, methods=['get'], suffix='compare') def compare(self, request, pk=None): pass
28
2
16
1
14
1
3
0.29
2
17
12
0
15
0
15
17
365
66
233
99
205
68
193
86
177
14
2
3
50
145,504
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.CallbackSerializer.Meta
class Meta: model = Callback exclude = ('headers', 'object_reference_type', 'object_reference_id')
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
145,505
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.DelayedReportFilter.Meta
class Meta: model = DelayedReport fields = { "output_format": ['exact', 'in', 'startswith', 'contains', 'icontains'], "id": ['exact', 'in'], "template": ['exact', 'in'], "email_recipient": ['exact', 'in', 'startswith', 'contains', 'icontains'], "email_recipient_notified": ['exact'], "callback": ['exact', 'in', 'startswith', 'contains', 'icontains'], "callback_notified": ['exact'], "data_retention_days": ['exact', 'in'], "output_text": ['exact', 'in', 'startswith', 'contains', 'icontains'], "output_html": ['exact', 'in', 'startswith', 'contains', 'icontains'], "error_message": ['exact', 'in', 'startswith', 'contains', 'icontains'], "status_code": ['exact', 'in'], "created_at": ['exact', 'gt', 'lt'], }
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
17
0
17
3
16
0
3
3
2
0
0
0
0
145,506
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.DelayedReportSerializer.Meta
class Meta: model = DelayedReport exclude = ('callback_token',)
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
145,507
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.EmailTemplateSerializer.Meta
class Meta: model = EmailTemplate fields = '__all__'
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
145,508
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.EnvironmentFilter.Meta
class Meta: model = Environment fields = {'name': ['exact', 'in', 'startswith', 'contains', 'icontains'], 'slug': ['exact', 'in', 'startswith', 'contains', 'icontains'], 'id': ['exact', 'in']}
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
5
0
5
3
4
0
3
3
2
0
0
0
0
145,509
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.EnvironmentSerializer.Meta
class Meta: model = Environment fields = '__all__'
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
145,510
Linaro/squad
Linaro_squad/test/core/test_import_data.py
test.core.test_import_data.TestMissingMetadata
class TestMissingMetadata(TestCase): def test_missing_metadata(self): self.importer = Command() self.importer.silent = True d = os.path.join(os.path.dirname(__file__), 'test_import_data_missing_metadata') call_command('import_data', '--silent', 'foo/bar', d) self.assertEqual(0, Build.objects.count())
class TestMissingMetadata(TestCase): def test_missing_metadata(self): pass
2
0
6
0
6
0
1
0
1
2
2
0
1
1
1
1
8
1
7
4
5
0
7
4
5
1
1
0
1
145,511
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.FailuresWithConfidenceSerializer.Meta
class Meta: model = Test exclude = ( 'known_issues', 'has_known_issues', 'result', 'url', )
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
8
0
8
3
7
0
3
3
2
0
0
0
0
145,512
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.GroupSerializer.Meta
class Meta: model = Group exclude = ('members',)
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
145,513
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.KnownIssueFilter.Meta
class Meta: model = KnownIssue fields = {'title': ['exact', 'in', 'startswith', 'contains', 'icontains'], 'test_name': ['exact', 'in', 'startswith', 'contains', 'icontains'], 'url': ['exact', 'in', 'startswith', 'contains', 'icontains'], 'active': ['exact', 'in'], 'intermittent': ['exact', 'in'], 'id': ['exact', 'in']}
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
8
0
8
3
7
0
3
3
2
0
0
0
0
145,514
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.KnownIssueSerializer.Meta
class Meta: model = KnownIssue fields = '__all__'
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
145,515
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.MetricFilter.Meta
class Meta: model = Metric fields = {'result': ['exact', 'in'], 'test_run': ['exact', 'in'], 'is_outlier': ['exact', 'in'], 'suite': ['exact', 'in'], 'unit': ['exact', 'in']}
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
7
0
7
3
6
0
3
3
2
0
0
0
0
145,516
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.MetricSerializer.Meta
class Meta: model = Metric exclude = ['measurements']
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
145,517
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.MetricThresholdFilter.Meta
class Meta: model = MetricThreshold fields = {'name': ['exact', 'in', 'startswith', 'contains', 'icontains'], 'id': ['exact', 'in']}
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
4
0
4
3
3
0
3
3
2
0
0
0
0
145,518
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.MetricThresholdSerializer.Meta
class Meta: model = MetricThreshold fields = '__all__'
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
145,519
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.PatchSourceSerializer.Meta
class Meta: model = PatchSource fields = '__all__' extra_kwargs = { 'token': {'write_only': True}, 'username': {'write_only': True}, '_password': {'write_only': True}, }
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
8
0
8
4
7
0
4
4
3
0
0
0
0
145,520
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.ProjectFilter.Meta
class Meta: model = Project fields = {'name': ['exact', 'in', 'startswith', 'contains', 'icontains'], 'slug': ['exact', 'in', 'startswith', 'contains', 'icontains'], 'datetime': ['exact', 'gt', 'gte', 'lt', 'lte'], 'id': ['exact', 'in']}
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
6
0
6
3
5
0
3
3
2
0
0
0
0
145,521
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.ProjectSerializer.Meta
class Meta: model = Project fields = '__all__'
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
145,522
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.ProjectStatusFilter.Meta
class Meta: model = ProjectStatus fields = {'finished': ['exact', 'in'], 'approved': ['exact', 'in'], 'notified': ['exact', 'in'], 'has_metrics': ['exact', 'in'], 'last_updated': ['gt', 'lt']}
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
7
0
7
3
6
0
3
3
2
0
0
0
0
145,523
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.ProjectStatusSerializer.Meta
class Meta: model = ProjectStatus fields = ('last_updated', 'finished', 'notified', 'notified_on_timeout', 'approved', 'tests_pass', 'tests_fail', 'tests_skip', 'tests_xfail', 'tests_total', 'pass_percentage', 'fail_percentage', 'skip_percentage', 'test_runs_total', 'test_runs_completed', 'test_runs_incomplete', 'has_metrics', 'has_tests', 'metrics_summary', 'build', 'baseline', 'created_at', 'regressions', 'fixes', 'metric_regressions', 'metric_fixes')
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
28
0
28
3
27
0
3
3
2
0
0
0
0
145,524
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.ProjectViewSet
class ProjectViewSet(viewsets.ModelViewSet): """ List of projects. Includes public projects and projects that the current user has access to. Additional actions: * `api/projects/<id>/builds` GET List of builds for the current project. * `api/projects/<id>/suites` GET List of test suite names available in this project * `api/projects/<id>/tests` GET List of test names available in this project * `api/projects/<id>/test_results` GET Test results of the last build * `api/projects/<id>/basic_settings` GET List of the basic settings for this project * `api/projects/<id>/subscribe` POST Subscribe to project notifications * `api/projects/<id>/unsubscribe` POST Unsubscribe from project notifications * `api/projects/<id>/compare_builds` POST/GET Compares two builds and report regressions/fixes. <br /> The required args are: <br /> - to_compare: target build id <br /> - baseline: baseline build id <br /> Optional args are: <br /> - by: it can be "metrics" or "tests" (default). Please note that <br /> comparing it by metrics will return a list of metrics that regressed <br /> or improved (fixes) and that will be decided upon adding metric thresholds <br /> in &lt;group&gt;/&lt;project&gt;/settings/thresholds. <br /> <br /> - force: Use "force=true" in order to force comparing builds that aren't finished yet. <br /> The comparison will compare to_compare against baseline. """ queryset = Project.objects serializer_class = ProjectSerializer filterset_fields = ( 'group', 'slug', 'name', 'is_public', 'html_mail', 'custom_email_template', 'moderate_notifications', ) # TODO: remove when django-filters 1.x is not supported anymore filter_fields = filterset_fields filter_backends = (ComplexFilterBackend, ) filterset_class = ProjectFilter # TODO: remove when django-filters 1.x is not supported anymore filter_class = filterset_class search_fields = ('slug', 'name',) ordering_fields = ('slug', 'name',) def get_queryset(self): return self.queryset.accessible_to(self.request.user).prefetch_related('group') @action(detail=True, methods=['get'], suffix='suites') def suites(self, request, pk=None): """ List of test suite names available in this project """ suites_names = self.get_object().suites.values_list('slug') suites_metadata = SuiteMetadata.objects.filter( kind='suite', suite__in=suites_names) page = self.paginate_queryset(suites_metadata) serializer = SuiteMetadataSerializer( page, many=True, context={'request': request}) return self.get_paginated_response(serializer.data) @action(detail=True, methods=['get'], suffix='tests') def tests(self, request, pk=None): """ List of test names available in this project """ suite_name = request.query_params.get("suite_name", None) if suite_name is None: suites_names = self.get_object().suites.values_list('slug') else: suites_names = [suite_name] suites_metadata = SuiteMetadata.objects.filter( kind='test', suite__in=suites_names) page = self.paginate_queryset(suites_metadata) serializer = SuiteMetadataSerializer( page, many=True, context={'request': request}) return self.get_paginated_response(serializer.data) @action(detail=True, methods=['get'], suffix='test_results') def test_results(self, request, pk=None): test_full_name = request.query_params.get('test_name', None) if test_full_name is None: raise serializers.ValidationError( _('"test_name" parameter is mandatory. Ex: suitename/testname')) suite_slug, test_name = parse_name(test_full_name) try: metadata = SuiteMetadata.objects.get( kind='test', suite=suite_slug, name=test_name) except SuiteMetadata.DoesNotExist: raise serializers.ValidationError( _('There is no test named "%s/%s"' % (suite_slug, test_name))) project = self.get_object() builds = project.builds.prefetch_related( 'test_runs__environment', 'project__group', 'status').order_by('-datetime') environments = project.environments.order_by('name', 'slug') try: suite = project.suites.get(slug=suite_slug) except Suite.DoesNotExist: return Response() page = self.paginate_queryset(builds) serializer = LatestTestResultsSerializer( page, many=True, context={'request': request, 'suite': suite, 'metadata': metadata, 'environments': environments} ) return Response(serializer.data) @action(detail=True, methods=['get'], suffix='basic_settings') def basic_settings(self, request, pk=None): """ List of the basic settings for this project """ project = self.get_object() return Response({ "build_confidence_count": project.build_confidence_count, "build_confidence_threshold": project.build_confidence_threshold, }, status=status.HTTP_200_OK) @action(detail=True, methods=['post'], suffix='subscribe') def subscribe(self, request, pk=None): subscriber_email = request.data.get("email", None) if subscriber_email is None: raise serializers.ValidationError("'email' field is mandatory.") try: validate_email(subscriber_email) except core_exceptions.ValidationError: raise serializers.ValidationError("Invalid 'email' field value.") user = User.objects.filter(email=subscriber_email).first() if user is None: sub, created = Subscription.objects.get_or_create( email=subscriber_email, project=self.get_object()) if created: log_addition(request, sub, "Subscription created") else: sub, created = Subscription.objects.get_or_create( user=user, project=self.get_object()) if created: log_addition(request, sub, "Subscription created") data = {"email": subscriber_email} return Response(data, status=status.HTTP_201_CREATED) @action(detail=True, methods=['post'], suffix='unsubscribe') def unsubscribe(self, request, pk=None): subscriber_email = request.data.get("email", None) if subscriber_email is None: raise serializers.ValidationError("'email' field is mandatory.") try: validate_email(subscriber_email) except core_exceptions.ValidationError: raise serializers.ValidationError("Invalid 'email' field value.") subs = self.get_object().subscriptions.filter( Q(email=subscriber_email) | Q(user__email=subscriber_email)) for sub in subs: log_deletion(request, sub, "Subscription deleted") subs.delete() data = {"email": subscriber_email} return Response(data, status=status.HTTP_200_OK) @action(detail=True, methods=['get', 'post'], suffix='compare_builds') def compare_builds(self, request, pk=None): builds_to_compare = {f: request.GET.get(f, request.POST.get(f, None)) for f in [ 'baseline', 'to_compare']} force_unfinished = request.GET.get('force', None) if all(builds_to_compare.values()): try: int(builds_to_compare['baseline']) int(builds_to_compare['to_compare']) baseline = self.get_object().builds.get( pk=builds_to_compare['baseline']) to_compare = self.get_object().builds.get( pk=builds_to_compare['to_compare']) if force_unfinished is None and (not baseline.status.finished or not to_compare.status.finished): raise serializers.ValidationError( "Cannot report regressions/fixes on non-finished builds") except Build.DoesNotExist: raise NotFound() except ValueError: raise serializers.ValidationError("builds IDs must be integer") else: raise serializers.ValidationError( "Invalid args provided. 'baseline' and 'to_compare' build ids must NOT be empty") by = request.GET.get('by', 'tests') if by not in ['tests', 'metrics']: raise serializers.ValidationError( "Invalid args provided. 'by' should be either 'tests' or 'metrics'") if baseline and to_compare: if by == 'tests': comparison = TestComparison( baseline, to_compare, regressions_and_fixes_only=True) else: comparison = MetricComparison( baseline, to_compare, regressions_and_fixes_only=True) serializer = BuildsComparisonSerializer(comparison) return Response(serializer.data)
class ProjectViewSet(viewsets.ModelViewSet): ''' List of projects. Includes public projects and projects that the current user has access to. Additional actions: * `api/projects/<id>/builds` GET List of builds for the current project. * `api/projects/<id>/suites` GET List of test suite names available in this project * `api/projects/<id>/tests` GET List of test names available in this project * `api/projects/<id>/test_results` GET Test results of the last build * `api/projects/<id>/basic_settings` GET List of the basic settings for this project * `api/projects/<id>/subscribe` POST Subscribe to project notifications * `api/projects/<id>/unsubscribe` POST Unsubscribe from project notifications * `api/projects/<id>/compare_builds` POST/GET Compares two builds and report regressions/fixes. <br /> The required args are: <br /> - to_compare: target build id <br /> - baseline: baseline build id <br /> Optional args are: <br /> - by: it can be "metrics" or "tests" (default). Please note that <br /> comparing it by metrics will return a list of metrics that regressed <br /> or improved (fixes) and that will be decided upon adding metric thresholds <br /> in &lt;group&gt;/&lt;project&gt;/settings/thresholds. <br /> <br /> - force: Use "force=true" in order to force comparing builds that aren't finished yet. <br /> The comparison will compare to_compare against baseline. ''' def get_queryset(self): pass @action(detail=True, methods=['get'], suffix='suites') def suites(self, request, pk=None): ''' List of test suite names available in this project ''' pass @action(detail=True, methods=['get'], suffix='tests') def tests(self, request, pk=None): ''' List of test names available in this project ''' pass @action(detail=True, methods=['get'], suffix='test_results') def test_results(self, request, pk=None): pass @action(detail=True, methods=['get'], suffix='basic_settings') def basic_settings(self, request, pk=None): ''' List of the basic settings for this project ''' pass @action(detail=True, methods=['post'], suffix='subscribe') def subscribe(self, request, pk=None): pass @action(detail=True, methods=['post'], suffix='unsubscribe') def unsubscribe(self, request, pk=None): pass @action(detail=True, methods=['get', 'post'], suffix='compare_builds') def compare_builds(self, request, pk=None): pass
16
4
16
1
13
1
3
0.31
1
11
9
0
8
0
8
8
208
34
134
59
118
42
106
52
97
8
1
3
27
145,525
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/api/rest.py
squad.api.rest.GroupFilter.Meta
class Meta: model = Group fields = {'name': ['exact', 'in', 'startswith', 'contains', 'icontains'], 'slug': ['exact', 'in', 'startswith', 'contains', 'icontains'], 'id': ['exact', 'in']}
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
5
0
5
3
4
0
3
3
2
0
0
0
0
145,526
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/test/test_code_quality.py
test.test_code_quality.TestCodeQuality
class TestCodeQuality(TestCase): def test_flake8(self): self.assertEqual(0, subprocess.call('flake8'))
class TestCodeQuality(TestCase): def test_flake8(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
73
3
0
3
2
1
0
3
2
1
1
2
0
1
145,527
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/core/models.py
squad.core.models.Suite.Meta
class Meta: unique_together = ('project', 'slug',)
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
0
0
0
145,528
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/squad/core/models.py
squad.core.models.SuiteVersion.Meta
class Meta: unique_together = ('suite', 'version')
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
0
0
0
145,529
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/test/ci/test_tasks.py
test.ci.test_tasks.SubmitTest
class SubmitTest(TestCase): def setUp(self): group = core_models.Group.objects.create(slug='test') project = group.projects.create(slug='test') backend = models.Backend.objects.create() self.test_job = models.TestJob.objects.create( backend=backend, target=project) @patch('squad.ci.models.Backend.submit') def test_submit(self, submit_method): submit.apply(args=[self.test_job.id]) submit_method.assert_called_with(self.test_job) @patch('squad.ci.models.Backend.submit') def test_submit_fatal_error(self, submit_method): submit_method.side_effect = SubmissionIssue("ERROR") submit.apply(args=[self.test_job.id]) self.test_job.refresh_from_db() self.assertEqual(self.test_job.failure, "ERROR") @patch('squad.ci.tasks.submit.retry') @patch('squad.ci.models.Backend.submit') def test_submit_temporary_error(self, submit_method, retry): exception = TemporarySubmissionIssue("TEMPORARY ERROR") retry.return_value = Retry() submit_method.side_effect = exception with self.assertRaises(Retry): submit.apply(args=[self.test_job.id]) retry.assert_called_with(exc=exception, countdown=3600) self.test_job.refresh_from_db() self.assertEqual(self.test_job.failure, "TEMPORARY ERROR") @patch('squad.ci.models.Backend.submit') def test_avoid_multiple_submissions(self, submit_method): self.test_job.submitted = True self.test_job.save() submit.apply(args=[self.test_job.id]) self.assertFalse(submit_method.called) @patch('squad.ci.tasks.submit.retry') @patch('squad.ci.models.Backend.submit') def test_submit_overwrite_failure_after_success(self, submit_method, retry): exception = TemporarySubmissionIssue("TEMPORARY ERROR") retry.return_value = Retry() submit_method.side_effect = exception with self.assertRaises(Retry): submit.apply(args=[self.test_job.id]) retry.assert_called_with(exc=exception, countdown=3600) self.test_job.refresh_from_db() self.assertEqual(self.test_job.failure, "TEMPORARY ERROR") submit_method.side_effect = None submit.apply(args=[self.test_job.id]) self.test_job.refresh_from_db() self.assertIsNone(self.test_job.failure)
class SubmitTest(TestCase): def setUp(self): pass @patch('squad.ci.models.Backend.submit') def test_submit(self, submit_method): pass @patch('squad.ci.models.Backend.submit') def test_submit_fatal_error(self, submit_method): pass @patch('squad.ci.tasks.submit.retry') @patch('squad.ci.models.Backend.submit') def test_submit_temporary_error(self, submit_method, retry): pass @patch('squad.ci.models.Backend.submit') def test_avoid_multiple_submissions(self, submit_method): pass @patch('squad.ci.tasks.submit.retry') @patch('squad.ci.models.Backend.submit') def test_submit_overwrite_failure_after_success(self, submit_method, retry): pass
14
0
8
1
7
0
1
0
1
4
4
0
6
1
6
6
61
13
48
18
34
0
41
13
34
1
1
1
6
145,530
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/test/core/test_build.py
test.core.test_build.BuildTest
class BuildTest(TestCase): def setUp(self): self.group = Group.objects.create(slug='mygroup') self.project = self.group.projects.create(slug='myproject') def test_default_ordering(self): now = timezone.now() before = now - relativedelta(hours=1) newer = Build.objects.create( project=self.project, version='1.1', datetime=now) Build.objects.create(project=self.project, version='1.0', datetime=before) self.assertEqual(newer, Build.objects.last()) @patch('squad.core.models.TestSummary') def test_test_summary(self, TestSummary): the_summary = object() TestSummary.return_value = the_summary build = Build.objects.create(project=self.project, version='1.1') summary = build.test_summary TestSummary.assert_called_with(build) self.assertIs(summary, the_summary) def test_metadata_with_different_values_for_the_same_key(self): build = Build.objects.create(project=self.project, version='1.1') env = self.project.environments.create(slug='env') build.test_runs.create( environment=env, metadata_file='{"foo": "bar", "baz": "qux"}') build.test_runs.create( environment=env, metadata_file='{"foo": "bar", "baz": "fox"}') self.assertEqual({"foo": "bar", "baz": ["fox", "qux"]}, build.metadata) def test_metadata_no_common_keys(self): build = Build.objects.create(project=self.project, version='1.1') env = self.project.environments.create(slug='env') build.test_runs.create(environment=env, metadata_file='{"foo": "bar"}') build.test_runs.create(environment=env, metadata_file='{"baz": "qux"}') self.assertEqual({"foo": "bar", "baz": "qux"}, build.metadata) def test_metadata_no_testruns(self): build = Build.objects.create(project=self.project, version='1.1') self.assertEqual({}, build.metadata) def test_metadata_with_testruns_with_empty_metadata(self): build = Build.objects.create(project=self.project, version='1.1') env = self.project.environments.create(slug='env') build.test_runs.create(environment=env) self.assertEqual({}, build.metadata) def test_metadata_list_value(self): build = Build.objects.create(project=self.project, version='1.1') env = self.project.environments.create(slug='env') build.test_runs.create( environment=env, metadata_file='{"foo": "bar", "baz": ["qux"]}') build.test_runs.create( environment=env, metadata_file='{"foo": "bar", "baz": ["qux"]}') self.assertEqual({"foo": "bar", "baz": ["qux"]}, build.metadata) def test_metadata_common_key_with_string_and_list_values(self): build = Build.objects.create(project=self.project, version='1.1') env = self.project.environments.create(slug='env') build.test_runs.create(environment=env, metadata_file='{"foo": "bar"}') build.test_runs.create( environment=env, metadata_file='{"foo": ["bar"]}') self.assertEqual({"foo": [["bar"], "bar"]}, build.metadata) def test_metadata_common_key_with_list_and_string_values(self): build = Build.objects.create(project=self.project, version='1.1') env = self.project.environments.create(slug='env') build.test_runs.create( environment=env, metadata_file='{"foo": ["bar"]}') build.test_runs.create(environment=env, metadata_file='{"foo": "bar"}') self.assertEqual({"foo": [["bar"], "bar"]}, build.metadata) def test_metadata_is_cached(self): build = Build.objects.create(project=self.project, version='1.1') env = self.project.environments.create(slug='env') build.test_runs.create(environment=env, metadata_file='{"foo": "bar"}') metadata1 = build.metadata build.test_runs.create(environment=env, metadata_file='{"foo": "baz"}') metadata2 = build.metadata self.assertEqual(metadata1, metadata2) def test_finished_empty_expected_test_runs(self): env1 = self.project.environments.create( slug='env1', expected_test_runs=None) self.project.environments.create(slug='env2', expected_test_runs=None) build = self.project.builds.create(version='1') build.test_runs.create(environment=env1) finished, _ = build.finished self.assertTrue(finished) def test_finished(self): env1 = self.project.environments.create(slug='env1') env2 = self.project.environments.create(slug='env2') build = self.project.builds.create(version='1') build.test_runs.create(environment=env1) build.test_runs.create(environment=env2) finished, _ = build.finished self.assertTrue(finished) def test_finished_multiple_test_runs(self): env1 = self.project.environments.create(slug='env1') env2 = self.project.environments.create(slug='env2') build = self.project.builds.create(version='1') build.test_runs.create(environment=env1) build.test_runs.create(environment=env2) build.test_runs.create(environment=env2) finished, _ = build.finished self.assertTrue(finished) def test_unfinished_with_expected_test_runs(self): build = self.project.builds.create(version='1') env1 = self.project.environments.create( slug='env1', expected_test_runs=2) build.test_runs.create(environment=env1) finished, _ = build.finished self.assertFalse(finished) def test_finished_with_expected_test_runs(self): build = self.project.builds.create(version='1') env1 = self.project.environments.create( slug='env1', expected_test_runs=2) build.test_runs.create(environment=env1) build.test_runs.create(environment=env1) finished, _ = build.finished self.assertTrue(finished) def test_not_finished_when_test_run_not_completed(self): build = self.project.builds.create(version='1') env1 = self.project.environments.create( slug='env1', expected_test_runs=1) build.test_runs.create(environment=env1, completed=False) finished, _ = build.finished self.assertFalse(finished) @patch('squad.ci.backend.null.Backend.job_url', return_value="http://example.com/123") @patch('squad.ci.backend.null.Backend.fetch') def test_not_finished_with_pending_ci_jobs(self, fetch, job_url): build = self.project.builds.create(version='1') env1 = self.project.environments.create( slug='env1', expected_test_runs=1) backend = Backend.objects.create( name='foobar', implementation_type='null') fetch.return_value = ('OK', True, {}, {'test1': 'pass'}, {}, '...') t1 = TestJob.objects.create( job_id='1', backend=backend, definition='blablabla', target=build.project, target_build=build, environment=env1.slug, submitted=True, fetched=False, ) t1.backend.fetch(t1.id) t2 = TestJob.objects.create( job_id='2', backend=backend, definition='blablabla', target=build.project, target_build=build, environment=env1.slug, submitted=True, fetched=False, ) finished, _ = build.finished self.assertFalse(finished) t2.backend.fetch(t2.id) finished, _ = build.finished self.assertTrue(finished) @patch('squad.ci.backend.null.Backend.job_url', return_value="http://example.com/123") @patch('squad.ci.backend.null.Backend.fetch') def test_not_finished_no_pending_testjobs_but_not_enough_of_them(self, fetch, job_url): build = self.project.builds.create(version='1') env1 = self.project.environments.create( slug='env1', expected_test_runs=2) backend = Backend.objects.create( name='foobar', implementation_type='null') fetch.return_value = ('OK', True, {}, {'test1': 'pass'}, {}, '...') t1 = TestJob.objects.create( job_id='1', backend=backend, definition='blablabla', target=build.project, target_build=build, environment=env1.slug, submitted=True, fetched=False, ) t1.backend.fetch(t1.id) # expect 2, only 1 received finished, _ = build.finished self.assertFalse(finished) def test_not_finished_when_no_jobs_or_testruns(self): build = self.project.builds.create(version='1') finished, _ = build.finished self.assertFalse(finished) def test_get_or_create_with_version_twice(self): self.project.builds.get_or_create(version='1.0-rc1') self.project.builds.get_or_create(version='1.0-rc1') def test_test_suites_by_environment(self): build = Build.objects.create(project=self.project, version='1.1') env1 = self.project.environments.create(slug='env1') env2 = self.project.environments.create(slug='env2') foo = self.project.suites.create(slug="foo") bar = self.project.suites.create(slug="bar") testrun1 = build.test_runs.create(environment=env1) testrun2 = build.test_runs.create(environment=env2) foo_test1_metadata, _ = SuiteMetadata.objects.get_or_create( suite=foo.slug, name='test1', kind='test') foo_pla_metadata, _ = SuiteMetadata.objects.get_or_create( suite=foo.slug, name='pla', kind='test') bar_test1_metadata, _ = SuiteMetadata.objects.get_or_create( suite=bar.slug, name='test1', kind='test') testrun1.tests.create(build=testrun1.build, environment=testrun1.environment, suite=foo, metadata=foo_test1_metadata, result=True) testrun1.tests.create(build=testrun1.build, environment=testrun1.environment, suite=foo, metadata=foo_pla_metadata, result=True) testrun1.tests.create(build=testrun1.build, environment=testrun1.environment, suite=bar, metadata=bar_test1_metadata, result=False) testrun2.tests.create(build=testrun2.build, environment=testrun2.environment, suite=foo, metadata=foo_test1_metadata, result=True) # make sure 'xfail' is covered by test issue = KnownIssue.objects.create( title='pla is broken', test_name='qux') xfail_test = testrun2.tests.create( build=testrun2.build, environment=testrun2.environment, suite=foo, metadata=foo_pla_metadata, result=False) xfail_test.known_issues.add(issue) test_suites = build.test_suites_by_environment self.assertEqual([env1, env2], list(test_suites.keys())) self.assertEqual(["bar", "foo"], [ s[0].slug for s in test_suites[env1]]) self.assertEqual(["foo"], [s[0].slug for s in test_suites[env2]]) def test_testjobs_summary(self): build = self.project.builds.create(version='build-testjobs') backend = Backend.objects.create( name='foobar', implementation_type='null') for env in ['env1', 'env2']: for status in [None, 'Complete', 'Incomplete', 'Canceled', 'Running']: build.test_jobs.create( backend=backend, target=build.project, environment=env, job_status=status, submitted=status is not None, fetched=status in ['Complete', 'Incomplete'], ) summary = build.test_jobs_summary() expected_summary = {None: 2, 'Complete': 2, 'Incomplete': 2, 'Canceled': 2, 'Running': 2} self.assertEqual(expected_summary, summary) summary = build.test_jobs_summary(per_environment=True) expected_summary = { 'env1': {None: 1, 'Complete': 1, 'Incomplete': 1, 'Canceled': 1, 'Running': 1}, 'env2': {None: 1, 'Complete': 1, 'Incomplete': 1, 'Canceled': 1, 'Running': 1}, } self.assertEqual(expected_summary, summary) def test_important_metadata_default(self): project = Project() build = Build(project=project) with patch('squad.core.models.Build.metadata', {'foo': 'bar'}): self.assertEqual({'foo': 'bar'}, build.important_metadata) self.assertEqual(False, build.has_extra_metadata) def test_important_metadata(self): project = Project(important_metadata_keys='foo1\nfoo2\nmissingkey\n') build = Build(project=project) m = { 'foo1': 'bar1', 'foo2': 'bar2', 'foo3': 'bar3', } with patch('squad.core.models.Build.metadata', m): self.assertEqual({'foo1': 'bar1', 'foo2': 'bar2'}, build.important_metadata) self.assertEqual(True, build.has_extra_metadata) def test_important_metadata_keys_with_spaces(self): project = Project(important_metadata_keys='my key\n') build = Build(project=project) m = { 'my key': 'my value', } with patch('squad.core.models.Build.metadata', m): self.assertEqual({'my key': 'my value'}, build.important_metadata) def test_important_metadata_order(self): project = Project(important_metadata_keys='key2\nkey1\nkey3\n') build = Build(project=project) m = {'key3': 'val3', 'key1': 'val1', 'key2': 'val2'} with patch('squad.core.models.Build.metadata', m): self.assertEqual({'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}, build.important_metadata) self.assertEqual(['key2', 'key1', 'key3'], list( build.important_metadata.keys())) def test_metadata(self): build = Build.objects.create( project=self.project, version='build-metadata') env1 = self.project.environments.create(slug='env1') build.test_runs.create( environment=env1, metadata_file='{"key1": "val1"}') build.test_runs.create( environment=env1, metadata_file='{"key2": "val2"}') self.assertEqual({'key1': 'val1', 'key2': 'val2'}, build.metadata) def test_metadata_by_testrun(self): build = Build.objects.create( project=self.project, version='build-metadata') env1 = self.project.environments.create(slug='env1') testrun1 = build.test_runs.create( environment=env1, metadata_file='{"key1": "val1"}') testrun2 = build.test_runs.create( environment=env1, metadata_file='{"key2": "val2"}') self.assertEqual({ testrun1.id: {'key1': 'val1'}, testrun2.id: {'key2': 'val2'} }, build.metadata_by_testrun) def test_create_project_status(self): build = Build.objects.create(project=self.project, version='1.0') self.assertIsNotNone(build.status)
class BuildTest(TestCase): def setUp(self): pass def test_default_ordering(self): pass @patch('squad.core.models.TestSummary') def test_test_summary(self, TestSummary): pass def test_metadata_with_different_values_for_the_same_key(self): pass def test_metadata_no_common_keys(self): pass def test_metadata_no_testruns(self): pass def test_metadata_with_testruns_with_empty_metadata(self): pass def test_metadata_list_value(self): pass def test_metadata_common_key_with_string_and_list_values(self): pass def test_metadata_common_key_with_list_and_string_values(self): pass def test_metadata_is_cached(self): pass def test_finished_empty_expected_test_runs(self): pass def test_finished_empty_expected_test_runs(self): pass def test_finished_multiple_test_runs(self): pass def test_unfinished_with_expected_test_runs(self): pass def test_finished_with_expected_test_runs(self): pass def test_not_finished_when_test_run_not_completed(self): pass @patch('squad.ci.backend.null.Backend.job_url', return_value="http://example.com/123") @patch('squad.ci.backend.null.Backend.fetch') def test_not_finished_with_pending_ci_jobs(self, fetch, job_url): pass @patch('squad.ci.backend.null.Backend.job_url', return_value="http://example.com/123") @patch('squad.ci.backend.null.Backend.fetch') def test_not_finished_no_pending_testjobs_but_not_enough_of_them(self, fetch, job_url): pass def test_not_finished_when_no_jobs_or_testruns(self): pass def test_get_or_create_with_version_twice(self): pass def test_test_suites_by_environment(self): pass def test_testjobs_summary(self): pass def test_important_metadata_default(self): pass def test_important_metadata_default(self): pass def test_important_metadata_keys_with_spaces(self): pass def test_important_metadata_order(self): pass def test_metadata_with_different_values_for_the_same_key(self): pass def test_metadata_by_testrun(self): pass def test_create_project_status(self): pass
36
0
9
1
9
0
1
0.01
1
9
6
0
30
2
30
30
314
51
261
129
225
2
210
126
179
3
1
2
32
145,531
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/test/core/test_callback.py
test.core.test_callback.CallbackTest
class CallbackTest(TestCase): def setUp(self): self.group = Group.objects.create(slug='mygroup') self.project = self.group.projects.create( slug='myproject', project_settings='{"CALLBACK_HEADERS": {"Authorization": "token 123456"}}') self.build = self.project.builds.create(version='mybuild') self.event = Callback.events.ON_BUILD_FINISHED @patch('requests.post') def test_build_callback(self, requests_post): url = 'http://callback-target.com' callback = self.build.callbacks.create(url=url, event=self.event) callback.dispatch() self.assertTrue(requests_post.called) self.assertTrue(callback.is_sent) @patch('requests.post') def test_build_callback_with_json_payload(self, requests_post): url = 'http://callback-target.com' payload = json.dumps({'data': 'value'}) callback = self.build.callbacks.create( url=url, event=self.event, payload=payload) callback.dispatch() self.assertTrue(requests_post.called) self.assertTrue(callback.is_sent) requests_post.assert_called_with(url, json=payload) @patch('requests.post') def test_build_callback_with_formdata_payload(self, requests_post): url = 'http://callback-target.com' payload = {'data': 'value'} callback = self.build.callbacks.create( url=url, event=self.event, payload=json.dumps(payload), payload_is_json=False) callback.dispatch() self.assertTrue(requests_post.called) self.assertTrue(callback.is_sent) requests_post.assert_called_with(url, data=payload) @patch('requests.post') def test_build_callback_with_auth_headers(self, requests_post): url = 'http://callback-target.com' headers = {'Authorization': 'token 654321'} callback = self.build.callbacks.create( url=url, event=self.event, headers=json.dumps(headers)) callback.dispatch() self.assertTrue(requests_post.called) self.assertTrue(callback.is_sent) requests_post.assert_called_with(url, headers=headers) @patch('requests.post') def test_build_multiple_callbacks(self, requests_post): url1 = 'http://callback-target1.com' url2 = 'http://callback-target2.com' self.build.callbacks.create(url=url1, event=self.event) self.build.callbacks.create(url=url2, event=self.event) first_callback = self.build.callbacks.first() first_callback.dispatch() self.assertTrue(requests_post.called) self.assertTrue(first_callback.is_sent) requests_post.assert_called_with(url1) last_callback = self.build.callbacks.last() last_callback.dispatch() self.assertTrue(requests_post.called) self.assertTrue(last_callback.is_sent) requests_post.assert_called_with(url2) @patch('requests.post') def test_build_callback_not_dispatched_more_than_once(self, requests_post): url = 'http://callback-target.com' callback = self.build.callbacks.create(url=url, event=self.event) callback.dispatch() self.assertTrue(requests_post.called) self.assertTrue(callback.is_sent) requests_post.reset_mock() callback.dispatch() self.assertFalse(requests_post.called) @patch('requests.post') def test_build_callback_catch_exceptions_on_dispatch(self, requests_post): requests_post.side_effect = requests.exceptions.ConnectionError( "bad connection") url = 'http://callback-target.com' callback = self.build.callbacks.create( url=url, event=self.event, record_response=True) callback.dispatch() self.assertTrue(requests_post.called) self.assertTrue(callback.is_sent) self.assertEqual("bad connection", callback.response_content) @patch('requests.post') def test_build_callback_gets_deleted_on_build_deletion(self, requests_post): url = 'http://callback-target.com' build = self.project.builds.create(version='to-be-deleted') callback = build.callbacks.create(url=url, event=self.event) build.delete() with self.assertRaises(Callback.DoesNotExist): callback.refresh_from_db() def test_malformed_callback(self): callback = Callback(object_reference=self.build, url='invalid-url') with self.assertRaises(ValidationError): callback.full_clean() callback = Callback(object_reference=self.build, event='weird-event') with self.assertRaises(ValidationError): callback.full_clean() def test_duplicated_callback(self): self.build.callbacks.create(url='http://callback.url') with self.assertRaises(IntegrityError): self.build.callbacks.create(url='http://callback.url') def test_long_response_content(self): # Make sure callback won't raise errors when saving # response content of a callback response_content = 'content' * 1000 callback = self.build.callbacks.create( url='http://callback.url', response_content=response_content) callback.refresh_from_db() self.assertEqual(callback.response_content, response_content)
class CallbackTest(TestCase): def setUp(self): pass @patch('requests.post') def test_build_callback(self, requests_post): pass @patch('requests.post') def test_build_callback_with_json_payload(self, requests_post): pass @patch('requests.post') def test_build_callback_with_formdata_payload(self, requests_post): pass @patch('requests.post') def test_build_callback_with_auth_headers(self, requests_post): pass @patch('requests.post') def test_build_multiple_callbacks(self, requests_post): pass @patch('requests.post') def test_build_callback_not_dispatched_more_than_once(self, requests_post): pass @patch('requests.post') def test_build_callback_catch_exceptions_on_dispatch(self, requests_post): pass @patch('requests.post') def test_build_callback_gets_deleted_on_build_deletion(self, requests_post): pass def test_malformed_callback(self): pass def test_duplicated_callback(self): pass def test_long_response_content(self): pass
21
0
9
2
8
0
1
0.02
1
1
1
0
12
4
12
12
133
32
99
50
78
2
91
42
78
1
1
1
12
145,532
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/test/core/test_metric.py
test.core.test_metric.MetricTest
class MetricTest(TestCase): def test_measuremens_list_none(self): m = Metric(measurements=None) self.assertEqual([], m.measurement_list) def test_measuremens_list_empty(self): m = Metric(measurements='') self.assertEqual([], m.measurement_list) def test_measuremens_list(self): m = Metric(measurements='1,2.5,3') self.assertEqual([1, 2.5, 3], m.measurement_list) @patch("squad.core.models.join_name", lambda x, y: 'woooops') def test_full_name(self): sm = SuiteMetadata() m = Metric(metadata=sm) self.assertEqual('woooops', m.full_name)
class MetricTest(TestCase): def test_measuremens_list_none(self): pass def test_measuremens_list_empty(self): pass def test_measuremens_list_none(self): pass @patch("squad.core.models.join_name", lambda x, y: 'woooops') def test_full_name(self): pass
6
0
3
0
3
0
1
0
1
2
2
0
4
0
4
4
19
4
15
11
9
0
14
10
9
1
1
0
4
145,533
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/test/core/test_notification.py
test.core.test_notification.NotificationTest
class NotificationTest(TestCase): @patch("squad.core.comparison.TestComparison.diff", new_callable=PropertyMock) def test_delegates_diff_to_test_comparison_object(self, diff): the_diff = {} diff.return_value = the_diff group = Group.objects.create(slug='mygroup') project = group.projects.create(slug='myproject') build1 = project.builds.create(version='1') ProjectStatus.create_or_update(build1) build2 = project.builds.create(version='2') status = ProjectStatus.create_or_update(build2) notification = Notification(status) self.assertIs(the_diff, notification.diff)
class NotificationTest(TestCase): @patch("squad.core.comparison.TestComparison.diff", new_callable=PropertyMock) def test_delegates_diff_to_test_comparison_object(self, diff): pass
3
0
14
3
11
0
1
0
1
2
2
0
1
0
1
1
17
4
13
10
10
0
12
9
10
1
1
0
1
145,534
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/test/core/test_notification.py
test.core.test_notification.TestSendNotification
class TestSendNotification(TestCase): def setUp(self): t0 = timezone.now() - relativedelta(hours=3) t = timezone.now() - relativedelta(hours=2.75) self.group = Group.objects.create(slug='mygroup') self.user = User.objects.create(username='myuser', email="user@example.com") self.project = self.group.projects.create(slug='myproject') self.build1 = self.project.builds.create(version='1', datetime=t0) status = ProjectStatus.create_or_update(self.build1) status.finished = True status.notified = True status.save() self.build2 = self.project.builds.create(version='2', datetime=t) @patch("squad.core.comparison.TestComparison.diff", new_callable=PropertyMock) def test_send_notification(self, diff): self.project.subscriptions.create(email='foo@example.com') diff.return_value = fake_diff() status = ProjectStatus.create_or_update(self.build2) send_status_notification(status) self.assertEqual(1, len(mail.outbox)) @patch("squad.core.comparison.TestComparison.diff", new_callable=PropertyMock) def test_send_notification_for_all_builds(self, diff): self.project.subscriptions.create(email='foo@example.com') diff.return_value = fake_diff() status1 = ProjectStatus.create_or_update(self.build2) send_status_notification(status1) self.assertEqual(1, len(mail.outbox)) t = timezone.now() - relativedelta(hours=2.5) build = self.project.builds.create(version='3', datetime=t) status2 = ProjectStatus.create_or_update(build) send_status_notification(status2) self.assertEqual(2, len(mail.outbox)) def test_send_notification_on_change_only_with_no_changes(self): self.project.subscriptions.create( email='foo@example.com', notification_strategy=Subscription.NOTIFY_ON_CHANGE) status = ProjectStatus.create_or_update(self.build2) send_status_notification(status) self.assertEqual(0, len(mail.outbox)) def test_send_notification_on_regression_only_with_no_regressions(self): self.project.subscriptions.create( email='foo@example.com', notification_strategy=Subscription.NOTIFY_ON_REGRESSION) status = ProjectStatus.create_or_update(self.build2) send_status_notification(status) self.assertEqual(0, len(mail.outbox)) def test_send_notification_on_regression_only_with_no_errors(self): backend = Backend.objects.create( url='http://example.com', username='foobar', token='mypassword', ) self.build2.test_jobs.create( backend=backend, target=self.project, job_status="Incomplete" ) self.project.project_settings = yaml.dump( {'CI_LAVA_JOB_ERROR_STATUS': ["Incomplete"]}) self.project.save() self.project.subscriptions.create( email='foo@example.com', notification_strategy=Subscription.NOTIFY_ON_ERROR) status = ProjectStatus.create_or_update(self.build2) send_status_notification(status) self.assertEqual(0, len(mail.outbox)) @patch("squad.core.comparison.TestComparison.diff", new_callable=PropertyMock) def test_send_notification_on_change_only(self, diff): diff.return_value = fake_diff() self.project.subscriptions.create( email='foo@example.com', notification_strategy=Subscription.NOTIFY_ON_CHANGE) status = ProjectStatus.create_or_update(self.build2) send_status_notification(status) self.assertEqual(1, len(mail.outbox)) @patch("squad.core.comparison.TestComparison.regressions", new_callable=PropertyMock) def test_send_notification_on_regression_only(self, regressions): regressions.return_value = OrderedDict({'key': 'value'}) self.project.subscriptions.create( email='foo@example.com', notification_strategy=Subscription.NOTIFY_ON_REGRESSION) status = ProjectStatus.create_or_update(self.build2) send_status_notification(status) self.assertEqual(1, len(mail.outbox)) def test_send_notification_on_errors_only(self): backend = Backend.objects.create( url='http://example.com', username='foobar', token='mypassword', ) self.build2.test_jobs.create( backend=backend, target=self.project, job_status="Incomplete" ) self.project.project_settings = yaml.dump( {'CI_LAVA_JOB_ERROR_STATUS': "Incomplete"}) self.project.save() self.project.subscriptions.create( email='foo@example.com', notification_strategy=Subscription.NOTIFY_ON_ERROR) status = ProjectStatus.create_or_update(self.build2) send_status_notification(status) self.assertEqual(1, len(mail.outbox)) @patch("squad.core.comparison.TestComparison.diff", new_callable=PropertyMock) def test_no_recipients_no_email(self, diff): diff.return_value = fake_diff() status = ProjectStatus.create_or_update(self.build2) send_status_notification(status) self.assertEqual(0, len(mail.outbox)) @patch("squad.core.comparison.TestComparison.diff", new_callable=PropertyMock) def test_no_recipients_no_email_mark_as_notified(self, diff): diff.return_value = fake_diff() status = ProjectStatus.create_or_update(self.build2) send_status_notification(status) self.assertEqual(0, len(mail.outbox)) status.refresh_from_db() self.assertTrue(status.notified) @patch("squad.core.comparison.TestComparison.diff", new_callable=PropertyMock) def test_send_notification_to_user(self, diff): self.project.subscriptions.create(user=self.user) diff.return_value = fake_diff() status = ProjectStatus.create_or_update(self.build2) send_status_notification(status) self.assertEqual(1, len(mail.outbox)) def test_send_a_single_notification_email(self): self.project.subscriptions.create(email='foo@example.com') self.project.subscriptions.create(email='bar@example.com') status = ProjectStatus.create_or_update(self.build2) send_status_notification(status) self.assertEqual(1, len(mail.outbox)) def test_send_plain_text_only(self): self.project.subscriptions.create(email='foo@example.com') self.project.html_mail = False self.project.save() status = ProjectStatus.create_or_update(self.build2) send_status_notification(status) msg = mail.outbox[0] self.assertEqual(0, len(msg.alternatives)) def test_dont_html_escape_metadata_for_plain_text(self): self.project.subscriptions.create(email='foo@example.com') self.project.html_mail = False self.project.save() env = self.project.environments.create(slug='myenv') self.build2.test_runs.create( environment=env, metadata_file='{"foo": "foo\'bar"}') status = ProjectStatus.create_or_update(self.build2) send_status_notification(status) msg = mail.outbox[0] self.assertIn("foo'bar", msg.body) def test_parse_metadata_list_of_lists(self): self.project.subscriptions.create(email='foo@example.com') self.project.html_mail = False self.project.save() env = self.project.environments.create(slug='myenv') self.build2.test_runs.create( environment=env, metadata_file='{"foo": [["list of list value 1"],["list of list value 2"]]}') status = ProjectStatus.create_or_update(self.build2) send_status_notification(status) msg = mail.outbox[0] self.assertIn( "[['list of list value 1'], ['list of list value 2']]", msg.body) def test_parse_metadata_list_of_ints(self): self.project.subscriptions.create(email='foo@example.com') self.project.html_mail = False self.project.save() env = self.project.environments.create(slug='myenv') self.build2.test_runs.create( environment=env, metadata_file='{"duration": [11,22,33]}') status = ProjectStatus.create_or_update(self.build2) send_status_notification(status) msg = mail.outbox[0] self.assertIn("11", msg.body) self.assertIn("22", msg.body) self.assertIn("33", msg.body) def test_avoid_big_emails(self): _1MB = 1024 * 1024 self.project.subscriptions.create(email='foo@example.com') template = EmailTemplate.objects.create( plain_text='dummy string' * _1MB) self.project.custom_email_template = template self.project.html_mail = False self.project.save() status = ProjectStatus.create_or_update(self.build2) send_status_notification(status) msg = mail.outbox[0] self.assertNotIn('dummy string', msg.body) self.assertIn('The email got too big', msg.body)
class TestSendNotification(TestCase): def setUp(self): pass @patch("squad.core.comparison.TestComparison.diff", new_callable=PropertyMock) def test_send_notification(self, diff): pass @patch("squad.core.comparison.TestComparison.diff", new_callable=PropertyMock) def test_send_notification_for_all_builds(self, diff): pass def test_send_notification_on_change_only_with_no_changes(self): pass def test_send_notification_on_regression_only_with_no_regressions(self): pass def test_send_notification_on_regression_only_with_no_errors(self): pass @patch("squad.core.comparison.TestComparison.diff", new_callable=PropertyMock) def test_send_notification_on_change_only_with_no_changes(self): pass @patch("squad.core.comparison.TestComparison.regressions", new_callable=PropertyMock) def test_send_notification_on_regression_only_with_no_regressions(self): pass def test_send_notification_on_errors_only(self): pass @patch("squad.core.comparison.TestComparison.diff", new_callable=PropertyMock) def test_no_recipients_no_email(self, diff): pass @patch("squad.core.comparison.TestComparison.diff", new_callable=PropertyMock) def test_no_recipients_no_email_mark_as_notified(self, diff): pass @patch("squad.core.comparison.TestComparison.diff", new_callable=PropertyMock) def test_send_notification_to_user(self, diff): pass def test_send_a_single_notification_email(self): pass def test_send_plain_text_only(self): pass def test_dont_html_escape_metadata_for_plain_text(self): pass def test_parse_metadata_list_of_lists(self): pass def test_parse_metadata_list_of_ints(self): pass def test_avoid_big_emails(self): pass
26
0
10
1
10
0
1
0
1
6
4
0
18
5
18
18
213
31
182
66
156
0
146
59
127
1
1
0
18
145,535
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/test/core/test_tasks.py
test.core.test_tasks.CleanupOldBuildsTest
class CleanupOldBuildsTest(TestCase): def setUp(self): self.group = Group.objects.create(slug='mygroup') self.project = self.group.projects.create( slug='myproject', data_retention_days=180) def create_build(self, version, created_at=None, project=None): if not project: project = self.project build = project.builds.create(version=version) if created_at: build.created_at = created_at # override actual creation date build.save() return build @patch('squad.core.tasks.cleanup_build') def test_cleanup_old_builds(self, cleanup_build): seven_months_ago = timezone.now() - timezone.timedelta(210) old_build = self.create_build('1', seven_months_ago) self.create_build('2') # new build, should be kept cleanup_old_builds() cleanup_build.delay.assert_called_once_with(old_build.id) @patch('squad.core.tasks.cleanup_build') def test_cleanup_old_builds_does_not_delete_builds_from_other_projects(self, cleanup_build): seven_months_ago = timezone.now() - timezone.timedelta(210) other_project = self.group.projects.create(slug='otherproject') self.create_build('1', created_at=seven_months_ago, project=other_project) cleanup_old_builds() cleanup_build.delay.assert_not_called() @patch('squad.core.tasks.cleanup_build') def test_cleanup_old_builds_respects_data_retention_policy(self, cleanup_build): build = self.create_build('1', timezone.now() - timezone.timedelta(90)) cleanup_old_builds() cleanup_build.delay.assert_not_called() self.project.data_retention_days = 60 self.project.save() cleanup_old_builds() cleanup_build.delay.assert_called_once_with(build.id) def test_cleanup_build(self): build_id = self.create_build('1').id self.assertTrue(self.project.builds.filter(id=build_id).exists()) cleanup_build(build_id) self.assertFalse(self.project.builds.filter(id=build_id).exists()) def test_cleanup_build_created_placeholder(self): build_id = self.create_build('1').id cleanup_build(build_id) self.assertTrue( self.project.build_placeholders.filter(version='1').exists()) @patch('squad.core.tasks.cleanup_build') def test_no_cleanup_with_non_positive_data_retention_days(self, cleanup_build): self.project.data_retention_days = 0 self.project.save() self.create_build('1', timezone.now() - timezone.timedelta(210)) cleanup_old_builds() cleanup_build.delay.assert_not_called() @patch('squad.core.tasks.cleanup_build') def test_no_cleanup_when_build_has_keep_data_checked(self, cleanup_build): build = self.create_build( '1', timezone.now() - timezone.timedelta(210)) build.keep_data = True build.save() cleanup_old_builds() cleanup_build.delay.assert_not_called()
class CleanupOldBuildsTest(TestCase): def setUp(self): pass def create_build(self, version, created_at=None, project=None): pass @patch('squad.core.tasks.cleanup_build') def test_cleanup_old_builds(self, cleanup_build): pass @patch('squad.core.tasks.cleanup_build') def test_cleanup_old_builds_does_not_delete_builds_from_other_projects(self, cleanup_build): pass @patch('squad.core.tasks.cleanup_build') def test_cleanup_old_builds_respects_data_retention_policy(self, cleanup_build): pass def test_cleanup_build(self): pass def test_cleanup_build_created_placeholder(self): pass @patch('squad.core.tasks.cleanup_build') def test_no_cleanup_with_non_positive_data_retention_days(self, cleanup_build): pass @patch('squad.core.tasks.cleanup_build') def test_no_cleanup_when_build_has_keep_data_checked(self, cleanup_build): pass
15
0
6
0
6
0
1
0.03
1
0
0
0
9
2
9
9
68
10
58
26
43
2
53
21
43
3
1
1
11
145,536
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/test/core/test_tasks.py
test.core.test_tasks.CreateBuildTest
class CreateBuildTest(TestCase): def setUp(self): group = Group.objects.create(slug='mygroup') self.project = group.projects.create(slug='mygroup') self.patch_source = PatchSource.objects.create( name='github', username='foo', url='https://github.com/', token='*********', implementation='example' ) def test_basics(self): create_build = CreateBuild(self.project) baseline, created = create_build('0.0') build, created = create_build( version='1.0', patch_source=self.patch_source, patch_id='111', patch_baseline=baseline, ) self.assertEqual(build.patch_source, self.patch_source) self.assertEqual(build.patch_id, '111') self.assertEqual(build.patch_baseline, baseline) self.assertEqual(build.patch_url, self.patch_source.get_url(build)) @patch('squad.core.tasks.notify_patch_build_created') def test_notify_patch_source(self, notify_patch_build_created): create_build = CreateBuild(self.project) build, created = create_build( '1.0', patch_source=self.patch_source, patch_id='111') notify_patch_build_created.delay.assert_called_with(build.id) @patch('squad.core.tasks.notify_patch_build_created') def test_dont_notify_patch_source_existing_build(self, notify_patch_build_created): create_build = CreateBuild(self.project) build, created = create_build( '1.0', patch_source=self.patch_source, patch_id='111') notify_patch_build_created.delay.assert_called_with(build.id) notify_patch_build_created.reset_mock() build, created = create_build( '1.0', patch_source=self.patch_source, patch_id='111') notify_patch_build_created.delay.assert_not_called() self.assertEqual(False, created) @patch('squad.core.tasks.notify_patch_build_created') def test_dont_notify_without_patch_source(self, notify_patch_build_created): create_build = CreateBuild(self.project) create_build('1.0') # no patch_source or patch_id notify_patch_build_created.delay.assert_not_called()
class CreateBuildTest(TestCase): def setUp(self): pass def test_basics(self): pass @patch('squad.core.tasks.notify_patch_build_created') def test_notify_patch_source(self, notify_patch_build_created): pass @patch('squad.core.tasks.notify_patch_build_created') def test_dont_notify_patch_source_existing_build(self, notify_patch_build_created): pass @patch('squad.core.tasks.notify_patch_build_created') def test_dont_notify_without_patch_source(self, notify_patch_build_created): pass
9
0
8
0
8
0
1
0.02
1
2
2
0
5
2
5
5
48
5
43
20
34
1
29
17
23
1
1
0
5
145,537
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/test/core/test_tasks.py
test.core.test_tasks.PrepareDelayedReport
class PrepareDelayedReport(TestCase): def setUp(self): self.group = Group.objects.create(slug='mygroup') self.project = self.group.projects.create(slug='myproject') t = timezone.make_aware(datetime.datetime(2018, 10, 1, 1, 0, 0)) self.build = self.project.builds.create(version='1', datetime=t) t2 = timezone.make_aware(datetime.datetime(2018, 10, 2, 1, 0, 0)) self.build2 = self.project.builds.create(version='2', datetime=t2) self.environment = self.project.environments.create(slug='myenv') self.environment_a = self.project.environments.create(slug='env-a') self.testrun = self.build.test_runs.create( environment=self.environment, build=self.build) self.testrun2 = self.build2.test_runs.create( environment=self.environment, build=self.build2) self.testrun_a = self.build.test_runs.create( environment=self.environment_a, build=self.build) self.testrun2_a = self.build2.test_runs.create( environment=self.environment_a, build=self.build2) self.emailtemplate = EmailTemplate.objects.create( name="fooTemplate", subject="abc", plain_text="def", ) self.validemailtemplate = EmailTemplate.objects.create( name="validTemplate", subject="subject", plain_text="{% if foo %}bar{% endif %}", html="{% if foo %}bar{% endif %}" ) self.invalidemailtemplate = EmailTemplate.objects.create( name="invalidTemplate", subject="subject", plain_text="{% if foo %}bar", html="{% if foo %}bar" ) def test_invalid_id(self): report = prepare_report(999) self.assertIsNone(report) def test_prepare_report(self): UpdateProjectStatus()(self.testrun) UpdateProjectStatus()(self.testrun2) report = self.build2.delayed_reports.create() prepared_report = prepare_report(report.pk) self.assertEqual(200, prepared_report.status_code) def test_long_error_message(self): report = self.build2.delayed_reports.create() prepared_report = prepare_report(report.pk) data = { "lineno": 1234, "message": LONG_ERROR_MESSAGE } update_delayed_report(prepared_report, data, 400) self.assertEqual(yaml.safe_load(prepared_report.error_message)[ 'message'], LONG_ERROR_MESSAGE) @patch('squad.core.tasks.notification.notify_delayed_report_email.delay') def test_email_notification(self, email_notification_mock): UpdateProjectStatus()(self.testrun) UpdateProjectStatus()(self.testrun2) report = self.build2.delayed_reports.create() report.email_recipient = "foo@bar.com" report.save() prepared_report = prepare_report(report.pk) self.assertEqual(200, prepared_report.status_code) email_notification_mock.assert_called_with(report.pk) @patch('squad.core.tasks.notification.notify_delayed_report_callback.delay') def test_callback_notification(self, callback_notification_mock): UpdateProjectStatus()(self.testrun) UpdateProjectStatus()(self.testrun2) report = self.build2.delayed_reports.create() report.callback = "http://foo.bar.com" report.save() prepared_report = prepare_report(report.pk) self.assertEqual(200, prepared_report.status_code) callback_notification_mock.assert_called_with(report.pk)
class PrepareDelayedReport(TestCase): def setUp(self): pass def test_invalid_id(self): pass def test_prepare_report(self): pass def test_long_error_message(self): pass @patch('squad.core.tasks.notification.notify_delayed_report_email.delay') def test_email_notification(self, email_notification_mock): pass @patch('squad.core.tasks.notification.notify_delayed_report_callback.delay') def test_callback_notification(self, callback_notification_mock): pass
9
0
11
0
11
0
1
0
1
3
2
0
6
13
6
6
76
7
69
34
60
0
50
32
43
1
1
0
6
145,538
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/test/core/test_tasks.py
test.core.test_tasks.ProcessTestRunTest
class ProcessTestRunTest(CommonTestCase): def test_basics(self): ProcessTestRun()(self.testrun) self.assertEqual(5, self.testrun.tests.count()) self.assertEqual(6, self.testrun.status.count()) @patch('squad.core.tasks.PostProcessTestRun.__call__') def test_postprocess(self, postprocess): ProcessTestRun()(self.testrun) postprocess.assert_called_with(self.testrun)
class ProcessTestRunTest(CommonTestCase): def test_basics(self): pass @patch('squad.core.tasks.PostProcessTestRun.__call__') def test_postprocess(self, postprocess): pass
4
0
4
0
4
0
1
0
1
1
1
0
2
0
2
3
11
2
9
4
5
0
8
3
5
1
2
0
2
145,539
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/test/core/test_tasks.py
test.core.test_tasks.ReceiveTestRunTest
class ReceiveTestRunTest(TestCase): def setUp(self): self.group = Group.objects.create(slug='mygroup') self.project = self.group.projects.create(slug='mygroup') def test_metadata(self): receive = ReceiveTestRun(self.project) today = timezone.now() metadata = { "datetime": today.isoformat(), "job_id": '999', "job_status": 'pass', "job_url": 'https://example.com/jobs/999', "resubmit_url": 'https://example.com/jobs/999', "build_url": 'https://example/com/builds/777', } receive('199', 'myenv', metadata_file=json.dumps(metadata)) testrun = TestRun.objects.last() self.assertEqual(today, testrun.datetime) self.assertEqual(metadata['job_id'], testrun.job_id) self.assertEqual(metadata['job_status'], testrun.job_status) self.assertEqual(metadata['job_url'], testrun.job_url) self.assertEqual(metadata['resubmit_url'], testrun.resubmit_url) self.assertEqual(metadata['build_url'], testrun.build_url) def test_metadata_non_string_values(self): receive = ReceiveTestRun(self.project) metadata_in = { 'job_id': '12345', 'number': 999, 'version': 4.4, 'list': [1, 2, 3], 'object': {'1': 2}, } receive('199', 'myenv', metadata_file=json.dumps(metadata_in)) testrun = TestRun.objects.last() metadata = json.loads(testrun.metadata_file) self.assertEqual(metadata_in, metadata) def test_logfile(self): receive = ReceiveTestRun(self.project) metadata_in = { 'job_id': '12345' } LOG_FILE_CONTENT = "abc" receive('199', 'myenv', metadata_file=json.dumps( metadata_in), log_file=LOG_FILE_CONTENT) testrun = TestRun.objects.last() self.assertEqual(LOG_FILE_CONTENT, testrun.log_file) self.assertEqual(LOG_FILE_CONTENT, testrun.log_file_storage.read().decode()) def test_logfile_with_null_bytes(self): receive = ReceiveTestRun(self.project) metadata_in = { 'job_id': '12345' } LOG_FILE_CONTENT = "ab\x00c" LOG_FILE_PROPER_CONTENT = "abc" receive('199', 'myenv', metadata_file=json.dumps( metadata_in), log_file=LOG_FILE_CONTENT) testrun = TestRun.objects.last() self.assertEqual(LOG_FILE_PROPER_CONTENT, testrun.log_file) self.assertEqual(LOG_FILE_PROPER_CONTENT, testrun.log_file_storage.read().decode()) def test_build_datetime(self): receive = ReceiveTestRun(self.project) yesterday = timezone.now() - relativedelta(days=7) metadata = { "datetime": yesterday.isoformat(), "job_id": '999', "job_status": 'pass', "job_url": 'https://example.com/jobs/999', "build_url": 'https://example/com/builds/777', } receive('199', 'myenv', metadata_file=json.dumps(metadata)) build = Build.objects.get(version='199') self.assertEqual(yesterday, build.datetime) @patch('squad.core.tasks.ValidateTestRun.__call__') def test_should_validate_test_run(self, validator_mock): validator_mock.side_effect = RuntimeError('crashed') with self.assertRaises(RuntimeError): receive = ReceiveTestRun(self.project) receive('199', 'myenv') def test_test_result_is_not_pass_or_fail(self): receive = ReceiveTestRun(self.project) metadata = { "job_id": '999', } tests = { "test1": "pass", "test2": "fail", "test3": "skip", } receive('199', 'myenv', metadata_file=json.dumps( metadata), tests_file=json.dumps(tests)) testrun = TestRun.objects.last() values = [t.result for t in testrun.tests.order_by('metadata__name')] self.assertEqual([True, False, None], values) def test_generate_job_id_when_not_present(self): receive = ReceiveTestRun(self.project) receive('199', 'myenv') testrun = TestRun.objects.last() self.assertIsNotNone(testrun.job_id) def test_update_project_status(self): receive = ReceiveTestRun(self.project) receive('199', 'myenv') testrun = TestRun.objects.last() self.assertEqual(1, ProjectStatus.objects.filter( build=testrun.build).count()) @patch('squad.core.tasks.UpdateProjectStatus.__call__') def test_dont_update_project_status(self, UpdateProjectStatus): receive = ReceiveTestRun(self.project, update_project_status=False) receive('199', 'myenv') UpdateProjectStatus.assert_not_called()
class ReceiveTestRunTest(TestCase): def setUp(self): pass def test_metadata(self): pass def test_metadata_non_string_values(self): pass def test_logfile(self): pass def test_logfile_with_null_bytes(self): pass def test_build_datetime(self): pass @patch('squad.core.tasks.ValidateTestRun.__call__') def test_should_validate_test_run(self, validator_mock): pass def test_test_result_is_not_pass_or_fail(self): pass def test_generate_job_id_when_not_present(self): pass def test_update_project_status(self): pass @patch('squad.core.tasks.UpdateProjectStatus.__call__') def test_dont_update_project_status(self, UpdateProjectStatus): pass
14
0
11
1
9
0
1
0
1
6
4
0
11
2
11
11
131
26
105
48
91
0
74
46
62
1
1
1
11
145,540
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/test/core/test_tasks.py
test.core.test_tasks.TestPostProcessTestRun
class TestPostProcessTestRun(CommonTestCase): @patch('squad.plugins.example.Plugin.postprocess_testrun') def test_calls_enabled_plugin(self, plugin_method): project = self.testrun.build.project project.enabled_plugins_list = ['example'] project.save() PostProcessTestRun()(self.testrun) plugin_method.assert_called_with(self.testrun)
class TestPostProcessTestRun(CommonTestCase): @patch('squad.plugins.example.Plugin.postprocess_testrun') def test_calls_enabled_plugin(self, plugin_method): pass
3
0
6
0
6
0
1
0
1
1
1
0
1
0
1
2
9
1
8
4
5
0
7
3
5
1
2
0
1
145,541
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/test/core/test_tasks.py
test.core.test_tasks.UpdateProjectStatusTest
class UpdateProjectStatusTest(CommonTestCase): @patch('squad.core.tasks.maybe_notify_project_status') def test_sends_notification(self, maybe_notify_project_status): ParseTestRunData()(self.testrun) RecordTestRunStatus()(self.testrun) UpdateProjectStatus()(self.testrun) status = ProjectStatus.objects.last() maybe_notify_project_status.delay.assert_called_with(status.id) @patch('requests.post') def test_dispatch_callback_on_build_finished(self, requests_post): url = 'http://callback-target.com' callback = self.build.callbacks.create( url=url, event=Callback.events.ON_BUILD_FINISHED) ParseTestRunData()(self.testrun) RecordTestRunStatus()(self.testrun) UpdateProjectStatus()(self.testrun) callback.refresh_from_db() self.assertTrue(callback.is_sent) requests_post.assert_called_with(url)
class UpdateProjectStatusTest(CommonTestCase): @patch('squad.core.tasks.maybe_notify_project_status') def test_sends_notification(self, maybe_notify_project_status): pass @patch('requests.post') def test_dispatch_callback_on_build_finished(self, requests_post): pass
5
0
9
2
8
0
1
0
1
5
5
0
2
0
2
3
23
5
18
8
13
0
16
6
13
1
2
0
2
145,542
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/test/core/test_tasks_notification.py
test.core.test_tasks_notification.TestNotificationTasks
class TestNotificationTasks(TestCase): def setUp(self): group = Group.objects.create(slug='mygroup') self.project1 = group.projects.create(slug='myproject1') self.project2 = group.projects.create(slug='myproject2') @patch("squad.core.tasks.notification.send_status_notification") def test_notify_project_status(self, send_status_notification): build = self.project1.builds.create(datetime=timezone.now()) environment = self.project1.environments.create(slug='env') build.test_runs.create(environment=environment) status = ProjectStatus.create_or_update(build) notify_project_status(status.id) send_status_notification.assert_called_with(status) @patch("squad.core.tasks.notification.send_status_notification") def test_maybe_notify_project_status(self, send_status_notification): build = self.project1.builds.create(datetime=timezone.now()) environment = self.project1.environments.create(slug='env') build.test_runs.create(environment=environment) status = ProjectStatus.create_or_update(build) maybe_notify_project_status(status.id) send_status_notification.assert_called_with(status) @patch("squad.core.tasks.notification.notify_patch_build_finished") def test_maybe_notify_project_status_notify_patch_build_finished(self, notify_patch_build_finished): build = self.project1.builds.create(datetime=timezone.now()) environment = self.project1.environments.create(slug='env') build.test_runs.create(environment=environment) status = ProjectStatus.create_or_update(build) maybe_notify_project_status(status.id) notify_patch_build_finished.delay.assert_called_with(build.id) @patch("squad.core.tasks.notification.notify_patch_build_finished") def test_maybe_notify_project_status_notify_patch_build_finished_active_plugin(self, notify_patch_build_finished): build = self.project1.builds.create(datetime=timezone.now()) environment = self.project1.environments.create(slug='env') build.test_runs.create(environment=environment) build.pluginscratch_set.create() status = ProjectStatus.create_or_update(build) maybe_notify_project_status(status.id) notify_patch_build_finished.delay.assert_not_called() build.pluginscratch_set.all().delete() maybe_notify_project_status(status.id) notify_patch_build_finished.delay.assert_called_with(build.id) @patch("squad.core.tasks.notification.send_status_notification") def test_maybe_notify_project_status_do_not_send_dup_notification(self, send_status_notification): build = self.project1.builds.create(datetime=timezone.now()) environment = self.project1.environments.create(slug='env') build.test_runs.create(environment=environment) status = ProjectStatus.create_or_update(build) status.notified = True status.save() maybe_notify_project_status(status.id) send_status_notification.assert_not_called() @patch("django.utils.timezone.now") @patch("squad.core.tasks.notification.send_status_notification") @patch("squad.core.tasks.notification.maybe_notify_project_status.apply_async") def test_maybe_notify_project_status_wait_before_notification(self, apply_async, send_status_notification, now): self.project1.wait_before_notification = 3600 # 1 hour self.project1.save() # build was created half an hour ago now.return_value = timezone.make_aware( datetime.datetime(2017, 10, 20, 10, 30, 0)) build = self.project1.builds.create(datetime=timezone.make_aware( datetime.datetime(2017, 10, 20, 10, 0, 0))) environment = self.project1.environments.create(slug='env') build.test_runs.create(environment=environment) status = ProjectStatus.create_or_update(build) maybe_notify_project_status(status.id) send_status_notification.assert_not_called() apply_async.assert_called_with(args=[status.id], countdown=1801) @patch("django.utils.timezone.now") @patch("squad.core.tasks.notification.send_status_notification") @patch("squad.core.tasks.notification.maybe_notify_project_status.apply_async") def test_maybe_notify_project_status_notifies_after_wait_before_notification(self, apply_async, send_status_notification, now): self.project1.wait_before_notification = 3600 # 1 hour self.project1.save() # build was created more than one hour ago now.return_value = timezone.make_aware( datetime.datetime(2017, 10, 20, 10, 30, 0)) build = self.project1.builds.create( datetime=timezone.make_aware(datetime.datetime(2017, 10, 20, 9, 0, 0))) environment = self.project1.environments.create(slug='env') build.test_runs.create(environment=environment) status = ProjectStatus.create_or_update(build) maybe_notify_project_status(status.id) send_status_notification.assert_called_with(status) apply_async.assert_not_called() @patch("squad.core.tasks.notification.notification_timeout.apply_async") def test_maybe_notify_project_status_schedule_timeout(self, apply_async): self.project1.notification_timeout = 3600 # 1 hour self.project1.save() build = self.project1.builds.create(datetime=timezone.now()) environment = self.project1.environments.create(slug='env') build.test_runs.create(environment=environment) status = ProjectStatus.create_or_update(build) maybe_notify_project_status(status.id) apply_async.assert_called_with(args=[status.id], countdown=3600) @patch("squad.core.tasks.notification.notification_timeout.apply_async") def test_maybe_notify_project_status_schedule_timeout_not_requested(self, apply_async): build = self.project1.builds.create(datetime=timezone.now()) environment = self.project1.environments.create(slug='env') build.test_runs.create(environment=environment) status = ProjectStatus.create_or_update(build) maybe_notify_project_status(status.id) apply_async.assert_not_called() @patch("squad.core.tasks.notification.send_status_notification") def test_notification_timeout(self, send_status_notification): self.project1.notification_timeout = 3600 # 1 hour self.project1.save() build = self.project1.builds.create(datetime=timezone.now()) environment = self.project1.environments.create(slug='env') build.test_runs.create(environment=environment) status = ProjectStatus.create_or_update(build) notification_timeout(status.id) send_status_notification.assert_called_with(status) @patch("squad.core.tasks.notification.send_status_notification") def test_notification_timeout_active_plugin(self, send_status_notification): self.project1.notification_timeout = 3600 # 1 hour self.project1.save() build = self.project1.builds.create(datetime=timezone.now()) environment = self.project1.environments.create(slug='env') build.test_runs.create(environment=environment) build.pluginscratch_set.create() status = ProjectStatus.create_or_update(build) notification_timeout(status.id) send_status_notification.assert_called_with(status) @patch("squad.core.tasks.notification.send_status_notification") def test_notification_timeout_noop(self, send_status_notification): self.project1.notification_timeout = 3600 # 1 hour self.project1.save() build = self.project1.builds.create(datetime=timezone.now()) environment = self.project1.environments.create(slug='env') build.test_runs.create(environment=environment) status = ProjectStatus.create_or_update(build) status.notified = True status.save() notification_timeout(status.id) send_status_notification.assert_not_called() @patch("squad.core.tasks.notification.send_status_notification") def test_notification_timeout_only_once(self, send_status_notification): self.project1.notification_timeout = 3600 # 1 hour self.project1.save() build = self.project1.builds.create(datetime=timezone.now()) environment = self.project1.environments.create(slug='env') build.test_runs.create(environment=environment) status = ProjectStatus.create_or_update(build) notification_timeout(status.id) notification_timeout(status.id) self.assertEqual(1, len(send_status_notification.call_args_list)) @patch("squad.core.tasks.notification.notification_timeout.apply_async") def test_notification_timeout_only_one_task(self, notification_timeout_apply_async): self.project1.notification_timeout = 3600 # 1 hour self.project1.save() build = self.project1.builds.create(datetime=timezone.now()) environment = self.project1.environments.create(slug='env') build.test_runs.create(environment=environment) status = ProjectStatus.create_or_update(build) maybe_notify_project_status(status.id) maybe_notify_project_status(status.id) self.assertEqual( 1, len(notification_timeout_apply_async.call_args_list))
class TestNotificationTasks(TestCase): def setUp(self): pass @patch("squad.core.tasks.notification.send_status_notification") def test_notify_project_status(self, send_status_notification): pass @patch("squad.core.tasks.notification.send_status_notification") def test_maybe_notify_project_status(self, send_status_notification): pass @patch("squad.core.tasks.notification.notify_patch_build_finished") def test_maybe_notify_project_status_notify_patch_build_finished(self, notify_patch_build_finished): pass @patch("squad.core.tasks.notification.notify_patch_build_finished") def test_maybe_notify_project_status_notify_patch_build_finished_active_plugin(self, notify_patch_build_finished): pass @patch("squad.core.tasks.notification.send_status_notification") def test_maybe_notify_project_status_do_not_send_dup_notification(self, send_status_notification): pass @patch("django.utils.timezone.now") @patch("squad.core.tasks.notification.send_status_notification") @patch("squad.core.tasks.notification.maybe_notify_project_status.apply_async") def test_maybe_notify_project_status_wait_before_notification(self, apply_async, send_status_notification, now): pass @patch("django.utils.timezone.now") @patch("squad.core.tasks.notification.send_status_notification") @patch("squad.core.tasks.notification.maybe_notify_project_status.apply_async") def test_maybe_notify_project_status_notifies_after_wait_before_notification(self, apply_async, send_status_notification, now): pass @patch("squad.core.tasks.notification.notification_timeout.apply_async") def test_maybe_notify_project_status_schedule_timeout(self, apply_async): pass @patch("squad.core.tasks.notification.notification_timeout.apply_async") def test_maybe_notify_project_status_schedule_timeout_not_requested(self, apply_async): pass @patch("squad.core.tasks.notification.send_status_notification") def test_notification_timeout(self, send_status_notification): pass @patch("squad.core.tasks.notification.send_status_notification") def test_notification_timeout_active_plugin(self, send_status_notification): pass @patch("squad.core.tasks.notification.send_status_notification") def test_notification_timeout_noop(self, send_status_notification): pass @patch("squad.core.tasks.notification.send_status_notification") def test_notification_timeout_only_once(self, send_status_notification): pass @patch("squad.core.tasks.notification.notification_timeout.apply_async") def test_notification_timeout_only_one_task(self, notification_timeout_apply_async): pass
34
0
11
2
9
1
1
0.07
1
2
1
0
15
2
15
15
196
42
152
75
118
10
134
61
118
1
1
0
15
145,543
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/test/core/test_tasks_notification.py
test.core.test_tasks_notification.TestNotificationTasksRaceCondition
class TestNotificationTasksRaceCondition(TransactionTestCase): def mock_apply_async(args, countdown=None): time.sleep(1) @tag('skip_sqlite') @patch("squad.core.tasks.notification.notification_timeout.apply_async", side_effect=mock_apply_async) def test_notification_race_condition(self, notification_timeout_apply_async): group = Group.objects.create(slug='mygroup') project = group.projects.create( slug='myproject1', notification_timeout=1) build = project.builds.create(datetime=timezone.now()) status = ProjectStatus.create_or_update(build) # ref: https://stackoverflow.com/a/56584761/3908350 def thread(status_id): maybe_notify_project_status(status_id) connection.close() parallel_task_1 = threading.Thread(target=thread, args=(status.id,)) parallel_task_2 = threading.Thread(target=thread, args=(status.id,)) parallel_task_1.start() parallel_task_2.start() parallel_task_1.join() parallel_task_2.join() self.assertEqual(1, notification_timeout_apply_async.call_count) @tag('skip_sqlite') @patch("squad.core.tasks.notification.notify_patch_build_finished.delay") def test_maybe_notify_project_status_notify_patch_build_finished_do_not_send_dup_race_condition(self, notify_patch_build_finished): group = Group.objects.create(slug='mygroup') project = group.projects.create(slug='myproject1') build = project.builds.create(datetime=timezone.now()) environment = project.environments.create(slug='env') build.test_runs.create(environment=environment) status = ProjectStatus.create_or_update(build) def thread(status_id): maybe_notify_project_status(status_id) connection.close() parallel_task_1 = threading.Thread(target=thread, args=(status.id,)) parallel_task_2 = threading.Thread(target=thread, args=(status.id,)) parallel_task_1.start() parallel_task_2.start() parallel_task_1.join() parallel_task_2.join() self.assertEqual(1, notify_patch_build_finished.call_count)
class TestNotificationTasksRaceCondition(TransactionTestCase): def mock_apply_async(args, countdown=None): pass @tag('skip_sqlite') @patch("squad.core.tasks.notification.notification_timeout.apply_async", side_effect=mock_apply_async) def test_notification_race_condition(self, notification_timeout_apply_async): pass def thread(status_id): pass @tag('skip_sqlite') @patch("squad.core.tasks.notification.notify_patch_build_finished.delay") def test_maybe_notify_project_status_notify_patch_build_finished_do_not_send_dup_race_condition(self, notify_patch_build_finished): pass def thread(status_id): pass
10
0
10
2
8
0
1
0.03
1
2
1
0
3
0
3
3
53
13
39
21
29
1
35
19
29
1
1
0
5
145,544
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/test/core/test_tasks_notification.py
test.core.test_tasks_notification.TestPatchNotificationTasks
class TestPatchNotificationTasks(TestCase): def setUp(self): group = Group.objects.create(slug='mygroup') self.project = group.projects.create(slug='myproject') self.patch_source = PatchSource.objects.create( name='foo', implementation='example', ) @patch("squad.core.models.PatchSource.get_implementation") def test_notify_patch_build_created(self, get_implementation): build = self.project.builds.create( version='1', patch_source=self.patch_source, patch_id='0123456789', ) plugin = MagicMock() get_implementation.return_value = plugin notify_patch_build_created(build.id) plugin.notify_patch_build_created.assert_called_with(build) @patch("squad.core.models.PatchSource.get_implementation") def test_notify_patch_build_finished(self, get_implementation): build = self.project.builds.create( version='1', patch_source=self.patch_source, patch_id='0123456789', ) plugin = MagicMock() get_implementation.return_value = plugin notify_patch_build_finished(build.id) plugin.notify_patch_build_finished.assert_called_with(build)
class TestPatchNotificationTasks(TestCase): def setUp(self): pass @patch("squad.core.models.PatchSource.get_implementation") def test_notify_patch_build_created(self, get_implementation): pass @patch("squad.core.models.PatchSource.get_implementation") def test_notify_patch_build_finished(self, get_implementation): pass
6
0
10
1
9
0
1
0
1
2
1
0
3
2
3
3
37
7
30
13
24
0
17
11
13
1
1
0
3
145,545
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/test/core/test_tasks_notification.py
test.core.test_tasks_notification.TestReportNotificationTasks
class TestReportNotificationTasks(TestCase): def setUp(self): self.group = Group.objects.create(slug='mygroup') self.project = self.group.projects.create(slug='myproject') self.build = self.project.builds.create(version='1') self.report = self.build.delayed_reports.create() @patch('requests.Session') def test_callback_notification(self, send_mock): url = "https://foo.bar.com" self.report.callback = url self.report.save() notify_delayed_report_callback(self.report.pk) send_mock.assert_any_call() report = DelayedReport.objects.get(pk=self.report.pk) self.assertTrue(report.callback_notified) @patch('requests.Session.send') def test_callback_notification_sent_earlier(self, send_mock): self.report.callback = "https://foo.bar.com" self.report.callback_notified = True self.report.save() notify_delayed_report_callback(self.report.pk) send_mock.assert_not_called() @patch('squad.core.models.DelayedReport.send') def test_email_notification(self, send_mock): self.report.email_recipient = "foo@bar.com" self.report.save() notify_delayed_report_email(self.report.pk) send_mock.assert_called_with() @patch('squad.core.models.DelayedReport.send') def test_email_notification_sent_earlier(self, send_mock): self.report.email_recipient = "foo@bar.com" self.report.email_recipient_notified = True self.report.save() notify_delayed_report_email(self.report.pk) send_mock.assert_not_called()
class TestReportNotificationTasks(TestCase): def setUp(self): pass @patch('requests.Session') def test_callback_notification(self, send_mock): pass @patch('requests.Session.send') def test_callback_notification_sent_earlier(self, send_mock): pass @patch('squad.core.models.DelayedReport.send') def test_email_notification(self, send_mock): pass @patch('squad.core.models.DelayedReport.send') def test_email_notification_sent_earlier(self, send_mock): pass
10
0
6
0
6
0
1
0
1
1
1
0
5
4
5
5
40
5
35
16
25
0
31
12
25
1
1
0
5
145,546
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/test/core/test_test.py
test.core.test_test.TestTest
class TestTest(TestCase): @patch("squad.core.models.join_name", lambda x, y: 'woooops') def test_full_name(self): t = create_test() self.assertEqual('woooops', t.full_name) def test_status_na(self): t = create_test(result=None) self.assertEqual('skip', t.status) def test_status_pass(self): t = create_test(result=True) self.assertEqual('pass', t.status) def test_status_fail(self): t = create_test(result=False) self.assertEqual('fail', t.status) def test_status_xfail(self): t = create_test(result=False, has_known_issues=True) self.assertEqual('xfail', t.status)
class TestTest(TestCase): @patch("squad.core.models.join_name", lambda x, y: 'woooops') def test_full_name(self): pass def test_status_na(self): pass def test_status_pass(self): pass def test_status_fail(self): pass def test_status_xfail(self): pass
7
0
3
0
3
0
1
0
1
0
0
0
5
0
5
5
22
5
17
12
10
0
16
11
10
1
1
0
5
145,547
Linaro/squad
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Linaro_squad/test/frontend/test_get_token_command.py
test.frontend.test_get_token_command.TestCommand
class TestCommand(TestCase): @patch('squad.frontend.management.commands.get_token.Command.output') def test_basics(self, output): command = Command() command.handle(PROJECT='foo/bar') project = Project.objects.get(group__slug='foo', slug='bar') self.assertEqual(project.group.members.count(), 1) @patch('squad.frontend.management.commands.get_token.Command.output') def test_is_idempotent(self, output): command = Command() command.handle(PROJECT='foo/bar') command.handle(PROJECT='foo/bar') project = Project.objects.get(group__slug='foo', slug='bar') self.assertEqual(project.group.members.count(), 1)
class TestCommand(TestCase): @patch('squad.frontend.management.commands.get_token.Command.output') def test_basics(self, output): pass @patch('squad.frontend.management.commands.get_token.Command.output') def test_is_idempotent(self, output): pass
5
0
6
0
6
0
1
0
1
2
2
0
2
0
2
2
16
2
14
9
9
0
12
7
9
1
1
0
2