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
2,100
ARMmbed/icetea
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ARMmbed_icetea/icetea_lib/Plugin/plugins/plugin_tests/test_dutmbed.py
icetea_lib.Plugin.plugins.plugin_tests.test_dutmbed.DutMbedTestcase
class DutMbedTestcase(unittest.TestCase): @mock.patch("icetea_lib.DeviceConnectors.Dut.LogManager") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.get_external_logger") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.Flash") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.Build") def test_flasher_logger_insert(self, mock_build, mock_flasher, mocked_logger, mock_logman): mocked_logger_for_flasher = mock.MagicMock() mocked_logger.return_value = mocked_logger_for_flasher dut = DutMbed(port="test", config={"allocated": {"target_id": "thing"}, "application": "thing"}) dut.flash("this_is_not_a_binary") mock_flasher.assert_called_with(logger=mocked_logger_for_flasher) @mock.patch("icetea_lib.DeviceConnectors.Dut.LogManager") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.get_external_logger") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.Flash") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.Build") def test_flash_build_init_not_implemented(self, mock_build, mock_flasher, mocked_logger, mock_logman): mock_build.init = mock.MagicMock(side_effect=[NotImplementedError]) mocked_logger_for_flasher = mock.MagicMock() mocked_logger.return_value = mocked_logger_for_flasher dut = DutMbed(port="test", config={"allocated": {"target_id": "thing"}, "application": "thing"}) with self.assertRaises(DutConnectionError): dut.flash("try") @mock.patch("icetea_lib.DeviceConnectors.Dut.LogManager") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.get_external_logger") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.Flash") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.Build") def test_flash_build_get_file_fail(self, mock_build, mock_flasher, mocked_logger, mock_logman): mock_build_object = mock.MagicMock() mock_build_object.get_file = mock.MagicMock( side_effect=[False, "Thisbin"]) mock_build.init = mock.MagicMock(return_value=mock_build_object) mocked_logger_for_flasher = mock.MagicMock() mocked_logger.return_value = mocked_logger_for_flasher dut = DutMbed(port="test", config={"allocated": {"target_id": "thing"}, "application": "thing"}) with self.assertRaises(DutConnectionError): dut.flash("try") @mock.patch("icetea_lib.DeviceConnectors.Dut.LogManager") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.get_external_logger") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.Flash") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.Build") def test_flash_fails(self, mock_build, mock_flasher, mocked_logger, mock_logman): mock_build_object = mock.MagicMock() mock_build_object.get_file = mock.MagicMock(return_value="Thisbin") mock_build.init = mock.MagicMock(return_value=mock_build_object) mocked_logger_for_flasher = mock.MagicMock() mocked_logger.return_value = mocked_logger_for_flasher mock_flasher_object = mock.MagicMock() mock_flasher.return_value = mock_flasher_object mock_flasher_object.flash = mock.MagicMock() mock_flasher_object.flash.side_effect = [ NotImplementedError, SyntaxError, 1] if FlashError is not None: mock_flasher_object.flash.side_effect = [NotImplementedError, SyntaxError, 1, FlashError("Error", 10)] dut = DutMbed(port="test", config={"allocated": {"target_id": "thing"}, "application": "thing"}) with self.assertRaises(DutConnectionError): dut.flash("try") with self.assertRaises(DutConnectionError): dut.flash("try2") self.assertFalse(dut.flash("try3")) if FlashError is not None: with self.assertRaises(DutConnectionError): dut.flash("try4") @mock.patch("icetea_lib.DeviceConnectors.Dut.LogManager") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.get_external_logger") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.Flash") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.Build") def test_flash_skip_flash(self, mock_build, mock_flasher, mocked_logger, mock_logman): mock_build_object = mock.MagicMock() mock_build_object.get_file = mock.MagicMock(return_value="Thisbin") mock_build.init = mock.MagicMock(return_value=mock_build_object) mocked_logger_for_flasher = mock.MagicMock() mocked_logger.return_value = mocked_logger_for_flasher mock_flasher_object = mock.MagicMock() mock_flasher.return_value = mock_flasher_object mock_flasher_object.flash = mock.MagicMock() mock_flasher_object.flash.return_value = 0 dut = DutMbed(port="test", config={"allocated": {"target_id": "thing"}, "application": "thing"}) self.assertTrue(dut.flash("try")) self.assertTrue(dut.flash("try")) self.assertTrue(dut.flash("try")) self.assertEqual(mock_flasher_object.flash.call_count, 1) self.assertTrue(dut.flash("try", forceflash=True)) self.assertEqual(mock_flasher_object.flash.call_count, 2)
class DutMbedTestcase(unittest.TestCase): @mock.patch("icetea_lib.DeviceConnectors.Dut.LogManager") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.get_external_logger") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.Flash") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.Build") def test_flasher_logger_insert(self, mock_build, mock_flasher, mocked_logger, mock_logman): pass @mock.patch("icetea_lib.DeviceConnectors.Dut.LogManager") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.get_external_logger") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.Flash") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.Build") def test_flash_build_init_not_implemented(self, mock_build, mock_flasher, mocked_logger, mock_logman): pass @mock.patch("icetea_lib.DeviceConnectors.Dut.LogManager") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.get_external_logger") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.Flash") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.Build") def test_flash_build_get_file_fail(self, mock_build, mock_flasher, mocked_logger, mock_logman): pass @mock.patch("icetea_lib.DeviceConnectors.Dut.LogManager") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.get_external_logger") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.Flash") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.Build") def test_flash_fails(self, mock_build, mock_flasher, mocked_logger, mock_logman): pass @mock.patch("icetea_lib.DeviceConnectors.Dut.LogManager") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.get_external_logger") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.Flash") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutMbed.Build") def test_flash_skip_flash(self, mock_build, mock_flasher, mocked_logger, mock_logman): pass
26
0
14
0
14
0
1
0
1
4
2
0
5
0
5
77
95
5
90
28
62
0
61
21
55
3
2
2
7
2,101
ARMmbed/icetea
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ARMmbed_icetea/icetea_lib/Plugin/plugins/plugin_tests/test_dutserial.py
icetea_lib.Plugin.plugins.plugin_tests.test_dutserial.DutSerialTestcase
class DutSerialTestcase(unittest.TestCase): def test_properties(self, mock_logger): ds = DutSerial() self.assertFalse(ds.ch_mode) ds.ch_mode = True self.assertTrue(ds.ch_mode) self.assertEqual(ds.ch_mode_chunk_size, 1) ds.ch_mode_chunk_size = 2 self.assertEqual(ds.ch_mode_chunk_size, 2) self.assertEqual(ds.ch_mode_ch_delay, 0.01) ds.ch_mode_ch_delay = 0.02 self.assertEqual(ds.ch_mode_ch_delay, 0.02) self.assertEqual(ds.ch_mode_start_delay, 0) ds.ch_mode_start_delay = 1 self.assertEqual(ds.ch_mode_start_delay, 1) self.assertEqual(ds.serial_baudrate, 460800) ds.serial_baudrate = 9600 self.assertEqual(ds.serial_baudrate, 9600) self.assertEqual(ds.serial_timeout, 0.01) ds.serial_timeout = 0.02 self.assertEqual(ds.serial_timeout, 0.02) self.assertFalse(ds.serial_xonxoff) ds.serial_xonxoff = True self.assertTrue(ds.serial_xonxoff) self.assertFalse(ds.serial_rtscts) ds.serial_rtscts = True self.assertTrue(ds.serial_rtscts) def test_get_resource_id(self, mock_logger): ds = DutSerial( config={"allocated": {"target_id": "test"}, "application": {}}) self.assertEqual(ds.get_resource_id(), "test") def test_get_info(self, mock_logger): ds = DutSerial() info = ds.get_info() self.assertTrue(isinstance(info, DutInformation)) def test_flash(self, mock_logger): ds = DutSerial() self.assertTrue(ds.flash()) @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutSerial.EnhancedSerial") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutSerial.Thread") def test_open_connection(self, mock_thread, mock_es, mock_logger): ds = DutSerial() ds.readthread = 1 ds.params = mock.MagicMock() type(ds.params).reset = mock.PropertyMock(return_value=False) with self.assertRaises(DutConnectionError): ds.open_connection() ds.readthread = None mock_es_2 = mock.MagicMock() mock_es_2.flushInput = mock.MagicMock( side_effect=[SerialException, ValueError, 1]) mock_es.return_value = mock_es_2 with self.assertRaises(DutConnectionError): ds.open_connection() with self.assertRaises(ValueError): ds.open_connection() ds.open_connection() mock_thread.assert_called_once() def test_prepare_connection_close(self, mock_logger): ds = DutSerial() with mock.patch.object(ds, "init_cli_human") as mock_init_cli_human: with mock.patch.object(ds, "stop") as mock_stop: ds.prepare_connection_close() mock_init_cli_human.assert_called_once() mock_stop.assert_called_once() def test_close_connection(self, mock_logger): ds = DutSerial() mocked_port = mock.MagicMock() mocked_port.close = mock.MagicMock() ds.port = mocked_port with mock.patch.object(ds, "stop") as mock_stop: ds.close_connection() mock_stop.assert_called_once() mocked_port.close.assert_called_once() self.assertFalse(ds.port) @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutSerial.time") def test_reset(self, mocked_time, mock_logger): ds = DutSerial() mock_port = mock.MagicMock() mock_port.safe_sendBreak = mock.MagicMock(return_value=True) mocked_time.sleep = mock.MagicMock() ds.port = mock_port self.assertIsNone(ds.reset()) def test_writeline(self, mock_logger): ds = DutSerial() mock_port = mock.MagicMock() mock_port.write = mock.MagicMock( side_effect=[1, 1, 1, 1, SerialException]) ds.port = mock_port ds.ch_mode = False ds.writeline("data") mock_port.write.assert_called_once_with("data\n".encode()) mock_port.reset_mock() ds.ch_mode = True ds.ch_mode_chunk_size = 2 ds.writeline("data") mock_port.write.assert_has_calls([mock.call("da".encode()), mock.call("ta".encode()), mock.call("\n".encode())]) with self.assertRaises(RuntimeError): ds.writeline("data") def test_readline(self, mock_logger): ds = DutSerial() ds.input_queue.append("test1") read = ds.readline() self.assertEqual(read, "test1") self.assertIsNone(ds.readline()) def test_peek(self, mock_logger): ds = DutSerial() mocked_port = mock.MagicMock() mocked_port.peek = mock.MagicMock(return_value="test") ds.port = mocked_port self.assertEqual(ds.peek(), "test") mocked_port.peek.assert_called_once() ds.port = None self.assertEqual(ds.peek(), "")
class DutSerialTestcase(unittest.TestCase): def test_properties(self, mock_logger): pass def test_get_resource_id(self, mock_logger): pass def test_get_info(self, mock_logger): pass def test_flash(self, mock_logger): pass @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutSerial.EnhancedSerial") @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutSerial.Thread") def test_open_connection(self, mock_thread, mock_es, mock_logger): pass def test_prepare_connection_close(self, mock_logger): pass def test_close_connection(self, mock_logger): pass @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.DutSerial.time") def test_reset(self, mocked_time, mock_logger): pass def test_writeline(self, mock_logger): pass def test_readline(self, mock_logger): pass def test_peek(self, mock_logger): pass
15
0
10
1
10
0
1
0
1
6
3
0
11
0
11
83
130
18
112
35
97
0
108
30
96
1
2
2
11
2,102
ARMmbed/icetea
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ARMmbed_icetea/icetea_lib/Plugin/plugins/plugin_tests/test_httpapi.py
icetea_lib.Plugin.plugins.plugin_tests.test_httpapi.APITestCase
class APITestCase(unittest.TestCase): def setUp(self): self.http = None self.host = "http://somesite.com" @mock.patch("icetea_lib.tools.HTTP.Api.HttpApi.get", side_effect=iter([ MockedRequestsResponse( status_code=200), MockedRequestsResponse(status_code=404), MockedRequestsResponse(status_code=404)])) @mock.patch("icetea_lib.tools.HTTP.Api.HttpApi.put", side_effect=iter([ MockedRequestsResponse( status_code=200), MockedRequestsResponse(status_code=404), MockedRequestsResponse(status_code=404)])) @mock.patch("icetea_lib.tools.HTTP.Api.HttpApi.post", side_effect=iter([ MockedRequestsResponse( status_code=200), MockedRequestsResponse(status_code=404), MockedRequestsResponse(status_code=404)])) @mock.patch("icetea_lib.tools.HTTP.Api.HttpApi.delete", side_effect=iter([ MockedRequestsResponse( status_code=200), MockedRequestsResponse(status_code=404), MockedRequestsResponse(status_code=404)])) @mock.patch("icetea_lib.tools.HTTP.Api.HttpApi.patch", side_effect=iter([ MockedRequestsResponse( status_code=200), MockedRequestsResponse(status_code=404), MockedRequestsResponse(status_code=404)])) def test_tcapi(self, mock_patch, mock_delete, mock_post, mock_put, mock_get): self.http = tc_api(host=self.host, headers=None, cert=None, logger=None) self.assertEquals(self.http.get("/").status_code, 200) self.assertEquals(self.http.get("/", expected=200, raiseException=False).status_code, 404) with self.assertRaises(TestStepFail): self.http.get("/", expected=200, raiseException=True) path = "/test" data = {"testkey1": "testvalue1"} self.assertEquals(self.http.put(path, data).status_code, 200) self.assertEquals(self.http.put(path, data, expected=200, raiseException=False).status_code, 404) with self.assertRaises(TestStepFail): self.http.put(path, data, expected=200, raiseException=True) self.assertEquals(self.http.post(path, json=data).status_code, 200) self.assertEquals(self.http.post(path, json=data, expected=200, raiseException=False).status_code, 404) with self.assertRaises(TestStepFail): self.http.post(path, json=data, expected=200, raiseException=True) self.assertEquals(self.http.delete(path).status_code, 200) self.assertEquals(self.http.delete(path, expected=200, raiseException=False).status_code, 404) with self.assertRaises(TestStepFail): self.http.delete(path, expected=200, raiseException=True) self.assertEquals(self.http.patch(path, data=data).status_code, 200) self.assertEquals(self.http.patch(path, data=data, expected=200, raiseException=False).status_code, 404) with self.assertRaises(TestStepFail): self.http.patch(path, data=data, expected=200, raiseException=True)
class APITestCase(unittest.TestCase): def setUp(self): pass @mock.patch("icetea_lib.tools.HTTP.Api.HttpApi.get", side_effect=iter([ MockedRequestsResponse( status_code=200), MockedRequestsResponse(status_code=404), MockedRequestsResponse(status_code=404)])) @mock.patch("icetea_lib.tools.HTTP.Api.HttpApi.put", side_effect=iter([ MockedRequestsResponse( status_code=200), MockedRequestsResponse(status_code=404), MockedRequestsResponse(status_code=404)])) @mock.patch("icetea_lib.tools.HTTP.Api.HttpApi.post", side_effect=iter([ MockedRequestsResponse( status_code=200), MockedRequestsResponse(status_code=404), MockedRequestsResponse(status_code=404)])) @mock.patch("icetea_lib.tools.HTTP.Api.HttpApi.delete", side_effect=iter([ MockedRequestsResponse( status_code=200), MockedRequestsResponse(status_code=404), MockedRequestsResponse(status_code=404)])) @mock.patch("icetea_lib.tools.HTTP.Api.HttpApi.patch", side_effect=iter([ MockedRequestsResponse( status_code=200), MockedRequestsResponse(status_code=404), MockedRequestsResponse(status_code=404)])) def test_tcapi(self, mock_patch, mock_delete, mock_post, mock_put, mock_get): pass
8
0
18
2
16
0
1
0
1
1
1
0
2
2
2
74
53
6
47
10
29
0
28
7
25
1
2
1
2
2,103
ARMmbed/icetea
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ARMmbed_icetea/icetea_lib/Plugin/plugins/plugin_tests/test_localallocator.py
icetea_lib.Plugin.plugins.plugin_tests.test_localallocator.TestVerify
class TestVerify(unittest.TestCase): def setUp(self): self.nulllogger = logging.getLogger("test") self.nulllogger.addHandler(logging.NullHandler()) def test_init_with_no_logger(self, mock_logging, mock_dutdetection): dutdetect = mock.Mock() mock_dutdetection.return_value = dutdetect dutdetect.get_available_devices = mock.MagicMock(return_value=None) mock_logger = mock.Mock() mock_logging.get_logger = mock.MagicMock(return_value=mock_logger) mock_logging.NullHandler = mock.MagicMock() LocalAllocator() mock_dutdetection.assert_not_called() dutdetect.get_available_devices.assert_not_called() mock_logging.assert_called_once_with("LocalAllocator", "LAL") def test_can_allocate_success(self, mock_logging, mock_dutdetection): alloc = LocalAllocator() data1 = {"type": "hardware"} self.assertTrue(alloc.can_allocate(data1)) def test_can_allocate_unknown_type(self, mock_logging, mock_dutdetection): dutdetect = mock.Mock() mock_dutdetection.return_value = dutdetect dutdetect.get_available_devices = mock.MagicMock(return_value=None) alloc = LocalAllocator() data_unknown_type = {"type": "unknown"} self.assertFalse(alloc.can_allocate(data_unknown_type)) mock_dutdetection.assert_not_called() dutdetect.get_available_devices.assert_not_called() data_unknown_type = {"type": None} self.assertFalse(alloc.can_allocate(data_unknown_type)) def test_can_allocate_missing_type(self, mock_logging, mock_dutdetection): alloc = LocalAllocator() data_no_type = {"notype": None} self.assertFalse(alloc.can_allocate(data_no_type)) def test_allocate_raises_on_invalid_dut_format(self, mock_logging, mock_dutdetection): alloc = LocalAllocator() mfunc = mock.MagicMock() mfunc.get_dut_configuration = mock.MagicMock() mfunc.get_dut_configuration.return_value = "Not a list" self.assertRaises(AllocationError, alloc.allocate, mfunc) def test_allocate_raises_devices_not_available(self, mock_logging, mock_dutdetection): detected = [1] mock_dutdetection.get_available_devices = mock.MagicMock( return_value=detected) alloc = LocalAllocator() mfunc = mock.MagicMock() mfunc.get_dut_configuration = mock.MagicMock() mfunc.get_dut_configuration.return_value = [ {"type": "hardware"}, {"type": "hardware"}] with self.assertRaises(AllocationError): alloc.allocate(mfunc) def test_internal_allocate_no_type_raises(self, mock_logging, mock_dutdetection): alloc = LocalAllocator() data = {"notype": None} self.assertRaises(KeyError, alloc._allocate, data) def test_internal_allocate_non_hardware_types_success(self, mock_logging, mock_dutdetection): dutdetect = mock.Mock() mock_dutdetection.return_value = dutdetect dutdetect.get_available_devices = mock.MagicMock(return_value=None) alloc = LocalAllocator() dut = ResourceRequirements({"type": "process"}) mfunc = mock.MagicMock() mfunc.get_dut_configuration = mock.MagicMock() mfunc.get_dut_configuration.return_value = [dut] self.assertTrue(alloc.allocate(mfunc)) mock_dutdetection.assert_not_called() dutdetect.get_available_devices.assert_not_called() def test_internal_allocate_non_hardware_types_success_without_dutfactory(self, mock_logging, mock_dutdetection): alloc = LocalAllocator() dut = ResourceRequirements({"type": "process"}) mfunc = mock.MagicMock() mfunc.get_dut_configuration = mock.MagicMock() mfunc.get_dut_configuration.return_value = [dut] self.assertTrue(alloc.allocate(mfunc)) def test_internal_allocate_hardware_platform_no_devices_raises_error(self, mock_logging, mock_dutdetection): dutdetect = mock.Mock() mock_dutdetection.return_value = dutdetect dutdetect.get_available_devices = mock.MagicMock(return_value=None) alloc = LocalAllocator() self.assertRaises(AllocationError, alloc._allocate, ResourceRequirements({"type": "hardware"})) def test_inter_alloc_suc_one_hardware_device_with_undef_allowed_platf(self, mock_logging, mock_dutdetection): # Allocation should succeed if no allowed_platform defined in dut configuration, # and devices are available dutdetect = mock.Mock() # DutDetection instance mock mock_dutdetection.return_value = dutdetect mock_dutdetection.is_port_usable = mock.MagicMock(return_value=True) device = {"state": "unknown", "platform_name": "K64F", "target_id": "ABCDEFG12345", "serial_port": "/dev/serial"} dutdetect.get_available_devices = mock.MagicMock(return_value=[device]) alloc = LocalAllocator() dut = ResourceRequirements({"type": "hardware"}) mfunc = mock.MagicMock() mfunc.get_dut_configuration = mock.MagicMock() mfunc.get_dut_configuration.return_value = [dut] self.assertEqual(len(alloc.allocate(mfunc)), 1) dutdetect.get_available_devices.assert_called_once_with() # Test correct format of resulting dut configuration mock_dutdetection.is_port_usable.assert_called_once_with( device["serial_port"]) def test_inter_alloc_suc_w_two_hw_allocatable_dev_one_has_unusable_serial(self, mock_logging, mock_dutdetection): # Test with two devices, both are allocatable, but the serial port for first is unusable dutdetect = mock.Mock() # DutDetection instance mock mock_dutdetection.return_value = dutdetect mock_dutdetection.is_port_usable = mock.MagicMock( side_effect=iter([False, True])) devices = [{"state": "unknown", "platform_name": "K64F", "target_id": "ABCDEFG12345", "serial_port": "/dev/serial"}, {"state": "unknown", "platform_name": "K64F", "target_id": "ABCDEFG12345", "serial_port": "/dev/serial"}] dutdetect.get_available_devices = mock.MagicMock(return_value=devices) alloc = LocalAllocator() dut = ResourceRequirements({"type": "hardware"}) mfunc = mock.MagicMock() mfunc.get_dut_configuration = mock.MagicMock() mfunc.get_dut_configuration.return_value = [dut] self.assertEqual(len(alloc.allocate(mfunc)), 1) self.assertEqual(mock_dutdetection.is_port_usable.call_count, 2) def test_inter_alloc_suc_w_two_hw_allocatable_dev_one_has_nonmatch_platf(self, mock_logging, mock_dutdetection): # Test with two devices, both are allocatable, but the serial port for first is unusable dutdetect = mock.Mock() # DutDetection instance mock mock_dutdetection.return_value = dutdetect mock_dutdetection.is_port_usable = mock.MagicMock(return_value=True) dut = ResourceRequirements( {"type": "hardware", "allowed_platforms": ["K64F"]}) devices = [{"state": "unknown", "platform_name": "unknown", "target_id": "ABCDEFG12345", "serial_port": "/dev/serial1"}, {"state": "unknown", "platform_name": "K64F", "target_id": "ABCDEFG12345", "serial_port": "/dev/serial2"}] dutdetect.get_available_devices = mock.MagicMock(return_value=devices) alloc = LocalAllocator() # Test correct format of resulting dut configuration mfunc = mock.MagicMock() mfunc.get_dut_configuration = mock.MagicMock() mfunc.get_dut_configuration.return_value = [dut] self.assertEqual(len(alloc.allocate(mfunc)), 1) resultingdut = dut resultingdevice = devices[1] resultingdevice["state"] = "allocated" resultingdut.set("allocated", resultingdevice) mock_dutdetection.is_port_usable.assert_called_once_with( resultingdevice["serial_port"]) def test_inter_alloc_suc_w_two_hw_allocatabl_dev_w_match_platf_one_alloc(self, mock_logging, mock_dutdetection): # Test with two devices, both are allocatable, but the serial port for first is unusable dutdetect = mock.Mock() # DutDetection instance mock mock_dutdetection.return_value = dutdetect mock_dutdetection.is_port_usable = mock.MagicMock(return_value=True) dut = ResourceRequirements( {"type": "hardware", "allowed_platforms": ["K64F"]}) devices = [{"state": "allocated", "platform_name": "K64F", "target_id": "ABCDEFG12345", "serial_port": "/dev/serial1"}, {"state": "unknown", "platform_name": "K64F", "target_id": "ABCDEFG12345", "serial_port": "/dev/serial2"}] dutdetect.get_available_devices = mock.MagicMock(return_value=devices) alloc = LocalAllocator() # Test correct format of resulting dut configuration mfunc = mock.MagicMock() mfunc.get_dut_configuration = mock.MagicMock() mfunc.get_dut_configuration.return_value = [dut] self.assertEqual(len(alloc.allocate(mfunc)), 1) resultingdut = dut resultingdevice = devices[1] resultingdevice["state"] = "allocated" resultingdut.set("allocated", resultingdevice) mock_dutdetection.is_port_usable.assert_called_once_with( resultingdevice["serial_port"]) def test_alloc_twice_suc_when_two_dev_available(self, mock_logging, mock_dutdetection): # Test with two devices, both are allocatable, but the serial port for first is unusable dutdetect = mock.Mock() # DutDetection instance mock mock_dutdetection.return_value = dutdetect mock_dutdetection.is_port_usable = mock.MagicMock(return_value=True) devices = [{"state": "unknown", "platform_name": "K64F", "target_id": "1234", "serial_port": "/dev/serial1"}, {"state": "unknown", "platform_name": "K64F", "target_id": "5678", "serial_port": "/dev/serial2"}] dutdetect.get_available_devices = mock.MagicMock(return_value=devices) alloc = LocalAllocator() duts = [ResourceRequirements({"type": "hardware", "allowed_platforms": ["K64F"]}), ResourceRequirements({"type": "hardware", "allowed_platforms": ["K64F"]})] mfunc = mock.MagicMock() mfunc.get_dut_configuration = mock.MagicMock() mfunc.get_dut_configuration.return_value = duts self.assertEqual(len(alloc.allocate(mfunc)), 2) # Result of first dut allocation resultingdut1 = duts[0] resultingdevice1 = devices[0] resultingdevice1["state"] = "allocated" resultingdut1.set("allocated", resultingdevice1) # Result of second dut allocation resultingdut2 = duts[1] resultingdevice2 = devices[1] resultingdevice2["state"] = "allocated" resultingdut2.set("allocated", resultingdevice2) mock_dutdetection.is_port_usable.assert_has_calls( [mock.call(resultingdevice1["serial_port"]), mock.call(resultingdevice2["serial_port"])]) def test_alloc_fail_w_two_hw_allocatable_dev_both_already_allocated(self, mock_logging, mock_dutdetection): # Allocation should raise AllocationError if no unallocated devices dutdetect = mock.Mock() # DutDetection instance mock mock_dutdetection.return_value = dutdetect mfunc = mock.MagicMock() mfunc.get_dut_configuration = mock.MagicMock() mfunc.get_dut_configuration.return_value = [ ResourceRequirements({"type": "hardware"})] devices = [{"state": "allocated", "platform_name": "K64F", "target_id": "ABCDEFG12345", "serial_port": "/dev/serial"}, {"state": "allocated", "platform_name": "K64F", "target_id": "ABCDEFG12345", "serial_port": "/dev/serial"}] dutdetect.get_available_devices = mock.MagicMock(return_value=devices) alloc = LocalAllocator() self.assertRaises(AllocationError, alloc.allocate, mfunc) def test_local_allocator_release(self, mock_logging, mock_dutdetection): alloc = LocalAllocator() alloc.release() @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.LocalAllocator.DutConsole") def test_init_console_dut(self, mock_dc, mock_logging, mock_dutdetection): conf = {} conf["subtype"] = "console" conf["application"] = "stuff" con_list = AllocationContextList(self.nulllogger) init_process_dut(con_list, conf, 1, mock.MagicMock()) conf["subtype"] = "other" con_list = AllocationContextList(self.nulllogger) with self.assertRaises(ResourceInitError): self.assertIsNone(init_process_dut( con_list, conf, 1, mock.MagicMock())) @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.LocalAllocator.DutMbed") def test_init_mbed_dut(self, mock_ds, mock_logging, mock_dutdetection): conf = {"allocated": {"serial_port": "port", "baud_rate": 115200, "platform_name": "test", "target_id": "id"}, "application": {"bin": "binary"}} args = mock.MagicMock() rtscts = mock.PropertyMock(return_value=True) s_xonxoff = mock.PropertyMock(return_value=True) s_timeout = mock.PropertyMock(return_value=True) s_ch_size = mock.PropertyMock(return_value=1) s_ch_delay = mock.PropertyMock(return_value=True) skip_flash = mock.PropertyMock(return_value=False) type(args).skip_flash = skip_flash type(args).serial_xonxoff = s_xonxoff type(args).serial_rtscts = rtscts type(args).serial_timeout = s_timeout type(args).serial_ch_size = s_ch_size type(args).ch_mode_ch_delay = s_ch_delay # Setup mocked dut dut1 = mock.MagicMock() dut1.close_dut = mock.MagicMock() dut1.close_connection = mock.MagicMock() dut1.flash = mock.MagicMock() dut1.flash.side_effect = [True, False] dut1.getInfo = mock.MagicMock(return_value="test") type(dut1).index = mock.PropertyMock() con_list = AllocationContextList(self.nulllogger) with mock.patch.object(con_list, "check_flashing_need") as mock_cfn: mock_cfn = mock.MagicMock() mock_cfn.return_value = True mock_ds.return_value = dut1 init_mbed_dut(con_list, conf, 1, args) with self.assertRaises(ResourceInitError): init_mbed_dut(con_list, conf, 1, args) dut1.close_dut.assert_called() dut1.close_connection.assert_called() @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.LocalAllocator.DutMbed") def test_init_mbed_dut_skip_flash(self, mock_ds, mock_logging, mock_dutdetection): conf = {"allocated": {"serial_port": "port", "baud_rate": 115200, "platform_name": "test", "target_id": "id"}, "application": {"bin": "binary"}} args = mock.MagicMock() rtscts = mock.PropertyMock(return_value=True) s_xonxoff = mock.PropertyMock(return_value=True) s_timeout = mock.PropertyMock(return_value=True) s_ch_size = mock.PropertyMock(return_value=1) s_ch_delay = mock.PropertyMock(return_value=True) skip_flash = mock.PropertyMock(return_value=True) type(args).skip_flash = skip_flash type(args).serial_xonxoff = s_xonxoff type(args).serial_rtscts = rtscts type(args).serial_timeout = s_timeout type(args).serial_ch_size = s_ch_size type(args).ch_mode_ch_delay = s_ch_delay # Setup mocked dut dut1 = mock.MagicMock() dut1.close_dut = mock.MagicMock() dut1.close_connection = mock.MagicMock() dut1.flash = mock.MagicMock() dut1.flash.side_effect = [True, False] dut1.getInfo = mock.MagicMock(return_value="test") type(dut1).index = mock.PropertyMock() con_list = AllocationContextList(self.nulllogger) with mock.patch.object(con_list, "check_flashing_need") as mock_cfn: mock_cfn = mock.MagicMock() mock_cfn.return_value = True mock_ds.return_value = dut1 init_mbed_dut(con_list, conf, 1, args) dut1.flash.assert_not_called() @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.LocalAllocator.DutMbed") def test_init_mbed_dut_nondefault_baud_rate(self, mock_ds, mock_logging, mock_dutdetection): conf = {"allocated": {"serial_port": "port", "baud_rate": 115200, "platform_name": "test", "target_id": "id"}, "application": {"bin": "binary", "baudrate": 9600}} args = mock.MagicMock() rtscts = mock.PropertyMock(return_value=True) s_xonxoff = mock.PropertyMock(return_value=True) s_timeout = mock.PropertyMock(return_value=True) s_ch_size = mock.PropertyMock(return_value=1) s_ch_delay = mock.PropertyMock(return_value=True) skip_flash = mock.PropertyMock(return_value=False) type(args).skip_flash = skip_flash type(args).baudrate = mock.PropertyMock(return_value=False) type(args).serial_xonxoff = s_xonxoff type(args).serial_rtscts = rtscts type(args).serial_timeout = s_timeout type(args).serial_ch_size = s_ch_size type(args).ch_mode_ch_delay = s_ch_delay # Setup mocked dut dut1 = mock.MagicMock() dut1.close_dut = mock.MagicMock() dut1.closeConnection = mock.MagicMock() dut1.flash = mock.MagicMock() dut1.flash.side_effect = [True, False] dut1.getInfo = mock.MagicMock(return_value="test") type(dut1).index = mock.PropertyMock() con_list = AllocationContextList(self.nulllogger) with mock.patch.object(con_list, "check_flashing_need") as mock_cfn: mock_cfn = mock.MagicMock() mock_cfn.return_value = True mock_ds.return_value = dut1 init_mbed_dut(con_list, conf, 1, args) mock_ds.assert_called_once_with(baudrate=9600, ch_mode_config={'ch_mode_ch_delay': True, 'ch_mode': True, 'ch_mode_chunk_size': 1}, config={'application': {'bin': 'binary', 'baudrate': 9600}, 'allocated': {'baud_rate': 115200, 'platform_name': 'test', 'target_id': 'id', 'serial_port': 'port'}}, name='D1', port='port', serial_config={'serial_timeout': True, 'serial_rtscts': True}, params=args)
class TestVerify(unittest.TestCase): def setUp(self): pass def test_init_with_no_logger(self, mock_logging, mock_dutdetection): pass def test_can_allocate_success(self, mock_logging, mock_dutdetection): pass def test_can_allocate_unknown_type(self, mock_logging, mock_dutdetection): pass def test_can_allocate_missing_type(self, mock_logging, mock_dutdetection): pass def test_allocate_raises_on_invalid_dut_format(self, mock_logging, mock_dutdetection): pass def test_allocate_raises_devices_not_available(self, mock_logging, mock_dutdetection): pass def test_internal_allocate_no_type_raises(self, mock_logging, mock_dutdetection): pass def test_internal_allocate_non_hardware_types_success(self, mock_logging, mock_dutdetection): pass def test_internal_allocate_non_hardware_types_success_without_dutfactory(self, mock_logging, mock_dutdetection): pass def test_internal_allocate_hardware_platform_no_devices_raises_error(self, mock_logging, mock_dutdetection): pass def test_inter_alloc_suc_one_hardware_device_with_undef_allowed_platf(self, mock_logging, mock_dutdetection): pass def test_inter_alloc_suc_w_two_hw_allocatable_dev_one_has_unusable_serial(self, mock_logging, mock_dutdetection): pass def test_inter_alloc_suc_w_two_hw_allocatable_dev_one_has_nonmatch_platf(self, mock_logging, mock_dutdetection): pass def test_inter_alloc_suc_w_two_hw_allocatabl_dev_w_match_platf_one_alloc(self, mock_logging, mock_dutdetection): pass def test_alloc_twice_suc_when_two_dev_available(self, mock_logging, mock_dutdetection): pass def test_alloc_fail_w_two_hw_allocatable_dev_both_already_allocated(self, mock_logging, mock_dutdetection): pass def test_local_allocator_release(self, mock_logging, mock_dutdetection): pass @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.LocalAllocator.DutConsole") def test_init_console_dut(self, mock_dc, mock_logging, mock_dutdetection): pass @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.LocalAllocator.DutMbed") def test_init_mbed_dut(self, mock_ds, mock_logging, mock_dutdetection): pass @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.LocalAllocator.DutMbed") def test_init_mbed_dut_skip_flash(self, mock_ds, mock_logging, mock_dutdetection): pass @mock.patch("icetea_lib.Plugin.plugins.LocalAllocator.LocalAllocator.DutMbed") def test_init_mbed_dut_nondefault_baud_rate(self, mock_ds, mock_logging, mock_dutdetection): pass
27
0
17
2
15
1
1
0.06
1
8
5
0
22
1
22
94
397
57
325
133
291
21
274
119
251
1
2
2
22
2,104
ARMmbed/icetea
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ARMmbed_icetea/icetea_lib/TestBench/BenchApi.py
icetea_lib.TestBench.BenchApi.BenchApi
class BenchApi(object): """ BenchApi class. Implements methods that provide access to the implementations contained in the other TestBench modules. """ def __init__(self, **kwargs): super(BenchApi, self).__init__() self._arguments = ArgsHandler() self._logger = Logger() self._configurations = Configurations(args=self._arguments.args, logger=self.logger, **kwargs) self._resources = ResourceFunctions( self._arguments.args, self.logger, self._configurations) self._plugins = Plugins(self.logger, self.env, self._arguments.args, self._configurations.config) self._resultfunctions = Results(self.logger, self._resources, self._configurations, self._arguments.args) self._benchfunctions = BenchFunctions(self.resource_configuration, self._resources, self._configurations) self._commands = Commands(self.logger, self._plugins, self._resources, self._arguments.args, self._benchfunctions) self._nwsniffer = NetworkSniffer(self._resources, self._configurations, self._arguments.args, self.logger) def _init(self): """ Initialize internal class instances. """ self._logger.init_logger(self._configurations.test_name, self.args.verbose, self.args.silent, self.args.color, self.args.disable_log_truncate) self._benchfunctions.init(logger=self.logger) self._configurations.init(self.logger) self._resources.init(self._commands, self.logger) self._plugins.init(self, self.logger) self._resultfunctions.init(self.logger) self._nwsniffer.init(self.logger) self._commands.init(self.logger) self.__wrap_obsoleted_functions() def get_logger(self): """ Get logger function. Calls Logger.get_logger(). :return: BenchLoggerAdapter """ return self._logger.get_logger() @property def args(self): """ Gets known args from ArgsHandler. :return: Namespace """ return self._arguments.args @args.setter def args(self, value): """ Setter for known args. """ self._arguments.args = value @property def unknown(self): """ Gets unknown args from ArgsHandler. """ return self._arguments.unknown @unknown.setter def unknown(self, value): """ Setter for unknown args. """ self._arguments.unknown = value @property def logger(self): """ :return: Logger from Logger. BenchLoggerAdapter usually. """ return self._logger.get_logger() @logger.setter def logger(self, value): """ Sets logger. """ self._logger.set_logger(value) @property def test_name(self): """ Returns test_name from Configurations. """ return self._configurations.test_name @property def config(self): """ :return: Configurations.config """ return self._configurations.config @config.setter def config(self, value): """ Sets Configurations.config. """ self._configurations.config = value @property def env(self): """ :return: Configurations.env """ return self._configurations.env def sync_cli(self, dut, generator_function=None, generator_function_args=None, retries=None, command_timeout=None): """ Synchronize cli for a dut using custom function. :param dut: Dut :param generator_function: callable :param generator_function_args: list of arguments for generator_function :param retries: int, if set to 0 will skip command entirely (for unit testing purposes) :param command_timeout: int :raises: TestStepError: if synchronization fails. :raises: AttributeError: if retries is set to 0, unit testing reasons. """ return self._commands.sync_cli(dut, generator_function, generator_function_args, retries, command_timeout) def is_hardware_in_use(self): """ :return: True if type is hardware """ return self._configurations.is_hardware_in_use() def get_platforms(self): """ Get list of dut platforms. :return: list """ return self._resources.get_platforms() def get_serialnumbers(self): """ Get list of dut serial numbers. :return: list """ return self._resources.get_serialnumbers() def get_test_component(self): """ Get test component. :return: string """ return self._configurations.get_test_component() def get_features_under_test(self): """ Get features tested by this test case. :return: list """ return self._configurations.get_features_under_test() def get_allowed_platforms(self): """ Return list of allowed platfroms from requirements. :return: list """ return self._configurations.get_allowed_platforms() def status(self): """ Get TC implementation status. :return: string or None """ return self._configurations.status() def type(self): """ Get test case type. :return: string or None """ return self._configurations.type() def subtype(self): """ Get test case subtype. :return: string or None """ return self._configurations.subtype() def get_config(self): """ Get test case configuration. :return: dict """ return self._configurations.get_config() def skip(self): """ Get skip value. :return: Boolean or None """ return self._configurations.skip() def skip_info(self): """ Get the entire skip dictionary. :return: dictionary or None """ return self._configurations.skip_info() def skip_reason(self): """ Get skip reason. :return: string """ return self._configurations.skip_reason() def get_tc_abspath(self, tc_file=None): """ Get path to test case. :param tc_file: name of the file. If None, tcdir used instead. :return: absolute path. """ return self._configurations.get_tc_abspath(tc_file) def set_config(self, config): """ Set the configuration for this test case. :param config: dictionary :return: Nothing """ return self._configurations.set_config(config) def check_skip(self): """ Check if tc should be skipped :return: Boolean """ return self._configurations.check_skip() def load_plugins(self): """ Initialize PluginManager and Load bench related plugins. :return: Nothing """ return self._plugins.load_plugins() def init_duts(self): """ Initialize Duts, and the network sniffer. :return: Nothing """ return self._resources.init_duts(self) def duts_release(self): """ Release Duts. :return: Nothing """ return self._resources.duts_release() @property def resource_configuration(self): """ Getter for __resource_configuration. :return: ResourceConfig """ return self._resources.resource_configuration @resource_configuration.setter def resource_configuration(self, value): """ Setter for __resource_configuration. :param value: ResourceConfig :return: Nothing """ self._resources.resource_configuration = value def dut_count(self): """ Getter for dut count from resource configuration. :return: int """ return self._resources.dut_count() def get_dut_count(self): """ Get dut count. :return: int """ return self._resources.get_dut_count() @property def resource_provider(self): """ Getter for __resource_provider :return: ResourceProvider """ return self._resources.resource_provider @property def duts(self): """ Get _duts. :return: list """ return self._resources.duts @duts.setter def duts(self, value): """ set a list as _duts. :param value: list :return: Nothing """ self._resources.duts = value def duts_iterator_all(self): """ Yield indexes and related duts. """ return self._resources.duts_iterator_all() def duts_iterator(self): """ Yield indexes and related duts that are for this test case. """ return self._resources.duts_iterator() def is_allowed_dut_index(self, dut_index): """ Check if dut_index is one of the duts for this test case. :param dut_index: int :return: Boolean """ return self._resources.is_allowed_dut_index(dut_index=dut_index) @property def dut_indexes(self): """ Get a list with dut indexes. :return: list """ return self._resources.dut_indexes def get_dut(self, k): """ Get dut object. :param k: index or nickname of dut. :return: Dut """ return self._resources.get_dut(k) def get_node_endpoint(self, endpoint_id): """ get NodeEndPoint object for dut endpoint_id. :param endpoint_id: nickname of dut :return: NodeEndPoint """ return self._resources.get_node_endpoint(endpoint_id, self) def is_my_dut_index(self, dut_index): """ :return: Boolean """ return self._resources.is_my_dut_index(dut_index) @property def dutinformations(self): """ Getter for DutInformation list. :return: list """ return self._resources.dutinformations @dutinformations.setter def dutinformations(self, value): """ Setter for dutinformations :param value: DutInformationList :return: Nothing """ self._resources.dutinformations = value def reset_dut(self, dut_index="*"): """ Reset dut k. :param dut_index: index of dut to reset. Default is *, which causes all duts to be reset. :return: Nothing """ return self._resources.reset_dut(dut_index) def get_dut_nick(self, dut_index): """ Get nick of dut index k. :param dut_index: index of dut :return: string """ return self._resources.get_dut_nick(dut_index) def get_dut_index(self, nick): """ Get index of dut with nickname nick. :param nick: string :return: integer > 1 """ return self._resources.get_dut_index(nick) def is_my_dut(self, k): """ :return: Boolean """ return self._resources.is_my_dut(k) @staticmethod def create_new_result(verdict, retcode, duration, input_data): """ Create a new Result object with data in function arguments. :param verdict: Verdict as string :param retcode: Return code as int :param duration: Duration as time :param input_data: Input data as dictionary :return: Result """ return Results.create_new_result(verdict, retcode, duration, input_data) def add_new_result(self, verdict, retcode, duration, input_data): """ Add a new Result to result object to the internal ResultList. :param verdict: Verdict as string :param retcode: Return code as int :param duration: Duration as time :param input_data: Input data as dict :return: Result """ return self._resultfunctions.add_new_result(verdict, retcode, duration, input_data) @property def results(self): """ Getter for internal _results variable. """ return self._resultfunctions.get_results() @results.setter def results(self, value): """ Call setter for internal ResultList. :param value: ResultList :return: Nothing """ self._resultfunctions.set_results(value) @property def retcode(self): """ Getter for return code. :return: int """ return self._resultfunctions.retcode @retcode.setter def retcode(self, value): """ Setter for retcode. :param value: int :return: Nothing """ self._resultfunctions.retcode = value def get_result(self, tc_file=None): """ Generate a Result object from this test case. :param tc_file: Location of test case file :return: Result """ return self._resultfunctions.get_result(tc_file) def append_result(self, tc_file=None): """ Append a new fully constructed Result to the internal ResultList. :param tc_file: Test case file path :return: Nothing """ return self._resultfunctions.append_result(tc_file) def set_failure(self, retcode, reason): """ Set internal state to reflect failure of test. :param retcode: return code :param reason: failure reason as string :return: Nothing """ return self._resultfunctions.set_failure(retcode, reason) def input_from_user(self, title=None): """ Input data from user. :param title: Title as string :return: stripped data from stdin. """ return self._benchfunctions.input_from_user(title) def open_node_terminal(self, k="*", wait=True): """ Open Putty (/or kitty if exists) :param k: number 1.<max duts> or '*' to open putty to all devices :param wait: wait while putty is closed before continue testing :return: Nothing """ return self._benchfunctions.open_node_terminal(k, wait) def delay(self, seconds): """ Sleep command. :param seconds: Amount of seconds to sleep. :return: Nothing """ return self._benchfunctions.delay(seconds) def verify_trace_skip_fail(self, k, expected_traces): """ Shortcut to set break_in_fail to False in verify_trace. :param k: nick or index of dut. :param expected_traces: Expected traces as a list or string :return: boolean """ return self._benchfunctions.verify_trace_skip_fail(k, expected_traces) def verify_trace(self, k, expected_traces, break_in_fail=True): """ Verify that traces expected_traces are found in dut traces. :param k: index or nick of dut whose traces are to be used. :param expected_traces: list of expected traces or string :param break_in_fail: Boolean, if True raise LookupError if search fails :return: boolean. :raises: LookupError if search fails. """ return self._benchfunctions.verify_trace(k, expected_traces, break_in_fail) def get_time(self): """ Get timestamp using time.time(). :return: timestamp """ return self._benchfunctions.get_time() @property def command(self): """ Alias for execute_command. :return: execute_command attribute reference. """ return self._commands.command def wait_for_async_response(self, cmd, async_resp): """ Wait for the given asynchronous response to be ready and then parse it. :param cmd: The asynchronous command that was sent to DUT. :param async_resp: The asynchronous response returned by the preceding command call. :return: CliResponse object """ return self._commands.wait_for_async_response(cmd, async_resp) def execute_command(self, k, cmd, # pylint: disable=invalid-name wait=True, timeout=50, expected_retcode=0, asynchronous=False, report_cmd_fail=True): """ Do Command request for DUT. If this fails, testcase will be marked as failed in internal mechanisms. This will happen even if you later catch the exception in your testcase. To get around this (allow command failing without throwing exceptions), use the reportCmdFail parameter which disables the raise. :param k: Index where command is sent, '*' -send command for all duts. :param cmd: Command to be sent to DUT. :param wait: For special cases when retcode is not wanted to wait. :param timeout: Command timeout in seconds. :param expected_retcode: Expecting this retcode, default: 0, can be None when it is ignored. :param asynchronous: Send command, but wait for response in parallel. When sending next command previous response will be wait. When using async mode, response is dummy. :param report_cmd_fail: If True (default), exception is thrown on command execution error. :return: CliResponse object """ return self._commands.execute_command(k, cmd, # pylint: disable=invalid-name wait, timeout, expected_retcode, asynchronous, report_cmd_fail) def send_post_commands(self, cmds=""): """ Send post commands to duts. :param cmds: Commands to send as string. :return: """ return self._commands.send_post_commands(cmds) def send_pre_commands(self, cmds=""): """ Send pre-commands to duts. :param cmds: Commands to send as string :return: Nothing """ return self._commands.send_pre_commands(cmds) def init_sniffer(self): """ Initialize and start sniffer if it is required. :return: Nothing """ return self._nwsniffer.init_sniffer() def get_start_time(self): """ Get test start timestamp. :return: None or timestamp. """ return self._resources.get_start_time() @property def wshark(self): """ Return wireshark object. :return: Wireshark """ return self._nwsniffer.wshark @property def tshark_arguments(self): """ Get tshark arguments. :return: dict """ return self._nwsniffer.tshark_arguments @property def sniffer_required(self): """ Check if sniffer was requested for this run. :return: Boolean """ return self._nwsniffer.sniffer_required def clear_sniffer(self): """ Clear sniffer :return: Nothing """ return self._nwsniffer.clear_sniffer() @property def capture_file(self): """ Return capture file path. :return: file path of capture file. """ return self._nwsniffer.capture_file def get_nw_log_filename(self): """ Get nw data log file name. :return: string """ return self._nwsniffer.get_nw_log_filename() @property def pluginmanager(self): """ Getter for PluginManager. :return: PluginManager """ return self._plugins.pluginmanager @pluginmanager.setter def pluginmanager(self, value): """ Setter for PluginManager. """ self._plugins.pluginmanager = value def start_external_services(self): """ Start ExtApps required by test case. :return: Nothing """ return self._plugins.start_external_services() def stop_external_services(self): """ Stop external services started via PluginManager """ return self._plugins.stop_external_services() def parse_response(self, cmd, response): """ Parse a response for command cmd. :param cmd: Command :param response: Response :return: Parsed response (usually dict) """ return self._plugins.parse_response(cmd, response) def _validate_dut_configs(self, dut_configuration_list, logger): """ Validate dut configurations. :param dut_configuration_list: dictionary with dut configurations :param logger: logger to be used :raises EnvironmentError if something is wrong """ return self._resources.validate_dut_configs(dut_configuration_list, logger) # Backwards compatibility functions here def __wrap_obsoleted_functions(self): """ Replaces obsoleted setup and teardown step names with old ones to provide backwards compatibility. :return: Nothing """ wrappers = { 'rampUp': 'setup', 'setUp': 'setup', 'rampDown': 'teardown', 'tearDown': 'teardown' } for key, value in iteritems(wrappers): if hasattr(self, key) and not hasattr(self, value): self.logger.warning( "%s has been deprecated, please rename it to %s", key, value) setattr(self, value, getattr(self, key)) def get_dut_range(self, i=0): """ get range of length dut_count with offset i. :param i: Offset :return: range """ return self.resource_configuration.get_dut_range(i) @deprecated("Please use test_name property instead.") def get_test_name(self): """ Get test case name. :return: str """ return self.test_name @deprecated("_check_skip has been deprecated. Use check_skip instead.") def _check_skip(self): """ Backwards compatibility. """ return self._configurations.check_skip() @property @deprecated("_dut_count has been deprecated. Use dut_count() instead.") def _dut_count(self): """ Backwards compatibility. """ return self.dut_count() @property @deprecated("_platforms has been deprecated. Please use get_platforms() instead.") def _platforms(self): """ Deprecated getter property for platforms. :return: list of strings """ return self.get_platforms() @property @deprecated("_serialnumbers has been deprecated. Please use get_serialnumbers() instead.") def _serialnumbers(self): """ Deprecated property for serial numbers. :return: list of strings """ return self.get_serialnumbers() @property @deprecated("Use test_name instead.") def name(self): """ Returns name from Configurations. """ return self._configurations.name @deprecated("Please don't use this function.") def get_dut_versions(self): """ Get nname results and set them to duts. :return: Nothing """ return self._resources.get_dut_versions(self._commands) @property @deprecated("_starttime has been deprecated. Please use get_start_time instead.") def _starttime(self): """ Deprecated getter for test start time. :return: None or timestamp. """ return self.get_start_time() @property @deprecated("_results has been deprecated. Please use results instead.") def _results(self): """ Deprecated getter for results. :return: ResultList """ return self.results @_results.setter @deprecated("_results has been deprecated. Please use results instead.") def _results(self, value): """ Deprecated setter for results. :param value: ResultList :return: Nothing """ self.results = value @property @deprecated("_dutinformation has been deprecated. Please use dutinformations instead.") def _dutinformations(self): """ Deprecated getter for dut information list. :return: DutInformationList """ return self.dutinformations @_dutinformations.setter @deprecated("_dutinformation has been deprecated. Please use dutinformations instead.") def _dutinformations(self, value): """ Deprecated setter for dut information list. :param value: DutInformationList :return: Nothing """ self.dutinformations = value @deprecated("set_args has been deprecated, please use the args property instead.") def set_args(self, args): """ Deprecated setter for args. :param args: :return: """ self.args = args @deprecated("get_metadata has been deprecated, please use get_config() instead") def get_metadata(self): """ Deprecated getter for test configuration and metadata. :return: dict """ return self.get_config() @deprecated("get_resource_configuration has been deprecated, please use the " "resource_configuration property instead.") def get_resource_configuration(self): """ Deprecated getter for resource configuration. :return: ResourceConfig """ return self.resource_configuration
class BenchApi(object): ''' BenchApi class. Implements methods that provide access to the implementations contained in the other TestBench modules. ''' def __init__(self, **kwargs): pass def _init(self): ''' Initialize internal class instances. ''' pass def get_logger(self): ''' Get logger function. Calls Logger.get_logger(). :return: BenchLoggerAdapter ''' pass @property def args(self): ''' Gets known args from ArgsHandler. :return: Namespace ''' pass @args.setter def args(self): ''' Setter for known args. ''' pass @property def unknown(self): ''' Gets unknown args from ArgsHandler. ''' pass @unknown.setter def unknown(self): ''' Setter for unknown args. ''' pass @property def logger(self): ''' :return: Logger from Logger. BenchLoggerAdapter usually. ''' pass @logger.setter def logger(self): ''' Sets logger. ''' pass @property def test_name(self): ''' Returns test_name from Configurations. ''' pass @property def config(self): ''' :return: Configurations.config ''' pass @config.setter def config(self): ''' Sets Configurations.config. ''' pass @property def env(self): ''' :return: Configurations.env ''' pass def sync_cli(self, dut, generator_function=None, generator_function_args=None, retries=None, command_timeout=None): ''' Synchronize cli for a dut using custom function. :param dut: Dut :param generator_function: callable :param generator_function_args: list of arguments for generator_function :param retries: int, if set to 0 will skip command entirely (for unit testing purposes) :param command_timeout: int :raises: TestStepError: if synchronization fails. :raises: AttributeError: if retries is set to 0, unit testing reasons. ''' pass def is_hardware_in_use(self): ''' :return: True if type is hardware ''' pass def get_platforms(self): ''' Get list of dut platforms. :return: list ''' pass def get_serialnumbers(self): ''' Get list of dut serial numbers. :return: list ''' pass def get_test_component(self): ''' Get test component. :return: string ''' pass def get_features_under_test(self): ''' Get features tested by this test case. :return: list ''' pass def get_allowed_platforms(self): ''' Return list of allowed platfroms from requirements. :return: list ''' pass def status(self): ''' Get TC implementation status. :return: string or None ''' pass def type(self): ''' Get test case type. :return: string or None ''' pass def subtype(self): ''' Get test case subtype. :return: string or None ''' pass def get_config(self): ''' Get test case configuration. :return: dict ''' pass def skip(self): ''' Get skip value. :return: Boolean or None ''' pass def skip_info(self): ''' Get the entire skip dictionary. :return: dictionary or None ''' pass def skip_reason(self): ''' Get skip reason. :return: string ''' pass def get_tc_abspath(self, tc_file=None): ''' Get path to test case. :param tc_file: name of the file. If None, tcdir used instead. :return: absolute path. ''' pass def set_config(self, config): ''' Set the configuration for this test case. :param config: dictionary :return: Nothing ''' pass def check_skip(self): ''' Check if tc should be skipped :return: Boolean ''' pass def load_plugins(self): ''' Initialize PluginManager and Load bench related plugins. :return: Nothing ''' pass def init_duts(self): ''' Initialize Duts, and the network sniffer. :return: Nothing ''' pass def duts_release(self): ''' Release Duts. :return: Nothing ''' pass @property def resource_configuration(self): ''' Getter for __resource_configuration. :return: ResourceConfig ''' pass @resource_configuration.setter def resource_configuration(self): ''' Setter for __resource_configuration. :param value: ResourceConfig :return: Nothing ''' pass def dut_count(self): ''' Getter for dut count from resource configuration. :return: int ''' pass def get_dut_count(self): ''' Get dut count. :return: int ''' pass @property def resource_provider(self): ''' Getter for __resource_provider :return: ResourceProvider ''' pass @property def duts_release(self): ''' Get _duts. :return: list ''' pass @duts.setter def duts_release(self): ''' set a list as _duts. :param value: list :return: Nothing ''' pass def duts_iterator_all(self): ''' Yield indexes and related duts. ''' pass def duts_iterator_all(self): ''' Yield indexes and related duts that are for this test case. ''' pass def is_allowed_dut_index(self, dut_index): ''' Check if dut_index is one of the duts for this test case. :param dut_index: int :return: Boolean ''' pass @property def dut_indexes(self): ''' Get a list with dut indexes. :return: list ''' pass def get_dut_count(self): ''' Get dut object. :param k: index or nickname of dut. :return: Dut ''' pass def get_node_endpoint(self, endpoint_id): ''' get NodeEndPoint object for dut endpoint_id. :param endpoint_id: nickname of dut :return: NodeEndPoint ''' pass def is_my_dut_index(self, dut_index): ''' :return: Boolean ''' pass @property def dutinformations(self): ''' Getter for DutInformation list. :return: list ''' pass @dutinformations.setter def dutinformations(self): ''' Setter for dutinformations :param value: DutInformationList :return: Nothing ''' pass def reset_dut(self, dut_index="*"): ''' Reset dut k. :param dut_index: index of dut to reset. Default is *, which causes all duts to be reset. :return: Nothing ''' pass def get_dut_nick(self, dut_index): ''' Get nick of dut index k. :param dut_index: index of dut :return: string ''' pass def get_dut_index(self, nick): ''' Get index of dut with nickname nick. :param nick: string :return: integer > 1 ''' pass def is_my_dut_index(self, dut_index): ''' :return: Boolean ''' pass @staticmethod def create_new_result(verdict, retcode, duration, input_data): ''' Create a new Result object with data in function arguments. :param verdict: Verdict as string :param retcode: Return code as int :param duration: Duration as time :param input_data: Input data as dictionary :return: Result ''' pass def add_new_result(self, verdict, retcode, duration, input_data): ''' Add a new Result to result object to the internal ResultList. :param verdict: Verdict as string :param retcode: Return code as int :param duration: Duration as time :param input_data: Input data as dict :return: Result ''' pass @property def results(self): ''' Getter for internal _results variable. ''' pass @results.setter def results(self): ''' Call setter for internal ResultList. :param value: ResultList :return: Nothing ''' pass @property def retcode(self): ''' Getter for return code. :return: int ''' pass @retcode.setter def retcode(self): ''' Setter for retcode. :param value: int :return: Nothing ''' pass def get_result(self, tc_file=None): ''' Generate a Result object from this test case. :param tc_file: Location of test case file :return: Result ''' pass def append_result(self, tc_file=None): ''' Append a new fully constructed Result to the internal ResultList. :param tc_file: Test case file path :return: Nothing ''' pass def set_failure(self, retcode, reason): ''' Set internal state to reflect failure of test. :param retcode: return code :param reason: failure reason as string :return: Nothing ''' pass def input_from_user(self, title=None): ''' Input data from user. :param title: Title as string :return: stripped data from stdin. ''' pass def open_node_terminal(self, k="*", wait=True): ''' Open Putty (/or kitty if exists) :param k: number 1.<max duts> or '*' to open putty to all devices :param wait: wait while putty is closed before continue testing :return: Nothing ''' pass def delay(self, seconds): ''' Sleep command. :param seconds: Amount of seconds to sleep. :return: Nothing ''' pass def verify_trace_skip_fail(self, k, expected_traces): ''' Shortcut to set break_in_fail to False in verify_trace. :param k: nick or index of dut. :param expected_traces: Expected traces as a list or string :return: boolean ''' pass def verify_trace_skip_fail(self, k, expected_traces): ''' Verify that traces expected_traces are found in dut traces. :param k: index or nick of dut whose traces are to be used. :param expected_traces: list of expected traces or string :param break_in_fail: Boolean, if True raise LookupError if search fails :return: boolean. :raises: LookupError if search fails. ''' pass def get_time(self): ''' Get timestamp using time.time(). :return: timestamp ''' pass @property def command(self): ''' Alias for execute_command. :return: execute_command attribute reference. ''' pass def wait_for_async_response(self, cmd, async_resp): ''' Wait for the given asynchronous response to be ready and then parse it. :param cmd: The asynchronous command that was sent to DUT. :param async_resp: The asynchronous response returned by the preceding command call. :return: CliResponse object ''' pass def execute_command(self, k, cmd, # pylint: disable=invalid-name wait=True, timeout=50, expected_retcode=0, asynchronous=False, report_cmd_fail=True): ''' Do Command request for DUT. If this fails, testcase will be marked as failed in internal mechanisms. This will happen even if you later catch the exception in your testcase. To get around this (allow command failing without throwing exceptions), use the reportCmdFail parameter which disables the raise. :param k: Index where command is sent, '*' -send command for all duts. :param cmd: Command to be sent to DUT. :param wait: For special cases when retcode is not wanted to wait. :param timeout: Command timeout in seconds. :param expected_retcode: Expecting this retcode, default: 0, can be None when it is ignored. :param asynchronous: Send command, but wait for response in parallel. When sending next command previous response will be wait. When using async mode, response is dummy. :param report_cmd_fail: If True (default), exception is thrown on command execution error. :return: CliResponse object ''' pass def send_post_commands(self, cmds=""): ''' Send post commands to duts. :param cmds: Commands to send as string. :return: ''' pass def send_pre_commands(self, cmds=""): ''' Send pre-commands to duts. :param cmds: Commands to send as string :return: Nothing ''' pass def init_sniffer(self): ''' Initialize and start sniffer if it is required. :return: Nothing ''' pass def get_start_time(self): ''' Get test start timestamp. :return: None or timestamp. ''' pass @property def wshark(self): ''' Return wireshark object. :return: Wireshark ''' pass @property def tshark_arguments(self): ''' Get tshark arguments. :return: dict ''' pass @property def sniffer_required(self): ''' Check if sniffer was requested for this run. :return: Boolean ''' pass def clear_sniffer(self): ''' Clear sniffer :return: Nothing ''' pass @property def capture_file(self): ''' Return capture file path. :return: file path of capture file. ''' pass def get_nw_log_filename(self): ''' Get nw data log file name. :return: string ''' pass @property def pluginmanager(self): ''' Getter for PluginManager. :return: PluginManager ''' pass @pluginmanager.setter def pluginmanager(self): ''' Setter for PluginManager. ''' pass def start_external_services(self): ''' Start ExtApps required by test case. :return: Nothing ''' pass def stop_external_services(self): ''' Stop external services started via PluginManager ''' pass def parse_response(self, cmd, response): ''' Parse a response for command cmd. :param cmd: Command :param response: Response :return: Parsed response (usually dict) ''' pass def _validate_dut_configs(self, dut_configuration_list, logger): ''' Validate dut configurations. :param dut_configuration_list: dictionary with dut configurations :param logger: logger to be used :raises EnvironmentError if something is wrong ''' pass def __wrap_obsoleted_functions(self): ''' Replaces obsoleted setup and teardown step names with old ones to provide backwards compatibility. :return: Nothing ''' pass def get_dut_range(self, i=0): ''' get range of length dut_count with offset i. :param i: Offset :return: range ''' pass @deprecated("Please use test_name property instead.") def get_test_name(self): ''' Get test case name. :return: str ''' pass @deprecated("_check_skip has been deprecated. Use check_skip instead.") def _check_skip(self): ''' Backwards compatibility. ''' pass @property @deprecated("_dut_count has been deprecated. Use dut_count() instead.") def _dut_count(self): ''' Backwards compatibility. ''' pass @property @deprecated("_platforms has been deprecated. Please use get_platforms() instead.") def _platforms(self): ''' Deprecated getter property for platforms. :return: list of strings ''' pass @property @deprecated("_serialnumbers has been deprecated. Please use get_serialnumbers() instead.") def _serialnumbers(self): ''' Deprecated property for serial numbers. :return: list of strings ''' pass @property @deprecated("Use test_name instead.") def name(self): ''' Returns name from Configurations. ''' pass @deprecated("Please don't use this function.") def get_dut_versions(self): ''' Get nname results and set them to duts. :return: Nothing ''' pass @property @deprecated("_starttime has been deprecated. Please use get_start_time instead.") def _starttime(self): ''' Deprecated getter for test start time. :return: None or timestamp. ''' pass @property @deprecated("_results has been deprecated. Please use results instead.") def _results(self): ''' Deprecated getter for results. :return: ResultList ''' pass @_results.setter @deprecated("_results has been deprecated. Please use results instead.") def _results(self): ''' Deprecated setter for results. :param value: ResultList :return: Nothing ''' pass @property @deprecated("_dutinformation has been deprecated. Please use dutinformations instead.") def _dutinformations(self): ''' Deprecated getter for dut information list. :return: DutInformationList ''' pass @_dutinformations.setter @deprecated("_dutinformation has been deprecated. Please use dutinformations instead.") def _dutinformations(self): ''' Deprecated setter for dut information list. :param value: DutInformationList :return: Nothing ''' pass @deprecated("set_args has been deprecated, please use the args property instead.") def set_args(self, args): ''' Deprecated setter for args. :param args: :return: ''' pass @deprecated("get_metadata has been deprecated, please use get_config() instead") def get_metadata(self): ''' Deprecated getter for test configuration and metadata. :return: dict ''' pass @deprecated("get_resource_configuration has been deprecated, please use the " "resource_configuration property instead.") def get_resource_configuration(self): ''' Deprecated getter for resource configuration. :return: ResourceConfig ''' pass
159
104
8
1
2
4
1
1.49
1
10
9
1
103
9
104
104
960
184
313
168
147
465
230
116
125
3
1
2
106
2,105
ARMmbed/icetea
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ARMmbed_icetea/test/test_allocationcontext.py
test.test_allocationcontext.AllocContextListTestcase
class AllocContextListTestcase(unittest.TestCase): def setUp(self): self.nulllogger = logging.getLogger("test") self.nulllogger.addHandler(logging.NullHandler()) def test_append_and_len(self): con1 = AllocationContext("id1", "al_id1", {"data": "data1"}) con2 = AllocationContext("id2", "al_id2", {"data": "data2"}) con_list = AllocationContextList(self.nulllogger) self.assertEqual(len(con_list), 0) con_list.append(con1) self.assertEqual(len(con_list), 1) con_list.append(con2) self.assertEqual(len(con_list), 2) def test_get_and_set_item(self): con1 = AllocationContext("id1", "al_id1", {"data": "data1"}) con2 = AllocationContext("id2", "al_id2", {"data": "data2"}) con_list = AllocationContextList(self.nulllogger) con_list.append(con1) con_list.append(con2) self.assertEqual(con_list[0].resource_id, "id1") self.assertEqual(con_list[1].alloc_id, "al_id2") con_list[0] = con2 self.assertEqual(con_list[0].resource_id, "id2") with self.assertRaises(IndexError): er = con_list[2] # pylint: disable=unused-variable,invalid-name with self.assertRaises(IndexError): er = con_list[-1] # pylint: disable=invalid-name with self.assertRaises(IndexError): con_list[-1] = "test" with self.assertRaises(IndexError): con_list[3] = "test" with self.assertRaises(TypeError): er = con_list["test"] # pylint: disable=unused-variable,invalid-name with self.assertRaises(TypeError): con_list["test"] = "test" def test_open_dut_connections(self): con_list = AllocationContextList(self.nulllogger) # Setup mocked duts dut1 = mock.MagicMock() dut1.start_dut_thread = mock.MagicMock() dut1.start_dut_thread.return_value = "ok" dut1.open_dut = mock.MagicMock() dut1.open_dut.return_value = "ok" dut1.close_dut = mock.MagicMock() dut1.close_connection = mock.MagicMock() dut2 = mock.MagicMock() dut2.start_dut_thread = mock.MagicMock() dut2.start_dut_thread.side_effect = [DutConnectionError] dut2.open_dut = mock.MagicMock() dut2.open_dut.return_value = "ok" dut2.close_dut = mock.MagicMock() dut2.close_connection = mock.MagicMock() con_list.duts = [dut1] con_list.open_dut_connections() dut1.start_dut_thread.assert_called() dut1.open_dut.assert_called() con_list.duts.append(dut2) with self.assertRaises(DutConnectionError): con_list.open_dut_connections() dut2.start_dut_thread.assert_called() dut2.close_dut.assert_called() dut2.close_connection.assert_called() @mock.patch("icetea_lib.AllocationContext.os.path.isfile") @mock.patch("icetea_lib.AllocationContext.AllocationContextList.get_build") def test_check_flashing_need(self, mock_get_build, mock_isfile): con_list = AllocationContextList(self.nulllogger) mock_get_build.return_value = "test_name.bin" mock_isfile.return_value = True self.assertTrue(con_list.check_flashing_need( "hardware", "test_build", False)) mock_get_build.return_value = "test_name.hex" self.assertTrue(con_list.check_flashing_need( "hardware", "test_build", False)) mock_get_build.return_value = "test_name" self.assertFalse(con_list.check_flashing_need( "hardware", "test_build", False)) self.assertTrue(con_list.check_flashing_need( "hardware", "test_build", True)) mock_isfile.return_value = False with self.assertRaises(ResourceInitError): con_list.check_flashing_need("hardware", "test_build", False)
class AllocContextListTestcase(unittest.TestCase): def setUp(self): pass def test_append_and_len(self): pass def test_get_and_set_item(self): pass def test_open_dut_connections(self): pass @mock.patch("icetea_lib.AllocationContext.os.path.isfile") @mock.patch("icetea_lib.AllocationContext.AllocationContextList.get_build") def test_check_flashing_need(self, mock_get_build, mock_isfile): pass
8
0
16
1
15
1
1
0.05
1
7
4
0
5
1
5
77
89
12
76
19
68
4
74
18
68
1
2
1
5
2,106
ARMmbed/icetea
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ARMmbed_icetea/test/test_bench.py
test.test_bench.TestVerify
class TestVerify(unittest.TestCase): def setUp(self): logging.disable(logging.FATAL) def test_bench_apis(self): testcase = ApiTestcase() retcode = testcase.run() self.assertEqual(retcode, ReturnCodes.RETCODE_SUCCESS) def test_exceptions_in_case(self): thread_count = threading.active_count() self.assertNotEqual(TestingTestcase(exception=True, in_case=True).run(), 0, "Test execution returned success retcode") self.assertEqual(thread_count, threading.active_count()) thread_count = threading.active_count() self.assertNotEqual(TestingTestcase(teststep_fail=True, in_case=True).run(), 0, "Test execution returned success retcode") self.assertEqual(thread_count, threading.active_count()) thread_count = threading.active_count() self.assertNotEqual(TestingTestcase(teststep_error=True, in_case=True).run(), 0, "Test execution returned success retcode") self.assertEqual(thread_count, threading.active_count()) thread_count = threading.active_count() self.assertNotEqual(TestingTestcase(name_error=True, in_case=True).run(), 0, "Test execution returned success retcode") self.assertEqual(thread_count, threading.active_count()) thread_count = threading.active_count() self.assertNotEqual(TestingTestcase(value_error=True, in_case=True).run(), 0, "Test execution returned success retcode") self.assertEqual(thread_count, threading.active_count()) thread_count = threading.active_count() self.assertNotEqual(TestingTestcase(test_step_timeout=True, in_case=True).run(), 0, "Test execution returned success retcode") self.assertEqual(thread_count, threading.active_count()) thread_count = threading.active_count() result = TestingTestcase(kbinterrupt=True, in_case=True).run() self.assertNotEqual( result, 0, "Test execution returned success retcode") self.assertEqual(thread_count, threading.active_count()) self.assertTrue(result in ReturnCodes.INCONCLUSIVE_RETCODES, "Test return code not in inconclusive!") result = TestingTestcase(inconclusive_error=True, in_case=True).run() self.assertNotEqual( result, 0, "Test execution returned success retcode") self.assertEqual(thread_count, threading.active_count()) self.assertTrue(result in ReturnCodes.INCONCLUSIVE_RETCODES, "Test return code not in inconclusive!") def test_verify_trace(self): bench = Bench() bench.duts.append(MockDut()) bench.verify_trace(1, "this is test line 2") bench.verify_trace(1, ["this is test line 2"]) with self.assertRaises(LookupError): bench.verify_trace(1, "This is not found in traces") def test_exceptions_in_rampup(self): thread_count = threading.active_count() self.assertNotEqual(TestingTestcase(exception=True, in_setup=True).run(), 0, "Test execution returned success retcode") self.assertEqual(thread_count, threading.active_count()) thread_count = threading.active_count() self.assertNotEqual(TestingTestcase(teststep_fail=True, in_setup=True).run(), 0, "Test execution returned success retcode") self.assertEqual(thread_count, threading.active_count()) thread_count = threading.active_count() self.assertNotEqual(TestingTestcase(teststep_error=True, in_setup=True).run(), 0, "Test execution returned success retcode") self.assertEqual(thread_count, threading.active_count()) thread_count = threading.active_count() self.assertNotEqual(TestingTestcase(name_error=True, in_setup=True).run(), 0, "Test execution returned success retcode") self.assertEqual(thread_count, threading.active_count()) thread_count = threading.active_count() self.assertNotEqual(TestingTestcase(value_error=True, in_setup=True).run(), 0, "Test execution returned success retcode") self.assertEqual(thread_count, threading.active_count()) thread_count = threading.active_count() self.assertNotEqual(TestingTestcase(kbinterrupt=True, in_setup=True).run(), 0, "Test execution returned success retcode") self.assertEqual(thread_count, threading.active_count()) result = TestingTestcase(inconclusive_error=True, in_setup=True).run() self.assertNotEqual( result, 0, "Test execution returned success retcode") self.assertEqual(thread_count, threading.active_count()) self.assertTrue(result in ReturnCodes.INCONCLUSIVE_RETCODES, "Test return code not in inconclusive!") @mock.patch("test.tests.test_tcTearDown.Testcase.teardown") def test_rampdown_called(self, mock_teardown): retcode = TearDownTest(teststepfail=True).run() self.assertEquals(retcode, 1001) self.assertTrue(mock_teardown.called) mock_teardown.reset_mock() retcode = TearDownTest(teststeperror=True).run() self.assertEquals(retcode, 1001) self.assertFalse(mock_teardown.called) retcode = TearDownTest(exception=True).run() self.assertEquals(retcode, 1001) self.assertFalse(mock_teardown.called) retcode = TearDownTest(teststeptimeout=True).run() self.assertEquals(retcode, 1001) self.assertFalse(mock_teardown.called) # Test tearDown is called when TestStepTimeout raised in test case retcode = TearDownTest(teststeptimeout_in_case=True).run() self.assertEquals(retcode, 1005) self.assertTrue(mock_teardown.called) mock_teardown.reset_mock() retcode = TearDownTest(name_error=True).run() self.assertEquals(retcode, 1001) self.assertFalse(mock_teardown.called) retcode = TearDownTest(value_error=True).run() self.assertEquals(retcode, 1001) self.assertFalse(mock_teardown.called) def test_exceptions_in_rampdown(self): thread_count = threading.active_count() self.assertNotEqual(TestingTestcase(exception=True, in_teardown=True).run(), 0, "Test execution returned success retcode") self.assertEqual(thread_count, threading.active_count()) thread_count = threading.active_count() self.assertNotEqual(TestingTestcase(teststep_fail=True, in_teardown=True).run(), 0, "Test execution returned success retcode") self.assertEqual(thread_count, threading.active_count()) thread_count = threading.active_count() self.assertNotEqual(TestingTestcase(teststep_error=True, in_teardown=True).run(), 0, "Test execution returned success retcode") self.assertEqual(thread_count, threading.active_count()) thread_count = threading.active_count() self.assertNotEqual(TestingTestcase(name_error=True, in_teardown=True).run(), 0, "Test execution returned success retcode") self.assertEqual(thread_count, threading.active_count()) thread_count = threading.active_count() self.assertNotEqual(TestingTestcase(value_error=True, in_teardown=True).run(), 0, "Test execution returned success retcode") self.assertEqual(thread_count, threading.active_count()) thread_count = threading.active_count() self.assertNotEqual(TestingTestcase(kbinterrupt=True, in_teardown=True).run(), 0, "Test execution returned success retcode") self.assertEqual(thread_count, threading.active_count()) result = TestingTestcase( inconclusive_error=True, in_teardown=True).run() self.assertNotEqual( result, 0, "Test execution returned success retcode") self.assertEqual(thread_count, threading.active_count()) self.assertTrue(result in ReturnCodes.INCONCLUSIVE_RETCODES, "Test return code not in inconclusive!") def test_no_hanging_threads(self): thread_count = threading.active_count() TestingTestcase().run() self.assertEqual(thread_count, threading.active_count()) @mock.patch('icetea_lib.TestBench.Resources.ResourceFunctions.resource_provider', create=True) @mock.patch('icetea_lib.TestBench.Commands.Commands.execute_command', create=True) def test_precmds_to_two_duts(self, mock_ec, mock_rp): # pylint: disable=no-self-use bench = Bench() bench._resource_provider = mock.Mock() bench.args = mock.MagicMock() bench.args.my_duts = mock.MagicMock(return_value=False) bench.execute_command = mock.MagicMock() mock_resconf = mock.Mock() mock_resconf.get_dut_configuration = mock.MagicMock(return_value=[{ "pre_cmds": ["first", "second"]}, {"pre_cmds": ["first2", "second2"]}]) bench.resource_configuration = mock_resconf mock_resconf.count_duts = mock.MagicMock(return_value=2) # Call using mangled name of __send_pre_commands method bench.send_pre_commands() mock_ec.assert_has_calls([mock.call(1, "first"), mock.call(1, "second"), mock.call(2, "first2"), mock.call(2, "second2")]) bench.execute_command.reset_mock() # Test again with argument cmds bench.send_pre_commands("somecommand") mock_ec.assert_has_calls([mock.call(1, "first"), mock.call(1, "second"), mock.call(2, "first2"), mock.call( 2, "second2"), mock.call("*", "somecommand")]) @mock.patch('icetea_lib.TestBench.Resources.ResourceFunctions.resource_provider', create=True) @mock.patch('icetea_lib.TestBench.Commands.Commands.execute_command', create=True) def test_postcmds_to_two_duts(self, mock_ec, mock_rp): # pylint: disable=no-self-use bench = Bench() bench._resource_provider = mock.MagicMock() bench.execute_command = mock.MagicMock() bench.args = mock.MagicMock() bench.logger = mock.MagicMock() type(bench.args).my_duts = mock.PropertyMock(return_value=False) type(bench.args).pause_when_external_dut = mock.MagicMock( return_value=False) bench._resources.init(mock.MagicMock()) bench._commands.init() mock_dut1 = mock.MagicMock() type(mock_dut1).index = mock.PropertyMock(return_value=1) mock_dut2 = mock.MagicMock() type(mock_dut2).index = mock.PropertyMock(return_value=2) bench._resources.duts = [mock_dut1, mock_dut2] mock_resconf = mock.Mock() mock_resconf.get_dut_configuration = mock.MagicMock( return_value=[{"post_cmds": ["first", "second"]}, {"post_cmds": ["first2", "second2"]}]) bench.resource_configuration = mock_resconf mock_resconf.count_duts = mock.MagicMock(return_value=2) bench.send_post_commands() mock_ec.assert_has_calls([mock.call(1, "first"), mock.call(1, "second"), mock.call(2, "first2"), mock.call(2, "second2")]) mock_ec.reset_mock() # Test again with argument cmds bench.send_post_commands("somecommand") mock_ec.assert_has_calls([mock.call(1, "first"), mock.call(1, "second"), mock.call(2, "first2"), mock.call( 2, "second2"), mock.call("*", "somecommand")]) def test_reset_duts(self): bench = Bench() bench.logger = mock.MagicMock() bench.args = mock.MagicMock() bench._resources._args = bench.args type(bench.args).my_duts = mock.PropertyMock(return_value=False) type(bench.args).pause_when_external_dut = mock.MagicMock( return_value=False) bench._resources.init(mock.MagicMock()) mock_dut = mock.MagicMock() dutconf = {"reset.return_value": True, "initCLI.return_value": True} mock_dut.configure_mock(**dutconf) mock_dutrange = range(2) mock_duts = [mock_dut, mock_dut] bench.duts = mock_duts # TODO: This mocking does not work somehow with mock.patch.object(bench.resource_configuration, "get_dut_range", return_value=mock_dutrange): with mock.patch.object(bench, "is_my_dut_index", return_value=True): for method in ["hard", "soft", None]: bench.args.reset = method bench.reset_dut() mock_dut.reset.assert_called_with(method) self.assertEqual(mock_dut.reset.call_count, 2) mock_dut.reset.reset_mock() def test_check_skip(self): testcase = TestingTestcase() testcase.config["requirements"]["duts"]["*"]["type"] = "process" testcase.config["execution"] = { "skip": {"value": True, "only_type": "process"}} self.assertEqual(testcase.run(), -1) self.assertTrue(testcase.get_result().skipped()) def test_check_skip_invalid_platform(self): # pylint: disable=invalid-name testcase = TestingTestcase() testcase.config["requirements"]["duts"]["*"]["allowed_platforms"] = ["K64F"] testcase.config["execution"] = { "skip": {"value": True, "platforms": ["K64F", "K65F"]}} self.assertEqual(testcase.run(), 0) self.assertFalse(testcase.get_result().skipped()) def test_check_skip_valid_platform(self): # pylint: disable=invalid-name testcase = TestingTestcase() testcase.config["requirements"]["duts"]["*"]["allowed_platforms"] = ["K64F"] testcase.config["requirements"]["duts"]["*"]["platform_name"] = "K64F" testcase.config["execution"] = { "skip": {"value": True, "platforms": ["K64F"]}} self.assertEqual(testcase.run(), -1) self.assertTrue(testcase.get_result().skipped()) def test_check_no_skip(self): testcase = TestingTestcase() testcase.config["execution"] = {"skip": {"value": True}} self.assertEqual(testcase.run(), 0) self.assertFalse(testcase.get_result().skipped()) def test_create_new_result(self): test_data = dict() test_data["reason"] = "this is a reason" result = Bench.create_new_result("fail", 1, 10, test_data) self.assertTrue(result.failure) def test_create_and_add_new_result(self): test_data = dict() test_data["reason"] = "this is a reason" bench = Bench() result = bench.add_new_result("fail", 1, 10, test_data) self.assertEqual(len(bench.results), 1) self.assertEqual(result.fail_reason, "this is a reason")
class TestVerify(unittest.TestCase): def setUp(self): pass def test_bench_apis(self): pass def test_exceptions_in_case(self): pass def test_verify_trace(self): pass def test_exceptions_in_rampup(self): pass @mock.patch("test.tests.test_tcTearDown.Testcase.teardown") def test_rampdown_called(self, mock_teardown): pass def test_exceptions_in_rampdown(self): pass def test_no_hanging_threads(self): pass @mock.patch('icetea_lib.TestBench.Resources.ResourceFunctions.resource_provider', create=True) @mock.patch('icetea_lib.TestBench.Commands.Commands.execute_command', create=True) def test_precmds_to_two_duts(self, mock_ec, mock_rp): pass @mock.patch('icetea_lib.TestBench.Resources.ResourceFunctions.resource_provider', create=True) @mock.patch('icetea_lib.TestBench.Commands.Commands.execute_command', create=True) def test_postcmds_to_two_duts(self, mock_ec, mock_rp): pass def test_reset_duts(self): pass def test_check_skip(self): pass def test_check_skip_invalid_platform(self): pass def test_check_skip_valid_platform(self): pass def test_check_no_skip(self): pass def test_create_new_result(self): pass def test_create_and_add_new_result(self): pass
23
0
15
0
14
1
1
0.04
1
9
5
0
17
0
17
89
283
25
251
53
228
9
213
50
195
2
2
3
18
2,107
ARMmbed/icetea
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ARMmbed_icetea/test/test_bench_commands.py
test.test_bench_commands.CommandMixerTestcase
class CommandMixerTestcase(unittest.TestCase): def test_command_fail_nameerror(self): cmixer = Commands(mock.MagicMock(), mock.MagicMock(), mock.MagicMock(), mock.MagicMock(), mock.MagicMock()) cmixer._logger = MockLogger() with self.assertRaises(NameError): cmixer._command_fail(None, fail_reason="this_fail") def test_command_fail(self): response = MockResponse(["line1", "line2"], 1001) request = MockReq(response) cmixer = Commands(mock.MagicMock(), mock.MagicMock(), mock.MagicMock(), mock.MagicMock(), mock.MagicMock()) cmixer._logger = MockLogger() with self.assertRaises(TestStepFail): cmixer._command_fail(request) with self.assertRaises(TestStepFail): request.response.retcode = -5 cmixer._command_fail(request) with self.assertRaises(TestStepFail): request.response.retcode = -2 cmixer._command_fail(request) with self.assertRaises(TestStepFail): request.response.retcode = -3 cmixer._command_fail(request) with self.assertRaises(TestStepFail): request.response.retcode = -4 cmixer._command_fail(request) with self.assertRaises(TestStepTimeout): request.response.timeout = True cmixer._command_fail(request) request.response = None with self.assertRaises(TestStepFail): cmixer._command_fail(request) def test_wait_for_async_response_attribute_error(self): cmixer = Commands(mock.MagicMock(), mock.MagicMock(), mock.MagicMock(), mock.MagicMock(), mock.MagicMock()) cmixer._logger = MockLogger() with self.assertRaises(AttributeError): cmixer.wait_for_async_response("test_command", None) def test_wait_for_async_response(self): mocked_plugins = mock.MagicMock() cmixer = Commands(mock.MagicMock(), mocked_plugins, mock.MagicMock(), mock.MagicMock(), mock.MagicMock()) cmixer._logger = MockLogger() mocked_dut = mock.MagicMock() async_resp = CliAsyncResponse(mocked_dut) response = MockResponse(["line1", "line2"], 1001) async_resp.parsed = True async_resp.response = response self.assertEqual(response, cmixer.wait_for_async_response( "test_cmd", async_resp)) async_resp.parsed = False mocked_plugins.parse_response = mock.MagicMock( return_value={"parsed": "resp"}) retval = cmixer.wait_for_async_response("test_command", async_resp) self.assertDictEqual(retval.parsed, {"parsed": "resp"}) self.assertEqual(response, retval) def test_execute_command_execute_failures(self): cmixer = Commands(mock.MagicMock(), mock.MagicMock(), mock.MagicMock(), mock.MagicMock(), mock.MagicMock()) cmixer._logger = MockLogger() cmixer.get_time = time.time mocked_dut = mock.MagicMock() mocked_dut.execute_command = mock.MagicMock() mocked_dut.execute_command.side_effect = [ TestStepFail, TestStepError, TestStepTimeout] with self.assertRaises(TestStepFail): cmixer._execute_command(mocked_dut, "test_command") with self.assertRaises(TestStepError): cmixer._execute_command(mocked_dut, "test_command") with self.assertRaises(TestStepTimeout): cmixer._execute_command(mocked_dut, "test_command") def test_private_execute_command(self): cmixer = Commands(mock.MagicMock(), mock.MagicMock(), mock.MagicMock(), mock.MagicMock(), mock.MagicMock()) cmixer._logger = MockLogger() cmixer.get_time = time.time mocked_dut = mock.MagicMock() mocked_dut.execute_command = mock.MagicMock() response = MockResponse(["line1"], retcode=0) mocked_dut.execute_command.return_value = response cmixer._parse_response = mock.MagicMock( return_value={"test": "parsed"}) self.assertEqual(cmixer._execute_command( mocked_dut, "test_command"), response) def test_sync_cli(self): mock_gen = mock.MagicMock(return_value=("val1", "val2")) mocked_resources = mock.MagicMock() logger = logging.getLogger('unittest') logger.addHandler(logging.NullHandler()) cmds = Commands(mock.MagicMock(), mock.MagicMock(), mocked_resources, mock.MagicMock(), mock.MagicMock()) cmds._logger = logger mocked_dut = mock.MagicMock() mocked_resources.get_dut = mock.MagicMock(return_value=mocked_dut) type(mocked_dut).config = mock.PropertyMock(return_value=dict()) with self.assertRaises(TestStepError): with mock.patch.object(cmds, "execute_command"): cmds.sync_cli("1", mock_gen, retries=1) @mock.patch("icetea_lib.TestBench.Commands.uuid") def test_echo_uuid_generator(self, mock_uuid): mock_uuid.uuid1 = mock.MagicMock(return_value="uuid") tpl = Commands.get_echo_uuid() expected_cmd = "echo uuid" expected_retval = "uuid" self.assertEqual(tpl[0], expected_cmd) self.assertEqual(tpl[1], expected_retval)
class CommandMixerTestcase(unittest.TestCase): def test_command_fail_nameerror(self): pass def test_command_fail_nameerror(self): pass def test_wait_for_async_response_attribute_error(self): pass def test_wait_for_async_response_attribute_error(self): pass def test_execute_command_execute_failures(self): pass def test_private_execute_command(self): pass def test_sync_cli(self): pass @mock.patch("icetea_lib.TestBench.Commands.uuid") def test_echo_uuid_generator(self, mock_uuid): pass
10
0
13
1
13
0
1
0
1
13
8
0
8
0
8
80
114
12
102
34
92
0
94
33
85
1
2
2
8
2,108
ARMmbed/icetea
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ARMmbed_icetea/test/test_bench_config.py
test.test_bench_config.ConfigMixerTests
class ConfigMixerTests(unittest.TestCase): def test_read_env_config(self): cmixer = Configurations() with self.assertRaises(InconclusiveError): env_cfg = cmixer._read_env_configs("test_config", "test_iface") env_cfg = cmixer._read_env_configs( os.path.abspath(os.path.join( __file__, "..", "data", "test_env_cfg.json")), "test_iface") self.assertDictEqual(env_cfg, {"test_config": "test", "sniffer": {"iface": "test_iface"}}) with self.assertRaises(InconclusiveError): env_cfg = cmixer._read_env_configs( os.path.abspath(os.path.join(__file__, "..", "data", "test_env_cfg_with_duplicates.json")), "test_iface") def test_read_exec_config(self): cmixer = Configurations() args = MockArgs() args.tc_cfg = "non_existent_file.json" with self.assertRaises(InconclusiveError): cmixer._read_exec_configs(args) args.tc_cfg = os.path.abspath(os.path.join( __file__, "..", "data", "test_env_cfg.json")) args.channel = "1" args.type = "type" args.bin = "bin" args.platform_name = "platform" cmixer._read_exec_configs(args) self.assertDictContainsSubset( {"test_config": "test", "requirements": { "duts": { "*": { "type": "type", "application": { "bin": "bin" }, "platform_name": "platform" } }, "external": { "apps": [] } } }, cmixer.config ) args.tc_cfg = os.path.abspath(os.path.join(__file__, "..", "data", "test_env_cfg_with_duplicates.json")) with self.assertRaises(TestStepError): cmixer._read_exec_configs(args) args.tc_cfg = os.path.abspath(os.path.join( __file__, "..", "data", "test_env_cfg.json")) args.platform_name = "not-in-allowed" cmixer.config["requirements"]["duts"]["*"]["allowed_platforms"] = ["allowed"] with self.assertRaises(TestStepError): cmixer._read_exec_configs(args) args.platform_name = "allowed" cmixer._read_exec_configs(args) self.assertDictContainsSubset( {"test_config": "test", "requirements": { "duts": { "*": { "type": "type", "application": { "bin": "bin" }, "allowed_platforms": ["allowed"], "platform_name": "allowed" } }, "external": { "apps": [] } } }, cmixer.config ) @unittest.skipIf(sys.platform == 'win32', "windows does't support process tests") def test_config_parse_corner_case_33(self): compile_dummy_dut() script_file = os.path.abspath(os.path.join(__file__, os.path.pardir, os.path.pardir, "icetea.py")) tcdir = os.path.abspath(os.path.join(__file__, os.path.pardir)) retcode = subprocess.call( "python " + script_file + " --clean -s " "--tc test_config_parse_corner_case --failure_return_value " "--tcdir " + tcdir, shell=True) self.assertEqual(retcode, ExitCodes.EXIT_SUCCESS) def test_parse_config(self): basic_config = { "name": "my_test", "type": "regression", "sub_type": None, "requirements": { "duts": {"*": { "application": { "bin": None } }} } } expected = { "compatible": { "framework": { "name": "Icetea", "version": ">=1.0.0" }, "automation": { "value": True }, "hw": { "value": True } }, "name": "my_test", "type": "regression", "sub_type": None, "requirements": { "duts": {"*": { "application": { "bin": None } }}, "external": { "apps": [ ] } } } retval, int_keys = Configurations._parse_config(**basic_config) self.assertDictEqual(retval, expected) self.assertFalse(int_keys) basic_config = { "name": "my_test", "type": "regression", "sub_type": None, "requirements": { "duts": { "*": { "application": { "bin": None } }, 1: {"nick": "intkey"}} } } expected = { "compatible": { "framework": { "name": "Icetea", "version": ">=1.0.0" }, "automation": { "value": True }, "hw": { "value": True } }, "name": "my_test", "type": "regression", "sub_type": None, "requirements": { "duts": { "*": { "application": { "bin": None } }, "1": {"nick": "intkey"}}, "external": { "apps": [ ] } } } retval, int_keys = Configurations._parse_config(**basic_config) self.assertDictEqual(retval, expected) self.assertTrue(int_keys)
class ConfigMixerTests(unittest.TestCase): def test_read_env_config(self): pass def test_read_exec_config(self): pass @unittest.skipIf(sys.platform == 'win32', "windows does't support process tests") def test_config_parse_corner_case_33(self): pass def test_parse_config(self): pass
6
0
47
2
44
0
1
0
1
5
5
0
4
0
4
76
192
13
179
16
173
0
50
15
45
1
2
1
4
2,109
ARMmbed/icetea
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ARMmbed_icetea/test/test_bench_functions.py
test.test_bench_functions.BenchFunctionsTests
class BenchFunctionsTests(unittest.TestCase): @mock.patch("icetea_lib.TestBench.BenchFunctions.time") def test_delay(self, mocked_time): benchfunctions = BenchFunctions(mock.MagicMock(), mock.MagicMock(), mock.MagicMock()) mocked_time.sleep = mock.MagicMock() benchfunctions._logger = mock.MagicMock() benchfunctions.delay(1) benchfunctions.delay(40) @mock.patch("icetea_lib.TestBench.BenchFunctions.sys") def test_input_from_user(self, mocked_sys): benchfunctions = BenchFunctions(mock.MagicMock(), mock.MagicMock(), mock.MagicMock()) mocked_sys.stdin = mock.MagicMock() mocked_sys.stdin.readline = mock.MagicMock( side_effect=["string\n", '']) data = benchfunctions.input_from_user("Test") self.assertEqual(data, "string") data = benchfunctions.input_from_user("Test") self.assertEqual(data, "") @mock.patch("icetea_lib.TestBench.BenchFunctions.verify_message") def test_verify_trace(self, mocked_verify_message): benchfunctions = BenchFunctions(mock.MagicMock(), mock.MagicMock(), mock.MagicMock()) mocked_verify_message.side_effect = [ True, TypeError, False, False, True] benchfunctions.duts = [MockedDut()] self.assertTrue(benchfunctions.verify_trace(0, "test1")) with self.assertRaises(TypeError): benchfunctions.verify_trace(0, "test1") self.assertFalse(benchfunctions.verify_trace(0, "test3", False)) with self.assertRaises(LookupError): benchfunctions.verify_trace(0, "test4") benchfunctions.get_dut_index = mock.MagicMock(return_value=0) self.assertTrue(benchfunctions.verify_trace("0", "test1"))
class BenchFunctionsTests(unittest.TestCase): @mock.patch("icetea_lib.TestBench.BenchFunctions.time") def test_delay(self, mocked_time): pass @mock.patch("icetea_lib.TestBench.BenchFunctions.sys") def test_input_from_user(self, mocked_sys): pass @mock.patch("icetea_lib.TestBench.BenchFunctions.verify_message") def test_verify_trace(self, mocked_verify_message): pass
7
0
10
0
10
0
1
0
1
4
2
0
3
0
3
75
36
3
33
11
26
0
27
8
23
1
2
1
3
2,110
ARMmbed/icetea
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ARMmbed_icetea/test/test_bench_plugin.py
test.test_bench_plugin.PluginMixerTests
class PluginMixerTests(unittest.TestCase): def test_start_external_services(self): mocked_config = { "requirements": { "external": { "apps": [ { "name": "test_app" } ] } } } mixer = Plugins(mock.MagicMock(), mock.MagicMock(), mock.MagicMock(), mocked_config) mixer.init(mock.MagicMock()) mixer._env = {} mixer._args = MockArgs() mixer._logger = MockLogger() mixer._pluginmanager = mock.MagicMock() mixer._pluginmanager.start_external_service = mock.MagicMock( side_effect=[PluginException, True]) with self.assertRaises(EnvironmentError): mixer.start_external_services() mixer._pluginmanager.start_external_service.assert_called_once_with( "test_app", conf={"name": "test_app"}) @mock.patch("icetea_lib.TestBench.Plugins.GenericProcess") def test_start_generic_app(self, mock_gp): mocked_config = { "requirements": { "external": { "apps": [ { "cmd": [ "echo", "1" ], "path": "test_path" } ] } } } mixer = Plugins(mock.MagicMock(), mock.MagicMock(), mock.MagicMock(), mocked_config) mixer._env = dict() mixer._logger = MockLogger() mixer._args = MockArgs() mocked_app = mock.MagicMock() mocked_app.start_process = mock.MagicMock() mock_gp.return_value = mocked_app mixer.start_external_services() mocked_app.start_process.assert_called_once() mock_gp.assert_called_with( cmd=["echo", "1"], name="generic", path="test_path")
class PluginMixerTests(unittest.TestCase): def test_start_external_services(self): pass @mock.patch("icetea_lib.TestBench.Plugins.GenericProcess") def test_start_generic_app(self, mock_gp): pass
4
0
26
1
25
0
1
0
1
5
4
0
2
0
2
74
55
3
52
9
48
0
25
8
22
1
2
1
2
2,111
ARMmbed/icetea
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ARMmbed_icetea/test/test_bench_resources.py
test.test_bench_resources.ResourceMixerTests
class ResourceMixerTests(unittest.TestCase): def _create_dut(self): mocked_dut = mock.MagicMock() mocked_dut.close_dut = mock.MagicMock( side_effect=[True, KeyboardInterrupt]) mocked_dut.close_connection = mock.MagicMock() mocked_dut.finished = mock.MagicMock(side_effect=[False, True]) return mocked_dut @mock.patch("icetea_lib.TestBench.Resources.time") def test_dut_release(self, mock_time): mocked_dut = self._create_dut() resmixer = ResourceFunctions( mock.MagicMock(), mock.MagicMock(), mock.MagicMock()) resmixer.duts = [mocked_dut] resmixer._args = MockArgs() resmixer._logger = MockLogger() resmixer._resource_provider = mock.MagicMock() resmixer._call_exception = mock.MagicMock() resmixer.is_my_dut_index = mock.MagicMock(return_value=True) resmixer.duts_release() mocked_dut.close_dut.assert_called_once() mocked_dut.close_connection.assert_called_once() resmixer.duts_release() self.assertEqual(len(resmixer.duts), 0) @mock.patch("icetea_lib.TestBench.Resources.time") def test_dut_release_exception(self, mock_time): mocked_dut = self._create_dut() mocked_dut.close_connection = mock.MagicMock(side_effect=[Exception]) resmixer = ResourceFunctions( mock.MagicMock(), mock.MagicMock(), mock.MagicMock()) resmixer.duts = [mocked_dut] resmixer._args = MockArgs() resmixer._logger = MockLogger() resmixer._resource_provider = mock.MagicMock() resmixer._resource_provider.allocator = mock.MagicMock() type(resmixer._resource_provider.allocator).share_allocations = mock.PropertyMock( return_value=False) resmixer._resource_provider.allocator.release = mock.MagicMock() resmixer._call_exception = mock.MagicMock() resmixer.is_my_dut_index = mock.MagicMock(return_value=True) resmixer.duts_release() mocked_dut.close_dut.assert_called_once() mocked_dut.close_connection.assert_called_once() resmixer._resource_provider.allocator.release.assert_called_once() def test_dut_count(self): resmixer = ResourceFunctions( mock.MagicMock(), mock.MagicMock(), mock.MagicMock()) resmixer.resource_configuration.count_duts = mock.MagicMock( return_value=1) self.assertEqual(resmixer.dut_count(), 1) resmixer.resource_configuration = None self.assertEqual(resmixer.dut_count(), 0) self.assertEqual(resmixer.get_dut_count(), 0) resmixer.resource_configuration = ResourceConfig() resmixer.resource_configuration.count_duts = mock.MagicMock( return_value=1) self.assertEqual(resmixer.get_dut_count(), 1) def test_is_allowed_dut_index(self): resmixer = ResourceFunctions( mock.MagicMock(), mock.MagicMock(), mock.MagicMock()) resmixer.resource_configuration = ResourceConfig() resmixer.resource_configuration.count_duts = mock.MagicMock( return_value=4) self.assertTrue(resmixer.is_allowed_dut_index(2)) self.assertTrue(resmixer.is_allowed_dut_index(4)) self.assertFalse(resmixer.is_allowed_dut_index(5)) def test_get_dut(self): resmixer = ResourceFunctions( mock.MagicMock(), mock.MagicMock(), mock.MagicMock()) resmixer._logger = MockLogger() mocked_dut = self._create_dut() resmixer.duts = [mocked_dut] self.assertEqual(resmixer.get_dut(1), mocked_dut) with self.assertRaises(ValueError): resmixer.get_dut(2) def test_get_dut_nick(self): resmixer = ResourceFunctions( mock.MagicMock(), mock.MagicMock(), mock.MagicMock()) type(resmixer._configuration).config = mock.PropertyMock( return_value=TEST_REQS) resmixer.resource_configuration = ResourceConfig(TEST_REQS) resmixer.resource_configuration.resolve_configuration(None) self.assertEqual(resmixer.get_dut_nick(1), "dut1") self.assertEqual(resmixer.get_dut_nick(2), "test_device") self.assertEqual(resmixer.get_dut_nick("1"), "dut1") self.assertEqual(resmixer.get_dut_nick("2"), "test_device") self.assertEqual(resmixer.get_dut_nick("3"), "3") def test_get_dut_index(self): resmixer = ResourceFunctions(mock.MagicMock(), mock.MagicMock(), mock.PropertyMock( return_value=TEST_REQS)) resmixer.resource_configuration = ResourceConfig(TEST_REQS) resmixer.resource_configuration.resolve_configuration(None) self.assertEqual(resmixer.get_dut_index("dut1"), 1) self.assertEqual(resmixer.get_dut_index("test_device"), 2) with self.assertRaises(ValueError): resmixer.get_dut_index("3") def test_config_validation_bin_not_defined(self): # pylint: disable=invalid-name duts_cfg = [{}] mocked_args = mock.MagicMock() type(mocked_args).skip_flash = mock.PropertyMock(return_value=False) resources = ResourceFunctions(mocked_args, mock.MagicMock(), mock.PropertyMock(return_value=TEST_REQS)) self.assertEqual(resources.validate_dut_configs( duts_cfg, MockLogger()), None) def test_config_validation_no_bin(self): duts_cfg = [{"application": {"bin": "not.exist"}}] mocked_args = mock.MagicMock() type(mocked_args).skip_flash = mock.PropertyMock(return_value=False) resources = ResourceFunctions(mocked_args, mock.MagicMock(), mock.PropertyMock( return_value=TEST_REQS)) with self.assertRaises(EnvironmentError): resources.validate_dut_configs(duts_cfg, MockLogger()) def test_config_validation_bin_defined(self): # pylint: disable=invalid-name duts_cfg = [{"application": {"bin": __file__}}] mocked_args = mock.MagicMock() type(mocked_args).skip_flash = mock.PropertyMock(return_value=False) resources = ResourceFunctions(mocked_args, mock.MagicMock(), mock.PropertyMock(return_value=TEST_REQS)) self.assertEqual(resources.validate_dut_configs( duts_cfg, MockLogger()), None) def test_config_validation_no_bin_skip_flash(self): # pylint: disable=invalid-name duts_cfg = [{"application": {"bin": "not.exist"}}] mocked_args = mock.MagicMock() type(mocked_args).skip_flash = mock.PropertyMock(return_value=True) resources = ResourceFunctions(mocked_args, mock.MagicMock(), mock.PropertyMock(return_value=TEST_REQS)) self.assertEqual(resources.validate_dut_configs( duts_cfg, MockLogger()), None)
class ResourceMixerTests(unittest.TestCase): def _create_dut(self): pass @mock.patch("icetea_lib.TestBench.Resources.time") def test_dut_release(self, mock_time): pass @mock.patch("icetea_lib.TestBench.Resources.time") def test_dut_release_exception(self, mock_time): pass def test_dut_count(self): pass def test_is_allowed_dut_index(self): pass def test_get_dut(self): pass def test_get_dut_nick(self): pass def test_get_dut_index(self): pass def test_config_validation_bin_not_defined(self): pass def test_config_validation_no_bin(self): pass def test_config_validation_bin_defined(self): pass def test_config_validation_no_bin_skip_flash(self): pass
15
0
9
0
9
0
1
0.03
1
8
4
0
12
0
12
84
126
12
114
38
99
3
106
36
93
1
2
1
12
2,112
ARMmbed/icetea
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ARMmbed_icetea/test/test_build.py
test.test_build.BuildTestCase
class BuildTestCase(unittest.TestCase): """ Basic true asserts to see that testing is executed """ def setUp(self): logging.disable(logging.CRITICAL) def tearDown(self): pass def test_build_file(self): build = Build.init("file:./test/test_build.py") self.assertEqual(build.get_type(), "file") self.assertEqual(build.get_url(), "./test/test_build.py") self.assertEqual(build.is_exists(), True) self.assertTrue(build.get_data().startswith(b'#!/usr/bin/env python')) build = Build.init("file:\\test\\build.py") self.assertEqual(build.get_type(), "file") self.assertEqual(build.get_url(), "\\test\\build.py") build = Build.init("file:c:\\file.py") self.assertEqual(build.get_type(), "file") self.assertEqual(build.get_url(), "c:\\file.py") build = Build.init("file:/tmp/file.py") self.assertEqual(build.get_type(), "file") self.assertEqual(build.get_url(), "/tmp/file.py") self.assertEqual(build.is_exists(), False) with self.assertRaises(NotFoundError): build.get_data() @mock.patch("icetea_lib.build.build.requests.get") def test_build_http(self, mocked_get): mocked_get.return_value = mock.MagicMock() type(mocked_get).content = mock.PropertyMock(return_value="\r") build = Build.init("http://www.hep.com") self.assertEqual(build.get_type(), "http") self.assertEqual(build.get_url(), "http://www.hep.com") self.assertTrue(build.get_data(), "\r") @mock.patch("icetea_lib.build.build.requests.get", side_effect=iter([requests.exceptions.SSLError])) def test_build_http_error(self, mocked_get): # pylint: disable=unused-argument build = Build.init("https://hep.com") self.assertEqual(build.get_type(), "http") with self.assertRaises(NotFoundError): build.get_data() def test_build_uuid(self): uuid = "f81d4fae-7dec-11d0-a765-00a0c91e6bf6" build = Build.init(uuid) self.assertEqual(build.get_type(), "database") self.assertEqual(build.get_url(), uuid) with self.assertRaises(NotImplementedError): build.get_data() def test_build_id(self): uuid = "537eed02ed345b2e039652d2" build = Build.init(uuid) self.assertEqual(build.get_type(), "database") self.assertEqual(build.get_url(), uuid) with self.assertRaises(NotImplementedError): build.get_data() def test_build_unknown_type(self): with self.assertRaises(NotImplementedError): build = Build.init(",") with self.assertRaises(NotImplementedError): build = Build(ref="", type="unknown") build._load()
class BuildTestCase(unittest.TestCase): ''' Basic true asserts to see that testing is executed ''' def setUp(self): pass def tearDown(self): pass def test_build_file(self): pass @mock.patch("icetea_lib.build.build.requests.get") def test_build_http(self, mocked_get): pass @mock.patch("icetea_lib.build.build.requests.get", side_effect=iter([requests.exceptions.SSLError])) def test_build_http_error(self, mocked_get): pass def test_build_uuid(self): pass def test_build_id(self): pass def test_build_unknown_type(self): pass
11
1
7
1
7
0
1
0.09
1
3
1
0
8
0
8
80
72
12
58
20
46
5
55
17
46
1
2
1
8
2,113
ARMmbed/icetea
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ARMmbed_icetea/test/test_cloud.py
test.test_cloud.CloudTestcase
class CloudTestcase(unittest.TestCase): def setUp(self): with mock.patch("icetea_lib.cloud.get_pkg_version") as mocked_reader: mocked_reader.return_value = [mock.MagicMock()] self.cloudclient = Cloud(module="moduletest") @mock.patch("icetea_lib.cloud.get_pkg_version") def test_module_import(self, mocked_version_reader): mocked_version_reader.return_value = "1.0.0" # Test ImportError with non-existent module with self.assertRaises(ImportError): cloud_module = Cloud(module="Nonexistentmodule") # Verify that Cloud interface init function can import cloud module properly cloud_module = Cloud(module="test.moduletest") self.assertIsNotNone(cloud_module._client, "Cloud client was None!") # Verify correct behaviour with incorrect module with self.assertRaises(ImportError): cloud_module = Cloud(module="test.moduletest.wrongmodule") def test_get_suite(self): self.cloudclient.get_suite("test_suite", ["foo", "bar"]) self.cloudclient._client.get_suite.assert_called_once_with("test_suite", [ "foo", "bar"]) def test_get_campaigns(self): self.cloudclient.get_campaigns() self.assertTrue(self.cloudclient._client.get_campaigns.called) def test_get_campaign_id(self): self.cloudclient.get_campaign_id("test_campaign") self.cloudclient._client.get_campaign_id.assert_called_once_with( "test_campaign") with self.assertRaises(KeyError): self.cloudclient.get_campaign_id("test_campaign") def test_get_campaign_names(self): self.cloudclient.get_campaign_names() self.assertTrue(self.cloudclient._client.get_campaign_names.called) def test_update_testcase(self): self.cloudclient.update_testcase({"test": "meta", "meta": "data"}) self.cloudclient._client.update_testcase.assert_called_once_with({"test": "meta", "meta": "data"}) def test_send_result(self): self.cloudclient.send_result({"verdict": "PASS"}) self.cloudclient._client.upload_results.assert_called_once_with({ "verdict": "PASS"}) self.assertIsNone(self.cloudclient.send_result("data")) def test_converter(self): metadata = {"status": "ready", "name": "tc_name", "title": "this_is_title", "requirements": { }, "feature": "unit test", "component": "Icetea" } self.assertEquals(self.cloudclient._convert_to_db_tc_metadata(metadata), {'status': {'value': 'ready'}, 'requirements': {'node': {'count': 1}}, 'other_info': {'features': 'unit test', 'components': 'Icetea', 'title': 'this_is_title'}, 'tcid': 'tc_name'}) def test_cloudresult_simple(self): test_res = { "testcase": "tc_name", "verdict": "pass", "retcode": 0, "fw_name": "Icetea", "fw_version": "0.10.2" } result = Result(test_res) res = create_result_object(result) compare = { 'exec': { 'verdict': 'pass', 'env': { 'framework': { 'ver': '0.10.2', 'name': 'Icetea' } }, 'dut': { 'sn': 'unknown' } }, 'tcid': 'tc_name' } self.assertDictContainsSubset(compare, res) def test_cloudresult_full(self): test_res = { "testcase": "tc_name", "verdict": "fail", "reason": "ohnou", "retcode": 0, "duration": 1, "fw_name": "Icetea", "fw_version": "0.10.2" } result = Result(test_res) class DummyBuild(object): @property def branch(self): return 'master' @property def commit_id(self): return '1234' @property def build_url(self): return 'url' @property def giturl(self): return 'url' @property def date(self): return "22.22.2222" @property def sha1(self): return "asdv" class DummyDut(object): @property def resource_id(self): return '123' @property def platform(self): return 'K64F' @property def build(self): return DummyBuild() result.set_dutinformation([DummyDut()]) res = create_result_object(result) compare = { 'exec': { 'verdict': 'pass', 'note': 'ohnou', 'duration': 1, 'env': { 'framework': { 'ver': '0.10.2', 'name': 'Icetea' } }, 'sut': { 'commitId': '1234', 'buildUrl': 'url', 'gitUrl': 'url', 'branch': 'master', "buildDate": "22.22.2222", "buildSha1": "asdv" }, 'dut': { 'sn': '123', 'model': 'K64F' } }, 'tcid': 'tc_name' } self.assertDictContainsSubset(compare, res)
class CloudTestcase(unittest.TestCase): def setUp(self): pass @mock.patch("icetea_lib.cloud.get_pkg_version") def test_module_import(self, mocked_version_reader): pass def test_get_suite(self): pass def test_get_campaigns(self): pass def test_get_campaign_id(self): pass def test_get_campaign_names(self): pass def test_update_testcase(self): pass def test_send_result(self): pass def test_converter(self): pass def test_cloudresult_simple(self): pass def test_cloudresult_full(self): pass class DummyBuild(object): @property def branch(self): pass @property def commit_id(self): pass @property def build_url(self): pass @property def giturl(self): pass @property def date(self): pass @property def sha1(self): pass class DummyDut(object): @property def resource_id(self): pass @property def platform(self): pass @property def build_url(self): pass
33
0
9
1
8
0
1
0.02
1
5
3
0
11
1
11
83
174
26
145
45
112
3
70
34
47
1
2
1
20
2,114
ARMmbed/icetea
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ARMmbed_icetea/test/test_cloud.py
test.test_cloud.CloudTestcase.test_cloudresult_full.DummyBuild
class DummyBuild(object): @property def branch(self): return 'master' @property def commit_id(self): return '1234' @property def build_url(self): return 'url' @property def giturl(self): return 'url' @property def date(self): return "22.22.2222" @property def sha1(self): return "asdv"
class DummyBuild(object): @property def branch(self): pass @property def commit_id(self): pass @property def build_url(self): pass @property def giturl(self): pass @property def date(self): pass @property def sha1(self): pass
13
0
2
0
2
0
1
0
1
0
0
0
6
0
6
6
24
5
19
13
6
0
13
7
6
1
1
0
6
2,115
ARMmbed/icetea
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ARMmbed_icetea/test/test_cloud.py
test.test_cloud.CloudTestcase.test_cloudresult_full.DummyDut
class DummyDut(object): @property def resource_id(self): return '123' @property def platform(self): return 'K64F' @property def build(self): return DummyBuild()
class DummyDut(object): @property def resource_id(self): pass @property def platform(self): pass @property def build(self): pass
7
0
2
0
2
0
1
0
1
1
1
0
3
0
3
3
12
2
10
7
3
0
7
4
3
1
1
0
3
2,116
ARMmbed/icetea
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ARMmbed_icetea/test/test_file.py
test.test_file.TestFileTestCase
class TestFileTestCase(unittest.TestCase): def setUp(self): self.ctm = IceteaManager() # variables for testing getLocalTestcases, parseLocalTestcases, # parseLocalTest, loadClass, printListTestcases self.testpath = os.path.abspath(os.path.dirname(__file__)) self.root_path = os.getcwd() sys.path.append(self.testpath) self.testdir = os.path.join(self.testpath, 'testbase') # variables for testing run() compile_dummy_dut() def test_init_with_non_existing_file(self): # pylint: disable=invalid-name proc = subprocess.Popen(['python', 'icetea.py', '-s', '--tc', 'test_cmdline', '--tcdir', 'examples', '--type', 'process', '--clean', '--bin', 'file.bin'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=self.root_path) out, error = proc.communicate() # pylint: disable=unused-variable self.assertTrue(out.find(b"Binary not found") != -1, "non exitent file error was not risen") self.assertEqual(proc.returncode, 0) @unittest.skipIf(sys.platform == 'win32', "windows doesn't support process test") def test_init_with_an_existing_file(self): bin_path = "test" + os.path.sep + "dut" + os.path.sep + "dummyDut" proc = subprocess.Popen(['python', 'icetea.py', '-s', '--tc', 'test_cmdline', '--tcdir', 'examples', '--type', 'process', '--clean', '--bin', bin_path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=self.root_path) out, error = proc.communicate() # pylint: disable=unused-variable self.assertTrue(out.find(b'test_cmdline | pass') != -1, "exitent file was not accepted") self.assertEqual(proc.returncode, 0, "Icetea execution with existing file crashed")
class TestFileTestCase(unittest.TestCase): def setUp(self): pass def test_init_with_non_existing_file(self): pass @unittest.skipIf(sys.platform == 'win32', "windows doesn't support process test") def test_init_with_an_existing_file(self): pass
5
0
12
1
10
2
1
0.19
1
2
1
0
3
4
3
75
39
5
31
14
26
6
19
13
15
1
2
0
3
2,117
ARMmbed/icetea
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ARMmbed_icetea/test/test_genericprocess.py
test.test_genericprocess.GenericProcessTestcase
class GenericProcessTestcase(unittest.TestCase): @unittest.skipIf( platform.system() == "Windows", "Launching process in Windows ends in icetea warning" "\"This OS is not supporting select.poll() or select.kqueue()\"") def test_quick_process(self): # Run testcase icetea_cmd = ["python", "icetea.py", "--clean", "--silent", "--failure_return_value", "--tc", "test_quick_process", "--tcdir", '"{}"'.format(os.path.join("test", "tests"))] # Shouldn't need to join the argument array, # but it doesn't work for some reason without it (Python 2.7.12). retcode = subprocess.call(args=" ".join(icetea_cmd), shell=True) # Check success self.assertEqual( retcode, ExitCodes.EXIT_SUCCESS, "Non-success returncode {} returned.".format(retcode)) def tearDown(self): # Run with --clean to clean up subprocess.call( "python icetea.py --clean ", shell=True)
class GenericProcessTestcase(unittest.TestCase): @unittest.skipIf( platform.system() == "Windows", "Launching process in Windows ends in icetea warning" "\"This OS is not supporting select.poll() or select.kqueue()\"") def test_quick_process(self): pass def tearDown(self): pass
4
0
11
1
8
3
1
0.25
1
1
1
0
2
0
2
74
28
3
20
9
13
5
7
5
4
1
2
0
2
2,118
ARMmbed/icetea
ARMmbed_icetea/test/tests/skip_tc.py
test.tests.skip_tc.Testcase
class Testcase(Bench): """ Test case for testing skipping test cases. """ def __init__(self): Bench.__init__(self, name="skipcasetest", title="Testcase test file", status="development", purpose="dummy", component=["None"], type="compatibility", requirements={ "duts": { '*': { "count": 0 } } }, execution={ "skip": { "value": True, "only_type": "process", "reason": "Because" } } ) def case(self): # pylint: disable=missing-docstring pass
class Testcase(Bench): ''' Test case for testing skipping test cases. ''' def __init__(self): pass def case(self): pass
3
1
13
0
13
1
1
0.15
1
0
0
0
2
0
2
108
30
1
26
3
23
4
5
3
2
1
3
0
2
2,119
ARMmbed/icetea
ARMmbed_icetea/test/tests/multiple_in_one_file/MultipleCases.py
test.tests.multiple_in_one_file.MultipleCases.MultipleTestcase
class MultipleTestcase(Bench): """ Example test case for implementing multiple test cases that share setup and teardown functions. """ def __init__(self, **kwargs): tc_args = { 'title': "dummy", 'status': "unknown", 'type': "functional", 'purpose': "dummy", 'requirements': { "duts": { '*': { "count": 0, } } } } tc_args.update(kwargs) Bench.__init__(self, **tc_args) def setup(self): pass def teardown(self): pass
class MultipleTestcase(Bench): ''' Example test case for implementing multiple test cases that share setup and teardown functions. ''' def __init__(self, **kwargs): pass def setup(self): pass def teardown(self): pass
4
1
7
0
7
0
1
0.14
1
0
0
0
3
0
3
109
26
2
21
5
17
3
9
5
5
1
3
0
3
2,120
ARMmbed/icetea
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ARMmbed_icetea/test/test_files.py
test.test_files.FileTestCase
class FileTestCase(unittest.TestCase): def setUp(self): self.file_name = "test_file" self.file_path = os.path.join("path", "to", "right") self.file_path2 = os.path.join( "path", "of", "no", "rights") + os.path.sep self.non_existing_file = "NoFile" self.test_json = {"test1": "value1", "test2": "value2", "test3": "value3", "test4": "test5"} self.test_json2 = {"Test": "Value", "Test1": "Value1", "Test2": "Value2"} self.jsonfile = JsonFile() ''' FileUtils tests here ''' @mock.patch("icetea_lib.tools.file.FileUtils.os.chdir") @mock.patch("icetea_lib.tools.file.FileUtils.os.remove") def test_remove_file(self, mock_rm, mock_chdir): mock_chdir.side_effect = iter([OSError, 1, 1, 1, 1]) mock_rm.side_effect = iter([OSError, 1]) path_nowhere = os.path.join("testPath", "to", "nowhere") path_somewhere = os.path.join("testPath", "to", "somewhere") with self.assertRaises(OSError): FileUtils.remove_file("testName", path_nowhere) with self.assertRaises(OSError): FileUtils.remove_file("testName", path_nowhere) self.assertTrue(FileUtils.remove_file("testName", path_somewhere)) @mock.patch("icetea_lib.tools.file.FileUtils.os.chdir") @mock.patch("icetea_lib.tools.file.FileUtils.os.rename") def test_rename_file(self, mock_rn, mock_chdir): mock_chdir.side_effect = iter([OSError, 1, 1, 1, 1]) mock_rn.side_effect = iter([OSError, 1]) path_nowhere = os.path.join("testPath", "to", "nowhere") path_somewhere = os.path.join("testPath", "to", "somewhere") with self.assertRaises(OSError): FileUtils.rename_file("testName", "new_testName", path_nowhere) with self.assertRaises(OSError): FileUtils.rename_file("testName", "new_testName", path_nowhere) self.assertTrue(FileUtils.rename_file( "testName", "new_testName", path_somewhere)) ''' JsonFile tests start here ''' def test_writing_file(self): # run test for saving a json to a new file. File path should not exists so it is created. self.jsonfile.write_file( self.test_json, self.file_path, self.file_name, 2) self.assertTrue(os.path.exists(self.file_path + os.path.sep + self.file_name + ".json")) with open(self.file_path + os.path.sep + self.file_name + ".json", 'r') as file_opened: self.assertDictEqual(json.load(file_opened), self.test_json) # save a json to an old file to overwrite entire file self.jsonfile.write_file( self.test_json2, self.file_path, self.file_name, 2) with open(self.file_path + os.path.sep + self.file_name + ".json", 'r') as file_opened: self.assertDictEqual(json.load(file_opened), self.test_json2) @unittest.skipIf(sys.platform == 'win32', "os.chmod with 0o444 or stat.S_IREAD doesn't work") def test_writing_file_fail_windows(self): # run test to save json to a file with an invalid path os.makedirs(self.file_path2, 0o777) os.chmod(self.file_path2, 0o444) with self.assertRaises(IOError): self.jsonfile.write_file( self.test_json, self.file_path2, self.file_name, 2) def test_writing_with_filter(self): self.jsonfile.write_file(self.test_json, self.file_path, self.file_name, 2, keys_to_write=["test1", "test2"]) ref = {"test1": self.test_json["test1"], "test2": self.test_json["test2"]} with open(self.file_path + os.path.sep + self.file_name + ".json", 'r') as file_opened: self.assertDictEqual(json.load(file_opened), ref) self.jsonfile.write_file( self.test_json, self.file_path, self.file_name, 2) self.jsonfile.write_values(self.test_json2, self.file_path, self.file_name, 2, keys_to_write=["Test"]) with open(self.file_path + os.path.sep + self.file_name + ".json", 'r') as file_opened: self.assertDictEqual(jsonmerge.merge(self.test_json, {"Test": self.test_json2["Test"]}), json.load(file_opened)) @mock.patch("icetea_lib.tools.file.SessionFiles.JsonFile._write_json") @mock.patch("icetea_lib.tools.file.SessionFiles.os.path.exists") @mock.patch("icetea_lib.tools.file.SessionFiles.os.makedirs") def test_write_file_errors(self, mock_mkdir, mock_exists, mock_json): mock_mkdir.side_effect = iter([OSError]) mock_exists.side_effect = iter([False, True, True]) mock_json.side_effect = iter([EnvironmentError, ValueError]) with self.assertRaises(OSError): self.jsonfile.write_file( self.test_json, self.file_path, self.file_name) with self.assertRaises(EnvironmentError): self.jsonfile.write_file( self.test_json, self.file_path, self.file_name) with self.assertRaises(ValueError): self.jsonfile.write_file( self.test_json, self.file_path, self.file_name) def test_reading_file(self): # Write test data self.jsonfile.write_file( self.test_json, self.file_path, self.file_name, 2) # read json from nonexisting file with self.assertRaises(IOError): self.jsonfile.read_file(self.file_path, self.non_existing_file) # read json from existing file data = self.jsonfile.read_file(self.file_path, self.file_name) self.assertDictEqual(data, self.test_json) # ToDo: read from malformed file def test_writing_values(self): # Test writing to a malformed file. self.jsonfile.write_file( "", self.file_path, "malformed_" + self.file_name) with self.assertRaises(TypeError): self.jsonfile.write_values(self.test_json, self.file_path, "malformed_" + self.file_name) cwd = os.getcwd() os.chdir(self.file_path) open("empty_" + self.file_name + ".json", "w") os.chdir(cwd) self.assertEquals(self.jsonfile.write_values(self.test_json, self.file_path, "empty_" + self.file_name), os.path.join(self.file_path, "empty_" + self.file_name + ".json")) # save a json to a new file with write_values instead of write_file self.assertEqual(self.jsonfile.write_values(self.test_json, self.file_path, self.file_name, 2), self.file_path + os.path.sep + self.file_name + ".json") # save a json to an old file to append to existing data self.jsonfile.write_file( self.test_json, self.file_path, self.file_name, 2) self.jsonfile.write_values( self.test_json2, self.file_path, self.file_name, 2) with open(self.file_path + os.path.sep + self.file_name + ".json", 'r') as file_opened: self.assertDictEqual(jsonmerge.merge(self.test_json, self.test_json2), json.load(file_opened)) @unittest.skipIf(sys.platform == 'win32', "os.chmod with 0o444 or stat.S_IREAD doesn't work") def test_writing_value_fail_windows(self): # Try adding content to a file with no write permissions os.makedirs(self.file_path2, 0o777) self.jsonfile.write_file( self.test_json2, self.file_path2, self.file_name, 2) os.chmod(self.file_path2, 0o444) with self.assertRaises(IOError): self.jsonfile.write_values( self.test_json, self.file_path2, self.file_name, 2) def test_reading_values(self): # Test writing to a malformed file. self.jsonfile.write_file( "", self.file_path, "malformed_" + self.file_name) with self.assertRaises(KeyError): self.jsonfile.read_value( "test1", self.file_path, "malformed_" + self.file_name) # read json from nonexisting file with self.assertRaises(IOError): self.jsonfile.read_value("Test1", self.file_path, self.file_name) # Create test data for reading self.jsonfile.write_file( self.test_json, self.file_path, self.file_name, 2) # read json from existing file self.assertEqual("value1", self.jsonfile.read_value("test1", self.file_path, self.file_name)) # try to read nonexisting key with self.assertRaises(KeyError): self.jsonfile.read_value("value1", self.file_path, self.file_name) def tearDown(self): # Do tearDown stuff. if os.path.exists(os.path.join(self.file_path, "malformed_" + self.file_name + ".json")): FileUtils.remove_file("malformed_" + self.file_name + ".json", self.file_path + os.path.sep) if os.path.exists(os.path.join(self.file_path, "empty_" + self.file_name + ".json")): FileUtils.remove_file( "empty_" + self.file_name + ".json", self.file_path + os.path.sep) if os.path.exists(self.file_path + os.path.sep + self.file_name + ".json"): FileUtils.remove_file(self.file_name + ".json", self.file_path + os.path.sep) os.removedirs(self.file_path + os.path.sep) if os.path.exists(self.file_path2): os.chmod(self.file_path2, 0o777) if os.path.exists(self.file_path2 + self.file_name + ".json"): FileUtils.remove_file( self.file_name + ".json", self.file_path2) os.removedirs(self.file_path2)
class FileTestCase(unittest.TestCase): def setUp(self): pass @mock.patch("icetea_lib.tools.file.FileUtils.os.chdir") @mock.patch("icetea_lib.tools.file.FileUtils.os.remove") def test_remove_file(self, mock_rm, mock_chdir): pass @mock.patch("icetea_lib.tools.file.FileUtils.os.chdir") @mock.patch("icetea_lib.tools.file.FileUtils.os.rename") def test_rename_file(self, mock_rn, mock_chdir): pass def test_writing_file(self): pass @unittest.skipIf(sys.platform == 'win32', "os.chmod with 0o444 or stat.S_IREAD doesn't work") def test_writing_file_fail_windows(self): pass def test_writing_with_filter(self): pass @mock.patch("icetea_lib.tools.file.SessionFiles.JsonFile._write_json") @mock.patch("icetea_lib.tools.file.SessionFiles.os.path.exists") @mock.patch("icetea_lib.tools.file.SessionFiles.os.makedirs") def test_write_file_errors(self, mock_mkdir, mock_exists, mock_json): pass def test_reading_file(self): pass def test_writing_values(self): pass @unittest.skipIf(sys.platform == 'win32', "os.chmod with 0o444 or stat.S_IREAD doesn't work") def test_writing_value_fail_windows(self): pass def test_reading_values(self): pass def tearDown(self): pass
22
0
12
1
10
1
1
0.18
1
5
1
0
12
7
12
84
181
27
131
35
109
23
110
27
97
6
2
2
17
2,121
ARMmbed/icetea
ARMmbed_icetea/test/tests/matching_test/feature2_test.py
test.tests.matching_test.feature2_test.Testcase
class Testcase(Bench): def __init__(self): Bench.__init__(self, name="ut_feature2_test", title="unittest matching", status="development", type="acceptance", purpose="dummy", component=["icetea_ut"], feature=["feature2"], requirements={ "duts": { '*': { "count": 0 } } } ) def case(self): pass
class Testcase(Bench): def __init__(self): pass def case(self): pass
3
0
10
0
10
0
1
0
1
0
0
0
2
0
2
108
21
1
20
3
17
0
5
3
2
1
3
0
2
2,122
ARMmbed/icetea
ARMmbed_icetea/test/test_result.py
test.test_result.ResultListTestcase
class ResultListTestcase(unittest.TestCase): def setUp(self): self.args_tc = argparse.Namespace( available=False, version=False, bin=None, binary=False, channel=None, clean=False, cloud=False, component=False, device='*', gdb=None, gdbs=None, gdbs_port=2345, group=False, iface=None, kill_putty=False, list=False, listsuites=False, log='./log', my_duts=None, nobuf=None, pause_when_external_dut=False, putty=False, reset=False, silent=True, skip_case=False, skip_rampdown=False, skip_rampup=False, platform=None, status=False, suite=None, tc="test_cmdline", tc_cfg=None, tcdir="examples", testtype=False, type="process", subtype=None, use_sniffer=False, valgrind=False, valgrind_tool=None, verbose=False, repeat=0, feature=None, suitedir="./test/suites", forceflash_once=True, forceflash=False, stop_on_failure=False, json=False) def test_append(self): # Test append for single Result rlist = ResultList() result1 = Result() rlist.append(result1) self.assertListEqual(rlist.data, [result1]) # Test append for ResultList result2 = Result() rlist2 = ResultList() rlist2.append(result2) rlist.append(rlist2) self.assertListEqual(rlist.data, [result1, result2]) # Test append TypeError with self.assertRaises(TypeError): rlist.append(["test"]) def test_get_verdict(self): dictionary = {"retcode": 0} res = Result(kwargs=dictionary) reslist = ResultList() reslist.append(res) self.assertEquals(reslist.get_verdict(), "pass") dictionary = {"retcode": 1} res2 = Result(kwargs=dictionary) res2.set_verdict(verdict="fail", retcode=1, duration=10) reslist.append(res2) self.assertEquals(reslist.get_verdict(), "fail") res3 = Result() res3.set_verdict("inconclusive", 4, 1) reslist = ResultList() reslist.append(res3) self.assertEquals(reslist.get_verdict(), "inconclusive") reslist.append(res2) self.assertEquals(reslist.get_verdict(), "fail") def test_get_summary(self): expected = {"count": 3, "pass": 1, "fail": 1, "skip": 0, "inconclusive": 1, "retries": 1, "duration": 10} dictionary = {"retcode": 0} res = Result(kwargs=dictionary) dictionary = {"retcode": 1} res2 = Result(kwargs=dictionary) res2.set_verdict(verdict="fail", retcode=1, duration=5) res3 = Result() res3.set_verdict("inconclusive", 4, 5) res3.retries_left = 1 resultlist = ResultList() resultlist.append(res) resultlist.append(res2) resultlist.append(res3) self.assertDictEqual(resultlist.get_summary(), expected) def test_inconc_count(self): dictionary = {"retcode": 0} res = Result(kwargs=dictionary) dictionary = {"retcode": 1} res2 = Result(kwargs=dictionary) res2.set_verdict(verdict="fail", retcode=1, duration=5) res3 = Result() res3.set_verdict("inconclusive", 4, 5) res3.retries_left = 1 resultlist = ResultList() resultlist.append(res) resultlist.append(res2) resultlist.append(res3) self.assertEqual(resultlist.inconclusive_count(), 1) res4 = Result() res4.set_verdict("inconclusive", 4, 5) resultlist.append(res4) self.assertEqual(resultlist.inconclusive_count(), 2) def test_pass_count(self): dictionary = {"retcode": 0} res = Result(kwargs=dictionary) dictionary = {"retcode": 1} res2 = Result(kwargs=dictionary) res2.set_verdict(verdict="fail", retcode=1, duration=5) res3 = Result() res3.set_verdict("inconclusive", 4, 5) res3.retries_left = 1 resultlist = ResultList() resultlist.append(res) resultlist.append(res2) resultlist.append(res3) self.assertEqual(resultlist.success_count(), 1) res4 = Result() res4.set_verdict("pass", 4, 5) resultlist.append(res4) self.assertEqual(resultlist.success_count(), 2) def test_fail_count(self): dictionary = {"retcode": 0} res = Result(kwargs=dictionary) dictionary = {"retcode": 1} res2 = Result(kwargs=dictionary) res2.set_verdict(verdict="fail", retcode=1, duration=5) res3 = Result() res3.set_verdict("inconclusive", 4, 5) res3.retries_left = 1 resultlist = ResultList() resultlist.append(res) resultlist.append(res2) resultlist.append(res3) self.assertEqual(resultlist.failure_count(), 1) res4 = Result() res4.set_verdict("fail", 4, 5) resultlist.append(res4) self.assertEqual(resultlist.failure_count(), 2) def test_retries_count(self): dictionary = {"retcode": 0} res = Result(kwargs=dictionary) dictionary = {"retcode": 1} res2 = Result(kwargs=dictionary) res2.set_verdict(verdict="fail", retcode=1, duration=5) res3 = Result() res3.set_verdict("inconclusive", 4, 5) res3.retries_left = 1 resultlist = ResultList() resultlist.append(res) resultlist.append(res2) resultlist.append(res3) self.assertEqual(resultlist.retry_count(), 1) res4 = Result() res4.set_verdict("inconclusive", 4, 5) resultlist.append(res4) self.assertEqual(resultlist.retry_count(), 1) def test_clean_fails(self): dictionary = {"retcode": 0} res = Result(kwargs=dictionary) res.set_verdict(verdict="pass", retcode=0, duration=0) dictionary = {"retcode": 1} res2 = Result(kwargs=dictionary) res2.set_verdict(verdict="fail", retcode=1, duration=5) res3 = Result() res3.set_verdict("inconclusive", 4, 5) res3.retries_left = 1 resultlist = ResultList() resultlist.append(res) resultlist.append(res2) resultlist.append(res3) res4 = Result() res4.set_verdict("inconclusive", 4, 5) resultlist.append(res4) self.assertTrue(resultlist.clean_fails()) dictionary = {"retcode": 0} res = Result(kwargs=dictionary) res.set_verdict(verdict="pass", retcode=0, duration=0) dictionary = {"retcode": 1} res2 = Result(kwargs=dictionary) res2.set_verdict(verdict="fail", retcode=1, duration=5) res2.retries_left = 1 res3 = Result() res3.set_verdict("fail", 4, 5) res3.retries_left = 0 resultlist = ResultList() resultlist.append(res) resultlist.append(res2) resultlist.append(res3) res4 = Result() res4.set_verdict("inconclusive", 4, 5) resultlist.append(res4) self.assertTrue(resultlist.clean_fails()) dictionary = {"retcode": 0} res = Result(kwargs=dictionary) res.set_verdict(verdict="pass", retcode=0, duration=0) dictionary = {"retcode": 1} res2 = Result(kwargs=dictionary) res2.set_verdict(verdict="fail", retcode=1, duration=5) res2.retries_left = 1 res3 = Result() res3.set_verdict("pass", 4, 5) res3.retries_left = 0 resultlist = ResultList() resultlist.append(res) resultlist.append(res2) resultlist.append(res3) res4 = Result() res4.set_verdict("inconclusive", 4, 5) resultlist.append(res4) self.assertFalse(resultlist.clean_fails()) def test_clean_inconcs(self): dictionary = {"retcode": 0} res = Result(kwargs=dictionary) res.set_verdict(verdict="pass", retcode=0, duration=0) dictionary = {"retcode": 1} res2 = Result(kwargs=dictionary) res2.set_verdict(verdict="fail", retcode=1, duration=5) res3 = Result() res3.set_verdict("inconclusive", 4, 5) resultlist = ResultList() resultlist.append(res) resultlist.append(res2) resultlist.append(res3) self.assertTrue(resultlist.clean_inconcs()) dictionary = {"retcode": 0} res = Result(kwargs=dictionary) res.set_verdict(verdict="pass", retcode=0, duration=0) dictionary = {"retcode": 1} res2 = Result(kwargs=dictionary) res2.set_verdict(verdict="fail", retcode=1, duration=5) res2.retries_left = 1 res3 = Result() res3.set_verdict("inconclusive", 4, 5) res3.retries_left = 1 resultlist = ResultList() resultlist.append(res) resultlist.append(res2) resultlist.append(res3) res4 = Result() res4.set_verdict("inconclusive", 4, 5) resultlist.append(res4) self.assertTrue(resultlist.clean_inconcs()) dictionary = {"retcode": 0} res = Result(kwargs=dictionary) res.set_verdict(verdict="pass", retcode=0, duration=0) dictionary = {"retcode": 1} res2 = Result(kwargs=dictionary) res2.set_verdict(verdict="inconclusive", retcode=1, duration=5) res2.retries_left = 1 res3 = Result() res3.set_verdict("pass", 4, 5) res3.retries_left = 0 resultlist = ResultList() resultlist.append(res) resultlist.append(res2) resultlist.append(res3) self.assertFalse(resultlist.clean_inconcs()) def test_pass_rate(self): dictionary = {"retcode": 0} res = Result(kwargs=dictionary) res.set_verdict(verdict="pass", retcode=0, duration=0) dictionary = {"retcode": 1} res2 = Result(kwargs=dictionary) res2.set_verdict(verdict="fail", retcode=1, duration=5) res3 = Result() res3.set_verdict("inconclusive", 4, 5) res4 = Result(kwargs=dictionary) res4.set_verdict(verdict="skip", retcode=1, duration=5) resultlist = ResultList() resultlist.append(res) resultlist.append(res2) resultlist.append(res3) self.assertEquals(resultlist.pass_rate(), "50.00 %") self.assertEquals(resultlist.pass_rate(include_inconclusive=True), "33.33 %") self.assertEquals(resultlist.pass_rate(include_skips=True), "50.00 %") resultlist.append(res4) self.assertEquals(resultlist.pass_rate(include_skips=True, include_inconclusive=True), "25.00 %")
class ResultListTestcase(unittest.TestCase): def setUp(self): pass def test_append(self): pass def test_get_verdict(self): pass def test_get_summary(self): pass def test_inconc_count(self): pass def test_pass_count(self): pass def test_fail_count(self): pass def test_retries_count(self): pass def test_clean_fails(self): pass def test_clean_inconcs(self): pass def test_pass_rate(self): pass
12
0
24
1
24
0
1
0.01
1
4
2
0
11
1
11
83
280
17
260
70
248
3
241
70
229
1
2
1
11
2,123
ARMmbed/icetea
ARMmbed_icetea/test/test_resourcerequirements.py
test.test_resourcerequirements.ResourceRequirementTestcase
class ResourceRequirementTestcase(unittest.TestCase): def setUp(self): self.simple_testreqs = { "type": "process", "allowed_platforms": [], "expires": 2000, "nick": None, "tags": {"test": True} } self.simple_testreqs2 = { "type": "process", "allowed_platforms": ["DEV3"], "nick": None, } self.recursion_testreqs = { "type": "process", "allowed_platforms": ["DEV3"], "application": {"bin": "test_binary"}, "nick": None, } self.actual_descriptor1 = {"platform_name": "DEV2", "resource_type": "mbed"} self.actual_descriptor2 = {"platform_name": "DEV1", "resource_type": "process"} self.actual_descriptor3 = {"platform_name": "DEV3", "resource_type": "process"} self.actual_descriptor4 = {"resource_type": "process", "bin": "test_binary"} def test_get(self): dutreq = ResourceRequirements(self.simple_testreqs) self.assertEqual(dutreq.get("type"), "process") dutreq = ResourceRequirements(self.recursion_testreqs) self.assertEqual(dutreq.get("application.bin"), "test_binary") self.assertIsNone(dutreq.get("application.bin.not_exist")) def test_set(self): dutreq = ResourceRequirements(self.simple_testreqs) dutreq.set("test_key", "test_val") self.assertEqual(dutreq._requirements["test_key"], "test_val") # Test override dutreq.set("test_key", "test_val2") self.assertEqual(dutreq._requirements["test_key"], "test_val2") # test tags merging. Also a test for set_tag(tags=stuff) dutreq.set("tags", {"test": False, "test2": True}) self.assertEqual(dutreq._requirements["tags"], {"test": False, "test2": True}) dutreq.set("tags", {"test2": False}) self.assertEqual(dutreq._requirements["tags"], {"test": False, "test2": False}) def test_set_tags(self): dutreq = ResourceRequirements(self.simple_testreqs) dutreq._set_tag(tag="test", value=False) dutreq._set_tag(tag="test2", value=True) self.assertDictEqual(dutreq._requirements["tags"], {"test": False, "test2": True}) def test_empty_tags(self): dutreq = ResourceRequirements(self.simple_testreqs) dutreq._set_tag("test", value=None) dutreq.remove_empty_tags() self.assertEqual(dutreq._requirements["tags"], {}) self.assertEqual(dutreq.remove_empty_tags(tags={"test1": True, "test2": None}), {"test1": True})
class ResourceRequirementTestcase(unittest.TestCase): def setUp(self): pass def test_get(self): pass def test_set(self): pass def test_set_tags(self): pass def test_empty_tags(self): pass
6
0
11
1
10
0
1
0.04
1
1
1
0
5
7
5
77
62
8
52
17
46
2
36
17
30
1
2
0
5
2,124
ARMmbed/icetea
ARMmbed_icetea/test/test_resourceprovider.py
test.test_resourceprovider.MockLogger
class MockLogger: def __init__(self): pass def info(self, message): pass def error(self, message): pass def debug(self, message, content=None): pass def exception(self, message): pass
class MockLogger: def __init__(self): pass def info(self, message): pass def error(self, message): pass def debug(self, message, content=None): pass def exception(self, message): pass
6
0
2
0
2
0
1
0
0
0
0
0
5
0
5
5
15
4
11
6
5
0
11
6
5
1
0
0
5
2,125
ARMmbed/icetea
ARMmbed_icetea/test/test_resourceprovider.py
test.test_resourceprovider.MockDut
class MockDut: def __init__(self): pass def close_dut(self): pass def close_connection(self): pass def release(self): pass def print_info(self): pass
class MockDut: def __init__(self): pass def close_dut(self): pass def close_connection(self): pass def release(self): pass def print_info(self): pass
6
0
2
0
2
0
1
0
0
0
0
0
5
0
5
5
15
4
11
6
5
0
11
6
5
1
0
0
5
2,126
ARMmbed/icetea
ARMmbed_icetea/test/test_resourceprovider.py
test.test_resourceprovider.MockArgs
class MockArgs: def __init__(self): self.parallel_flash = True self.allocator = "TestAllocator" self.list = False self.listsuites = False self.allocator_cfg = None
class MockArgs: def __init__(self): pass
2
0
6
0
6
0
1
0
0
0
0
0
1
5
1
1
7
0
7
7
5
0
7
7
5
1
0
0
1
2,127
ARMmbed/icetea
ARMmbed_icetea/test/test_resourceprovider.py
test.test_resourceprovider.MockAllocator
class MockAllocator: def __init__(self, thing1, thing2, thing3): self.allocate_calls = 0 def reset_logging(self): pass def allocate(self, *args, **kwargs): self.allocate_calls = self.allocate_calls+1 if self.allocate_calls == 1: raise AllocationError else: pass def cleanup(self): pass def release(self, dut=None): pass
class MockAllocator: def __init__(self, thing1, thing2, thing3): pass def reset_logging(self): pass def allocate(self, *args, **kwargs): pass def cleanup(self): pass def release(self, dut=None): pass
6
0
3
0
3
0
1
0
0
1
1
0
5
1
5
5
19
4
15
7
9
0
14
7
8
2
0
1
6
2,128
ARMmbed/icetea
ARMmbed_icetea/test/test_resourceconfig.py
test.test_resourceconfig.TestVerify
class TestVerify(unittest.TestCase): def setUp(self): self.resconfig = ResourceConfig() self.testreqs = { "requirements": { "duts": { "*": {"count": 2, "type": "process"} } } } self.testreqsresult = [ { "type": "process", "allowed_platforms": [], "nick": None, }, { "type": "process", "allowed_platforms": [], "nick": None, } ] def tearDown(self): del self.resconfig def test_dut_counts(self): self.resconfig._dut_requirements = [ResourceRequirements({"type": "process"}), ResourceRequirements({"type": "hardware"})] self.resconfig._resolve_dut_count() self.assertEqual(self.resconfig.count_duts(), 2) self.assertEqual(self.resconfig.count_hardware(), 1) self.assertEqual(self.resconfig.count_process(), 1) self.resconfig._dut_requirements = [ResourceRequirements({"type": "process"}), ResourceRequirements({"type": "process"}), ResourceRequirements({"type": "hardware"})] self.resconfig._resolve_dut_count() self.assertEqual(self.resconfig.count_duts(), 3) self.assertEqual(self.resconfig.count_hardware(), 1) self.assertEqual(self.resconfig.count_process(), 2) self.resconfig._dut_requirements = [] self.resconfig._resolve_dut_count() self.assertEqual(self.resconfig.count_duts(), 0) self.assertEqual(self.resconfig.count_hardware(), 0) self.assertEqual(self.resconfig.count_process(), 0) def test_dut_counts_invalid_fields(self): self.resconfig._dut_requirements = [ResourceRequirements({}), ResourceRequirements({"type": "process"}), ResourceRequirements({"type": "hardware"})] self.assertRaises(ValueError, self.resconfig._resolve_dut_count) def test_resolve_requirements(self): self.resconfig.resolve_configuration(self.testreqs) self.assertEqual(self.resconfig.get_dut_configuration()[0].get_requirements(), self.testreqsresult[0]) self.assertEqual(self.resconfig.get_dut_configuration()[1].get_requirements(), self.testreqsresult[1]) def test_dut_requirements_single(self): self.resconfig.resolve_configuration( { "requirements": { "duts": { "*": { "count": 1, "nick": None }, 1: { "nick": "Router{i}" } } } } ) self.assertEqual([self.resconfig.get_dut_configuration()[0].get_requirements()], [ {"type": "hardware", "allowed_platforms": [], "nick": "Router1"} ]) def test_dut_reqs_three_duts(self): self.resconfig.resolve_configuration( { "requirements": { "duts": { "*": { "count": 3, "allowed_platforms": ["K64F"], "application": {"bin": "hex.bin"} }, 1: {"application": {"bin": "my_hex.bin"}}, 2: {"application": {"bin": "my_hex2.bin"}} } } } ) self.assertEqual([req.get_requirements() for req in self.resconfig.get_dut_configuration()], [ {"type": "hardware", "allowed_platforms": ["K64F"], "application": {"bin": "my_hex.bin"}, "nick": None }, {"type": "hardware", "allowed_platforms": ["K64F"], "application": {"bin": "my_hex2.bin"}, "nick": None }, {"type": "hardware", "allowed_platforms": ["K64F"], "application": {"bin": "hex.bin"}, "nick": None } ] ) def test_dut_reqs_multiple_duts(self): self.resconfig.resolve_configuration( { "requirements": { "duts": { "*": { "count": 100, "allowed_platforms": ["K64F"], "application": {"bin": "hex.bin"} }, "1..50": {"application": {"bin": "my_hex.bin"}, "nick": "DUT{i}"}, 51: {"application": {"bin": "my_hex2.bin"}, "nick": "leader"}, "52..100": {"application": {"bin": "my_hex3.bin"}} } } } ) self.assertEqual(len(self.resconfig.get_dut_configuration()), 100) self.assertEqual(self.resconfig.get_dut_configuration()[0].get_requirements(), {"type": "hardware", "allowed_platforms": ["K64F"], "application": {"bin": "my_hex.bin"}, "nick": "DUT1"}) self.assertEqual(self.resconfig.get_dut_configuration()[50].get_requirements(), {"type": "hardware", "allowed_platforms": ["K64F"], "application": {"bin": "my_hex2.bin"}, "nick": "leader"}) self.assertEqual(self.resconfig.get_dut_configuration()[51].get_requirements(), {"type": "hardware", "allowed_platforms": ["K64F"], "application": {"bin": "my_hex3.bin"}, "nick": None}) def test_dut_reqs_locations(self): self.resconfig.resolve_configuration( {"requirements": { "duts": { "*": {"count": 1}, 1: {"location": [1, "{i}+{n}*{xy}"]} } } } ) self.assertEqual([req.get_requirements() for req in self.resconfig.get_dut_configuration()], [{"type": "hardware", "allowed_platforms": [], "location": [1, 2], "nick": None}]) def test_dut_reqs_locations_i(self): self.resconfig.resolve_configuration( { "requirements": { "duts": { "*": {"count": 5}, "1..5": {"location": [1, "{i}"]} } } } ) self.assertEqual([req.get_requirements() for req in self.resconfig.get_dut_configuration()], [ {"type": "hardware", "allowed_platforms": [], "location": [1, 1], "nick": None }, {"type": "hardware", "allowed_platforms": [], "location": [1, 2], "nick": None }, {"type": "hardware", "allowed_platforms": [], "location": [1, 3], "nick": None }, {"type": "hardware", "allowed_platforms": [], "location": [1, 4], "nick": None }, {"type": "hardware", "allowed_platforms": [], "location": [1, 5], "nick": None } ] ) def test_reqs_locations_circle(self): self.resconfig.resolve_configuration( { "requirements": { "duts": { "*": {"count": 1}, 1: {"location": ["10*math.cos((3.5*{i})*({pi}/180))", "10*math.sin((3.5*{i})*({pi}/180))"]} } } }) self.assertEqual( [ req.get_requirements() for req in self.resconfig.get_dut_configuration() ], [ { "type": "hardware", "allowed_platforms": [], "location": [ eval("10*math.cos((3.5*1)*({pi}/180))".replace("{pi}", str(math.pi))), eval("10*math.sin((3.5*1)*({pi}/180))".replace("{pi}", str(math.pi))) ], "nick": None}]) def test_dut_reqs_invalid_location(self): self.resconfig.resolve_configuration( { "requirements": { "duts": { "*": {"count": 1}, 1: {"location": ["1+/", "+/"]} } } } ) def test_dut_reqs_invalid_loc_len(self): self.resconfig.resolve_configuration( { "requirements": { "duts": { "*": {"count": 1}, 1: {"location": ["1+1"]} } } } ) def test_dut_reqs_any_indexed_regression(self): # pylint: disable=invalid-name self.resconfig.resolve_configuration( { "requirements": { "duts": { "*": { "count": 2, "allowed_platforms": [], "type": "hardware" }, "1": { "allowed_platforms": ["Tplat1"], "custom_key": "value" }, "2": { "allowed_platforms": ["Tplat2"], "custom_key2": "value" } } } } ) reqs = self.resconfig.get_dut_configuration() self.assertDictEqual(reqs[0].get_requirements(), {"allowed_platforms": ["Tplat1"], "custom_key": "value", "type": "hardware", "nick": None}) self.assertDictEqual(reqs[1].get_requirements(), {"allowed_platforms": ["Tplat2"], "custom_key2": "value", "type": "hardware", "nick": None}) def test_setting_dut_parameters(self): self.resconfig.resolve_configuration(self.testreqs) conf = self.resconfig.get_dut_configuration(1) conf.set("test", "test") self.resconfig.set_dut_configuration(1, conf) res = self.testreqsresult res[1]["test"] = "test" self.assertEqual([req.get_requirements() for req in self.resconfig.get_dut_configuration()], res) def test_init_with_logger(self): logger = mock.Mock() testrc = ResourceConfig(logger=logger) self.assertEqual(testrc.logger, logger)
class TestVerify(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_dut_counts(self): pass def test_dut_counts_invalid_fields(self): pass def test_resolve_requirements(self): pass def test_dut_requirements_single(self): pass def test_dut_reqs_three_duts(self): pass def test_dut_reqs_multiple_duts(self): pass def test_dut_reqs_locations(self): pass def test_dut_reqs_locations_i(self): pass def test_reqs_locations_circle(self): pass def test_dut_reqs_invalid_location(self): pass def test_dut_reqs_invalid_loc_len(self): pass def test_dut_reqs_any_indexed_regression(self): pass def test_setting_dut_parameters(self): pass def test_init_with_logger(self): pass
17
0
17
0
17
0
1
0
1
4
2
0
16
3
16
88
294
17
277
25
260
1
72
25
55
1
2
0
16
2,129
ARMmbed/icetea
ARMmbed_icetea/test/test_reports.py
test.test_reports.ReportCase
class ReportCase(unittest.TestCase): """ One unittest TestCase for all report types. """ """ ReportConsole unit tests """ def test_reportconsole_no_results(self): saved_stdout = sys.stdout results = ResultList() try: out = StringIO() sys.stdout = out report = ReportConsole(results) report.generate() output = out.getvalue().strip() lines = output.split("\n") self.assertEqual(len(lines), 13) finally: sys.stdout = saved_stdout def test_reportconsole_one_results(self): saved_stdout = sys.stdout results = ResultList() results.append(Result()) try: out = StringIO() sys.stdout = out report = ReportConsole(results) report.generate() output = out.getvalue().strip() lines = output.split("\n") self.assertEqual(len(lines), 15) self.assertRegexpMatches(lines[8], r"Final Verdict.*INCONCLUSIVE", lines[8]) self.assertRegexpMatches(lines[9], r"count.*1", lines[9]) self.assertRegexpMatches(lines[10], r"passrate.*0.00 \%", lines[10]) finally: sys.stdout = saved_stdout def test_reportconsole_multiple_results(self): # pylint: disable=invalid-name saved_stdout = sys.stdout results = ResultList() results.append(Result()) results.append(Result()) results.append(Result()) try: out = StringIO() sys.stdout = out report = ReportConsole(results) report.generate() output = out.getvalue().strip() lines = output.split("\n") self.assertEqual(len(lines), 17) self.assertRegexpMatches(lines[10], r"Final Verdict.*INCONCLUSIVE", lines[10]) self.assertRegexpMatches(lines[11], r"count.*3", lines[11]) self.assertRegexpMatches(lines[12], r"passrate.*0.00 \%", lines[12]) finally: sys.stdout = saved_stdout def test_console_multiple_results_with_retries(self): saved_stdout = sys.stdout results = ResultList() res1 = Result() res1.set_verdict("fail", 1001, 1) res1.retries_left = 1 res2 = Result() res2.set_verdict("pass", 0, 1) res2.retries_left = 0 results.append(res1) results.append(res2) results.append(Result()) results.append(Result()) results.append(Result()) try: out = StringIO() sys.stdout = out report = ReportConsole(results) report.generate() output = out.getvalue().strip() lines = output.split("\n") self.assertEqual(len(lines), 21) self.assertRegexpMatches(lines[3], "Yes", lines[4]) self.assertRegexpMatches(lines[4], "No", lines[5]) self.assertRegexpMatches(lines[12], "Final Verdict.*INCONCLUSIVE", lines[12]) self.assertRegexpMatches(lines[13], "count.*5", lines[13]) self.assertRegexpMatches(lines[14], r"passrate.*50.00 \%", lines[14]) finally: sys.stdout = saved_stdout def test_console_pass_with_retries(self): saved_stdout = sys.stdout results = ResultList() res1 = Result() res1.set_verdict("fail", 1001, 1) res1.retries_left = 1 res2 = Result() res2.set_verdict("pass", 0, 1) res2.retries_left = 0 results.append(res1) results.append(res2) try: out = StringIO() sys.stdout = out report = ReportConsole(results) report.generate() output = out.getvalue().strip() lines = output.split("\n") self.assertEqual(len(lines), 17) self.assertRegexpMatches(lines[3], "Yes", lines[4]) self.assertRegexpMatches(lines[4], "No", lines[5]) self.assertRegexpMatches(lines[9], "Final Verdict.*PASS", lines[9]) self.assertRegexpMatches(lines[10], "count.*2", lines[10]) self.assertRegexpMatches(lines[11], r"passrate.*50.00 \%", lines[11]) self.assertRegexpMatches(lines[12], r"passrate excluding retries.*100.00 \%", lines[12]) finally: sys.stdout = saved_stdout def test_reportconsole_skip(self): saved_stdout = sys.stdout results = ResultList() res = Result() res.skip_reason = "Skip_reason" res.set_verdict("skip", -1, -1) results.append(res) try: out = StringIO() sys.stdout = out report = ReportConsole(results) report.generate() output = out.getvalue().strip() lines = output.split("\n") self.assertEqual(len(lines), 15) self.assertRegexpMatches(lines[3], r"skip.*Skip_reason") self.assertRegexpMatches(lines[8], r"Final Verdict.*PASS", lines[8]) self.assertRegexpMatches(lines[9], r"count.*1", lines[9]) self.assertRegexpMatches(lines[11], r"passrate.*0.00 \%", lines[10]) self.assertRegexpMatches(lines[12], r"skip.*1", lines[10]) finally: sys.stdout = saved_stdout def test_reportconsole_decodefail(self): saved_stdout = sys.stdout failing_message = "\x00\x00\x00\x00\x00\x00\x01\xc8" results = ResultList() res = Result() res.set_verdict("fail", 1001, 0) res.fail_reason = failing_message results.append(res) try: out = StringIO() sys.stdout = out report = ReportConsole(results) report.generate() output = out.getvalue().strip() lines = output.split("\n") self.assertEqual(len(lines), 15) self.assertRegexpMatches(lines[8], r"Final Verdict.*FAIL", lines[8]) self.assertRegexpMatches(lines[9], r"count.*1", lines[9]) self.assertRegexpMatches(lines[10], r"passrate.*0.00 \%", lines[10]) finally: sys.stdout = saved_stdout """ ReportJunit tests """ def test_junit_default(self): str_should_be = '<testsuite failures="0" tests="1" errors="0" skipped="0">\n\ <testcase classname="test-case-A1" name="unknown" time="20"></testcase>\n\ </testsuite>' results = ResultList() results.append(Result({"testcase": "test-case-A1", "verdict": "PASS", "duration": 20})) junit = ReportJunit(results) str_report = junit.to_string() xml_shouldbe = ET.fromstring(str_should_be) report_xml = ET.fromstring(str_report) self.assertDictEqual(xml_shouldbe.attrib, report_xml.attrib) self.assertDictEqual(xml_shouldbe.find("testcase").attrib, report_xml.find( "testcase").attrib) self.assertEqual(len(xml_shouldbe.findall("testcase")), len(report_xml.findall( "testcase"))) def test_junit_multiple(self): str_should_be = '<testsuite failures="2" tests="7" errors="1" skipped="1">\n\ <testcase classname="test-case-A1" name="unknown" time="20"></testcase>\n\ <testcase classname="test-case-A2" name="unknown" time="50"></testcase>\n\ <testcase classname="test-case-A3" name="unknown" time="120"></testcase>\n\ <testcase classname="test-case-A4" name="unknown" time="120">\n\ <failure message="unknown"></failure>\n\ </testcase>\n\ <testcase classname="test-case-A5" name="unknown" time="1">\n\ <skipped></skipped>\n\ </testcase>\n\ <testcase classname="test-case-A6" name="unknown" time="2">\n\ <error message="unknown"></error>\n\ </testcase>\n\ <testcase classname="test-case-A4" name="unknown" time="1220">\n\ <failure message="WIN blue screen"></failure>\n\ </testcase>\n\ </testsuite>' shouldbe_xml = ET.fromstring(str_should_be) results = ResultList() results.append(Result({"testcase": "test-case-A1", "verdict": "PASS", "duration": 20})) results.append(Result({"testcase": "test-case-A2", "verdict": "PASS", "duration": 50})) results.append(Result({"testcase": "test-case-A3", "verdict": "PASS", "duration": 120})) results.append(Result({"testcase": "test-case-A4", "verdict": "FAIL", "reason": "unknown", "duration": 120})) results.append(Result({"testcase": "test-case-A5", "verdict": "SKIP", "reason": "unknown", "duration": 1})) results.append(Result({"testcase": "test-case-A6", "verdict": "INCONCLUSIVE", "reason": "unknown", "duration": 2})) results.append( Result({"testcase": "test-case-A4", "verdict": "FAIL", "reason": "WIN blue screen", "duration": 1220})) junit = ReportJunit(results) str_report = junit.to_string() is_xml = ET.fromstring(str_report) self.assertDictEqual(is_xml.attrib, {"failures": "2", "tests": "7", "errors": "1", "skipped": "1"}) self.assertEqual(len(is_xml.findall("testcase")), len(shouldbe_xml.findall("testcase"))) self.assertEqual(len(is_xml.findall("failure")), len(shouldbe_xml.findall("failure"))) self.assertEqual(len(is_xml.findall("skipped")), len(shouldbe_xml.findall("skipped"))) self.assertEqual(len(is_xml.findall("error")), len(shouldbe_xml.findall("error"))) def test_junit_hex_escape_support(self): reprstring = hex_escape_str(b'\x00\x00\x00\x00\x00\x00\x01\xc8') str_should_be = '<testsuite failures="1" tests="1" errors="0" skipped="0">\n\ <testcase classname="test-case-A1" name="unknown" time="20">\n\ <failure message="' + reprstring + '"></failure>\n\ </testcase>\n\ </testsuite>' results = ResultList() results.append(Result({"testcase": "test-case-A1", "verdict": "FAIL", "reason": b'\x00\x00\x00\x00\x00\x00\x01\xc8', "duration": 20})) junit = ReportJunit(results) str_report = junit.to_string() xml_report = ET.fromstring(str_report) shouldbe_report = ET.fromstring(str_should_be) self.assertDictEqual(xml_report.attrib, shouldbe_report.attrib) reported_tc = xml_report.find("testcase") failure_reason = reported_tc.find("failure") required_tc = shouldbe_report.find("testcase") required_reason = required_tc.find("failure") self.assertTrue(required_reason.attrib["message"] == failure_reason.attrib["message"]) def test_junit_hides(self): str_should_be1 = '<testsuite failures="0" tests="3" errors="0" skipped="0">\n\ <testcase classname="test-case-A1" name="unknown" time="20"></testcase>\n\ <testcase classname="test-case-A4" name="unknown" time="120"></testcase>\n\ <testcase classname="test-case-A6" name="unknown" time="2"></testcase>\n\ </testsuite>' results = ResultList() results.append(Result({"testcase": "test-case-A1", "verdict": "PASS", "duration": 20})) failres = Result({"testcase": "test-case-A4", "verdict": "FAIL", "reason": "unknown", "duration": 120}) failres.retries_left = 1 results.append(failres) results.append( Result({"testcase": "test-case-A4", "verdict": "PASS", "duration": 120})) incres = Result({"testcase": "test-case-A6", "verdict": "INCONCLUSIVE", "reason": "unknown", "duration": 2}) incres.retries_left = 1 results.append(incres) results.append(Result({"testcase": "test-case-A6", "verdict": "PASS", "duration": 2})) junit = ReportJunit(results) str_report = junit.to_string() report_xml = ET.fromstring(str_report) shouldbe_xml = ET.fromstring(str_should_be1) self.assertDictEqual(report_xml.attrib, shouldbe_xml.attrib) self.assertEqual(len(report_xml.findall("testcase")), len(shouldbe_xml.findall("testcase"))) str_should_be2 = '<testsuite failures="0" tests="3" errors="1" skipped="0">\n\ <testcase classname="test-case-A1" name="unknown" time="20"></testcase>\n\ <testcase classname="test-case-A4" name="unknown" time="12"></testcase>\n\ <testcase classname="test-case-A6" name="unknown" time="2">\n\ <error message="unknown"></error>\n\ </testcase>\n\ </testsuite>' results = ResultList() results.append(Result({"testcase": "test-case-A1", "verdict": "PASS", "duration": 20})) failres = Result({"testcase": "test-case-A4", "verdict": "FAIL", "reason": "unknown", "duration": 120}) failres.retries_left = 1 results.append(failres) results.append(Result({"testcase": "test-case-A4", "verdict": "PASS", "duration": 12})) results.append( Result({"testcase": "test-case-A6", "verdict": "INCONCLUSIVE", "reason": "unknown", "duration": 2})) junit = ReportJunit(results) str_report = junit.to_string() report_xml = ET.fromstring(str_report) shouldbe_xml = ET.fromstring(str_should_be2) self.assertDictEqual(report_xml.attrib, shouldbe_xml.attrib) self.assertEqual(len(report_xml.findall("testcase")), len(shouldbe_xml.findall("testcase"))) errors = [] for elem in report_xml.findall("testcase"): if elem.find("error") is not None: errors.append(elem) self.assertEqual(len(errors), 1) """ ReportHtml tests """ def test_html_report(self): results = ResultList() results.append(Result({"testcase": "test-case-A1", "verdict": "PASS", "duration": 20})) failres = Result({"testcase": "test-case-A4", "verdict": "FAIL", "reason": "unknown", "duration": 120}) results.append(failres) html_report = ReportHtml(results) # pylint: disable=protected-access hotml = html_report._create(title='Test Results', heads={'Build': '', 'Branch': ""}, refresh=None) doc = html.document_fromstring(hotml) body = doc.get_element_by_id("body") passes = body.find_class("item_pass") fails = body.find_class("item_fail") self.assertEqual(len(passes), len(fails))
class ReportCase(unittest.TestCase): ''' One unittest TestCase for all report types. ''' def test_reportconsole_no_results(self): pass def test_reportconsole_one_results(self): pass def test_reportconsole_multiple_results(self): pass def test_console_multiple_results_with_retries(self): pass def test_console_pass_with_retries(self): pass def test_reportconsole_skip(self): pass def test_reportconsole_decodefail(self): pass def test_junit_default(self): pass def test_junit_multiple(self): pass def test_junit_hex_escape_support(self): pass def test_junit_hides(self): pass def test_html_report(self): pass
13
1
25
0
24
0
1
0.05
1
2
2
0
12
0
12
84
325
19
293
104
280
14
236
104
223
3
2
2
14
2,130
ARMmbed/icetea
ARMmbed_icetea/test/test_randomize.py
test.test_randomize.RandomizeTestcase
class RandomizeTestcase(unittest.TestCase): def test_full_args(self): self.assertGreaterEqual(Randomize.random_integer(7, 3).value, 3) self.assertLessEqual(Randomize.random_integer(7, 3).value, 7) self.assertIn(Randomize.random_list_elem(['a', 'bb', 'cc']).value, ['a', 'bb', 'cc']) self.assertGreaterEqual(len(Randomize.random_string(7, 3, lambda x: random.choice(x), x='e34r')), 3) self.assertLessEqual(len(Randomize.random_string(7, 3, lambda x: random.choice(x), x='e34r')), 7) self.assertIn(Randomize.random_string(chars=["aa", "bb", "ceedee"]).value, ["a", "b", "c", "d", "e"]) self.assertIn(Randomize.random_array_elem(['a', 'bb', 'cc']).value, [['a'], ['bb'], ['cc']]) self.assertGreaterEqual(len(Randomize.random_string_array(9, 3, 7, 2, lambda x: random.choice(x), x='e34r')), 3) self.assertLessEqual(len(Randomize.random_string_array(9, 3, 7, 2, lambda x: random.choice(x), x='e34r')), 9) def test_chars_not_str(self): with self.assertRaises(ValueError): Randomize.random_string(7, 3, chars=6) def test_chars_not_list(self): with self.assertRaises(TypeError): Randomize.random_list_elem([6]) def test_random_str_lst_chars_no_str(self): # pylint: disable=invalid-name with self.assertRaises(TypeError): Randomize.random_string(2, 1, chars=["a", "abc", 1]) def test_random_integer_add(self): i = Randomize.random_integer(6) self.assertTrue(i + 6 == i.value + 6) self.assertTrue(6 + i == i.value + 6) def test_random_string_add(self): rand_str = Randomize.random_string(5) value = rand_str.value self.assertEqual(rand_str + ' hello', value + ' hello') self.assertEqual('hello ' + rand_str, 'hello ' + value) def test_random_string_array_add(self): rand_str = Randomize.random_string_array(5, 3) value = rand_str.value self.assertEqual(rand_str + ['world'], value + ['world']) self.assertEqual(['world'] + rand_str, ['world'] + value) def test_random_integer_iadd(self): rand_integer = Randomize.random_integer(6) value = rand_integer.value rand_integer += 6 value += 6 self.assertEqual(rand_integer.value, value) def test_random_integer_repr(self): rand_integer = Randomize.random_integer(6) self.assertEqual("%s" % rand_integer, str(rand_integer.value)) def test_random_string_repr(self): rand_str = Randomize.random_string(5) self.assertEqual("%s" % rand_str, str(rand_str.value)) def test_random_string_array_repr(self): rand_str_ar = Randomize.random_string_array(5, 3) self.assertEqual("%s" % rand_str_ar, str(rand_str_ar.value)) def test_random_string_iter(self): for elem in Randomize.random_string(7, 3): self.assertTrue(isinstance(elem, str)) def test_random_string_array_iter(self): for elem in Randomize.random_string_array(7, 3): self.assertTrue(isinstance(elem, str)) def test_random_string_get_item(self): rand_str = Randomize.random_string(6) value = rand_str.value self.assertEqual(rand_str[0], value[0]) def test_random_string_array_get_item(self): # pylint: disable=invalid-name rand_str_ar = Randomize.random_string_array(6, 3) value = rand_str_ar.value self.assertEqual(rand_str_ar[0], value[0]) def test_random_string_str(self): s_str = Randomize.random_string(6) self.assertEqual(str(s_str), s_str.value) def test_reproduce(self): seed = Randomize.random_integer(20, 3).value def user_func(seed): random.seed(seed) return random.randint(5, 15), random.randint(15, 25) rep1, rep2 = user_func(seed) rep3, rep4 = user_func(seed) self.assertEqual(rep1, rep3) self.assertEqual(rep2, rep4) def test_store_load(self): s_int = Randomize.random_integer(8, 4) s_str = Randomize.random_string(8, 4, lambda x: random.choice(x), x='e34r') s_str_a = Randomize.random_string_array(10, 6, 7, 4) temp_file = tempfile.NamedTemporaryFile(delete=False) s_int.store(temp_file.name) self.assertEqual(s_int.value, s_int.load(temp_file.name).value) temp_file.close() temp_file = tempfile.NamedTemporaryFile(delete=False) s_str.store(temp_file.name) self.assertEqual(s_str.value, s_str.load(temp_file.name).value) temp_file.close() temp_file = tempfile.NamedTemporaryFile(delete=False) s_str_a.store(temp_file.name) self.assertEqual(s_str_a.value, s_str_a.load(temp_file.name).value) temp_file.close()
class RandomizeTestcase(unittest.TestCase): def test_full_args(self): pass def test_chars_not_str(self): pass def test_chars_not_list(self): pass def test_random_str_lst_chars_no_str(self): pass def test_random_integer_add(self): pass def test_random_string_add(self): pass def test_random_string_array_add(self): pass def test_random_integer_iadd(self): pass def test_random_integer_repr(self): pass def test_random_string_repr(self): pass def test_random_string_array_repr(self): pass def test_random_string_iter(self): pass def test_random_string_array_iter(self): pass def test_random_string_get_item(self): pass def test_random_string_array_get_item(self): pass def test_random_string_str(self): pass def test_reproduce(self): pass def user_func(seed): pass def test_store_load(self): pass
20
0
7
1
6
0
1
0.02
1
4
1
0
18
0
18
90
139
29
110
44
90
2
91
44
71
2
2
1
21
2,131
ARMmbed/icetea
ARMmbed_icetea/test/test_plugin/duplicate_plugin/test_plugin.py
test.test_plugin.duplicate_plugin.test_plugin.Plugin
class Plugin(PluginBase): def __init__(self): super(Plugin, self).__init__() def get_bench_api(self): return {"test_plugin": self.test_plugin} def test_plugin(self): return 2
class Plugin(PluginBase): def __init__(self): pass def get_bench_api(self): pass def test_plugin(self): pass
4
0
2
0
2
0
1
0
1
1
0
0
3
0
3
10
9
2
7
4
3
0
7
4
3
1
2
0
3
2,132
ARMmbed/icetea
ARMmbed_icetea/test/test_logmanager.py
test.test_logmanager.TraverseJsonObjTest
class TraverseJsonObjTest(unittest.TestCase): def test_stays_untouched(self): test_dict = [{"a": "aa", "b": ["c", "d", {"e": "aa", "f": "aa"}]}] self.assertEqual(test_dict, traverse_json_obj(test_dict)) def test_all_modified(self): test_dict = [{"a": "aa", "b": ["c", "d", {"e": "aa", "f": "aa"}]}] def modify(value): return "bb" if value == "aa" else value expected = [{"a": "bb", "b": ["c", "d", {"e": "bb", "f": "bb"}]}] self.assertEqual(expected, traverse_json_obj(test_dict, callback=modify))
class TraverseJsonObjTest(unittest.TestCase): def test_stays_untouched(self): pass def test_all_modified(self): pass def modify(value): pass
4
0
5
1
4
0
1
0
1
0
0
0
2
0
2
74
14
4
10
7
6
0
10
7
6
2
2
0
4
2,133
ARMmbed/icetea
ARMmbed_icetea/test/test_logmanager.py
test.test_logmanager.CustomFormatterTest
class CustomFormatterTest(unittest.TestCase): def test_benchformatter_formats_timestamp(self): # pylint: disable=invalid-name formatter = LogManager.BenchFormatter("%(asctime)s | %(source)s %(type)s %(threadName)s: " "%(message)s", "%Y-%m-%dT%H:%M:%S.%FZ") record = create_log_record("test_message") time_str = formatter.formatTime(record, "%Y-%m-%dT%H:%M:%S.%FZ") # Check that T exists, should be in between date and time. self.assertTrue(time_str.rfind("T") > 0) # Check that date format matches ISO-8601 date = time_str[:time_str.rfind("T")] self.assertRegexpMatches(date, r"^([0-9]{4})(-?)(1[0-2]|0[1-9])\2(3[01]|0[1-9]|[12][0-9])$") # Chech that time format matches ISO-8601 time_ending = time_str[time_str.rfind("T") + 1: time_str.rfind(".")] self.assertRegexpMatches(time_ending, r"^(2[0-3]|[01][0-9]):?([0-5][0-9]):?([0-5][0-9])$") # Check that time_str ends with Z to show it's UTC self.assertTrue(time_str.endswith("Z")) # Check that milliseconds exist millis = time_str[time_str.rfind(".") + 1: time_str.rfind("Z")] self.assertRegexpMatches(millis, r"([0-9][0-9][0-9])")
class CustomFormatterTest(unittest.TestCase): def test_benchformatter_formats_timestamp(self): pass
2
0
24
6
13
6
1
0.43
1
1
1
0
1
0
1
73
26
7
14
8
12
6
13
8
11
1
2
0
1
2,134
ARMmbed/icetea
ARMmbed_icetea/test/test_logmanager.py
test.test_logmanager.ContextFilterTest
class ContextFilterTest(unittest.TestCase): def setUp(self): self.contextfilter = ContextFilter() def test_filter_base64(self): msg = "aaa=" record = create_log_record(msg) self.contextfilter.filter(record) self.assertEqual(msg, record.msg) msg = [] [msg.append("a") for _ in range(ContextFilter.MAXIMUM_LENGTH)] msg = "".join(msg) record = create_log_record(msg) self.contextfilter.filter(record) expected = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...[9950 more bytes]" self.assertEqual(expected, record.msg) msg = [] [msg.append("a") for _ in range(ContextFilter.MAXIMUM_LENGTH * 2)] msg = "".join(msg) record = create_log_record(msg) self.contextfilter.filter(record) expected = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...[19950 more bytes]" self.assertEqual(expected, record.msg) msg = [] [msg.append("a") for _ in range(ContextFilter.MAXIMUM_LENGTH - 1)] msg = "".join(msg) record = create_log_record(msg) self.contextfilter.filter(record) self.assertEqual(msg, record.msg) msg = [] [msg.append("a") for _ in range(ContextFilter.MAXIMUM_LENGTH + 1)] msg = "".join(msg) record = create_log_record(msg) self.contextfilter.filter(record) expected = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...[9951 more bytes]" self.assertEqual(expected, record.msg) def test_filter_human_readable(self): msg = [" "] [msg.append("a") for _ in range(ContextFilter.MAXIMUM_LENGTH)] msg = "".join(msg) record = create_log_record(msg) expected = " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...[9951 more bytes]" self.contextfilter.filter(record) self.assertEqual(expected, record.msg) def test_filter_binary_data(self): msg = [] [msg.append(os.urandom(1024)) for _ in range(ContextFilter.MAXIMUM_LENGTH +1)] msg = b"".join(msg) expected = "{}...[10240974 more bytes]".format(msg[:50]) record = create_log_record(msg) self.contextfilter.filter(record) self.assertEqual(expected, record.msg) msg = [] [msg.append(u'\ufffd') for _ in range(ContextFilter.MAXIMUM_LENGTH + 1)] msg = "".join(msg) if not IS_PYTHON3: expected = u"{}...[9951 more bytes]".format(repr(msg[:50])) else: expected = u"{}...[9951 more bytes]".format(msg[:50]) record = create_log_record(msg) self.contextfilter.filter(record) self.assertEqual(expected, record.msg)
class ContextFilterTest(unittest.TestCase): def setUp(self): pass def test_filter_base64(self): pass def test_filter_human_readable(self): pass def test_filter_binary_data(self): pass
5
0
17
2
15
0
1
0
1
2
1
0
4
1
4
76
71
10
61
18
56
0
60
15
55
2
2
1
5
2,135
ARMmbed/icetea
ARMmbed_icetea/test/test_logmanager.py
test.test_logmanager.ConfigFileTests
class ConfigFileTests(unittest.TestCase): def setUp(self): self.original_config = LogManager.LOGGING_CONFIG def test_configs_read(self): filepath = os.path.abspath(os.path.join(__file__, os.path.pardir, "tests", "does_not_exist.json")) with self.assertRaises(IOError): LogManager.init_base_logging(config_location=filepath) filepath = os.path.abspath(os.path.join(__file__, os.path.pardir, "tests", "logging_config.json")) LogManager._read_config(filepath) def test_configs_merge(self): filepath = os.path.abspath(os.path.join(__file__, os.path.pardir, "tests", "logging_config.json")) LogManager._read_config(filepath) self.assertDictEqual(LogManager.LOGGING_CONFIG.get("test_logger"), {"level": "ERROR"}) def test_configs_schema_validation(self): filepath = os.path.abspath(os.path.join(__file__, os.path.pardir, "tests", "erroneous_logging_config.json")) with self.assertRaises(ValidationError): LogManager._read_config(filepath) filepath = os.path.abspath(os.path.join(__file__, os.path.pardir, "tests", "logging_config.json")) LogManager._read_config(filepath) def tearDown(self): LogManager.LOGGING_CONFIG = self.original_config
class ConfigFileTests(unittest.TestCase): def setUp(self): pass def test_configs_read(self): pass def test_configs_merge(self): pass def test_configs_schema_validation(self): pass def tearDown(self): pass
6
0
5
0
5
0
1
0
1
1
0
0
5
1
5
77
30
4
26
10
20
0
21
10
15
1
2
1
5
2,136
ARMmbed/icetea
ARMmbed_icetea/test/test_iceteamanager.py
test.test_iceteamanager.MockResults
class MockResults(object): def __init__(self, fails=0, inconcs=0): self.fails = fails self.inconcs = inconcs def failure_count(self): return self.fails def inconclusive_count(self): return self.inconcs def __len__(self): return self.fails + self.inconcs
class MockResults(object): def __init__(self, fails=0, inconcs=0): pass def failure_count(self): pass def inconclusive_count(self): pass def __len__(self): pass
5
0
2
0
2
0
1
0
1
0
0
0
4
2
4
4
13
3
10
7
5
0
10
7
5
1
1
0
4
2,137
ARMmbed/icetea
ARMmbed_icetea/test/test_httpapi.py
test.test_httpapi.MockedRequestsResponse
class MockedRequestsResponse(object): # pylint: disable=too-few-public-methods def __init__(self, status_code=200, json_data=None): self.json_data = json_data if json_data else {"key1": "value1"} self.status_code = status_code self.url = '' self.headers = {"head": "ers"} self.text = "This is test text" self.request = self def json(self): return self.json_data
class MockedRequestsResponse(object): def __init__(self, status_code=200, json_data=None): pass def json(self): pass
3
0
5
0
5
0
2
0.1
1
0
0
0
2
6
2
2
11
1
10
9
7
1
10
9
7
2
1
0
3
2,138
ARMmbed/icetea
ARMmbed_icetea/test/test_genericprocess.py
test.test_genericprocess.MockLogger
class MockLogger(object): def __init__(self): pass def info(self, *args, **kwargs): pass def debug(self, *args, **kwargs): pass def warning(self, *args, **kwargs): pass def error(self, *args, **kwargs): pass
class MockLogger(object): def __init__(self): pass def info(self, *args, **kwargs): pass def debug(self, *args, **kwargs): pass def warning(self, *args, **kwargs): pass def error(self, *args, **kwargs): pass
6
0
2
0
2
0
1
0
1
0
0
0
5
0
5
5
15
4
11
6
5
0
11
6
5
1
1
0
5
2,139
ARMmbed/icetea
ARMmbed_icetea/test/tests/matching_test/feature_and_component_test.py
test.tests.matching_test.feature_and_component_test.Testcase
class Testcase(Bench): def __init__(self): Bench.__init__(self, name="both_feat_and_comp_test", title="unittest matching", status="development", type="acceptance", purpose="dummy", component=["icetea_ut", "component2"], feature=["feature2"], requirements={ "duts": { '*': { "count": 0 } } } ) def case(self): pass
class Testcase(Bench): def __init__(self): pass def case(self): pass
3
0
10
0
10
0
1
0
1
0
0
0
2
0
2
108
21
1
20
3
17
0
5
3
2
1
3
0
2
2,140
ARMmbed/icetea
ARMmbed_icetea/test/test_events.py
test.test_events.MockLineProvider
class MockLineProvider(object): # pylint: disable=too-few-public-methods def __init__(self): self.counter = 0 def readline(self, timeout): if self.counter == 2: self.counter = 0 return "found" sleep(randint(0, timeout)) self.counter += 1 return "nothing"
class MockLineProvider(object): def __init__(self): pass def readline(self, timeout): pass
3
0
5
0
5
0
2
0.1
1
0
0
0
2
1
2
2
11
1
10
4
7
1
10
4
7
2
1
1
3
2,141
ARMmbed/icetea
ARMmbed_icetea/test/test_result.py
test.test_result.ResultTestcase
class ResultTestcase(unittest.TestCase): def setUp(self): self.args_tc = argparse.Namespace( available=False, version=False, bin=None, binary=False, channel=None, clean=False, cloud=False, component=False, device='*', gdb=None, gdbs=None, gdbs_port=2345, group=False, iface=None, kill_putty=False, list=False, listsuites=False, log='./log', my_duts=None, nobuf=None, pause_when_external_dut=False, putty=False, reset=False, silent=True, skip_case=False, skip_rampdown=False, skip_rampup=False, platform=None, status=False, suite=None, tc="test_cmdline", tc_cfg=None, tcdir="examples", testtype=False, type="process", subtype=None, use_sniffer=False, valgrind=False, valgrind_tool=None, verbose=False, repeat=0, feature=None, suitedir="./test/suites", forceflash_once=True, forceflash=False, stop_on_failure=False, json=False) def test_init(self): dictionary = {"retcode": 0} res = Result(kwargs=dictionary) self.assertEqual(res.get_verdict(), "pass") dictionary = {"retcode": 1} res = Result(kwargs=dictionary) self.assertEqual(res.get_verdict(), "fail") def test_set_verdict(self): result = Result() result.set_verdict("pass", 0, 10) self.assertEqual(result.get_verdict(), "pass") self.assertEqual(result.retcode, 0) self.assertEqual(result.get_duration(), '0:00:10') self.assertEqual(result.get_duration(True), '10') with self.assertRaises(ValueError): result.set_verdict("wat") def test_haslogs(self): result = Result() result.logpath = os.path.join(os.path.dirname(__file__), "test_logpath") files = result.has_logs() self.assertTrue(files) self.assertEqual(len(files), 2) result = Result() result.logpath = None files = result.has_logs() self.assertListEqual(files, []) def test_result_metainfo_generation(self): pass_result = Result() pass_result.set_verdict('pass', 0, 10) dinfo = DutInformation("Test_platform", "123456", "1") dinfo.build = Build(ref="test_file", type="file") pass_result.add_dutinformation(dinfo) self.args_tc.branch = "test_branch" self.args_tc.commitId = "123456" self.args_tc.gitUrl = "url" self.args_tc.buildUrl = "url2" self.args_tc.campaign = "campaign" self.args_tc.jobId = "test_job" self.args_tc.toolchain = "toolchain" self.args_tc.buildDate = "today" pass_result.build_result_metadata(args=self.args_tc) self.assertEqual(pass_result.build_branch, "test_branch") self.assertEqual(pass_result.buildcommit, "123456") self.assertEqual(pass_result.build_git_url, "url") self.assertEqual(pass_result.build_url, "url2") self.assertEqual(pass_result.campaign, "campaign") self.assertEqual(pass_result.job_id, "test_job") self.assertEqual(pass_result.toolchain, "toolchain") self.assertEqual(pass_result.build_date, "today")
class ResultTestcase(unittest.TestCase): def setUp(self): pass def test_init(self): pass def test_set_verdict(self): pass def test_haslogs(self): pass def test_result_metainfo_generation(self): pass
6
0
13
1
13
0
1
0
1
5
3
0
5
1
5
77
72
8
64
14
58
0
52
14
46
1
2
1
5
2,142
ARMmbed/icetea
ARMmbed_icetea/test/test_run_retcodes_fail.py
test.test_run_retcodes_fail.Testcase
class Testcase(Bench): """ This test case should always result in a failure. """ def __init__(self): Bench.__init__(self, name="test_run_retcodes_fail", title="unittest dut crash in testcase", status="development", type="acceptance", purpose="dummy", component=["Icetea_ut"], requirements={ "duts": { '*': { "count": 0 } }} ) def case(self): # pylint: disable=no-self-use """ Raise a TestStepFail to fail the test case. """ raise TestStepFail("This must fail!")
class Testcase(Bench): ''' This test case should always result in a failure. ''' def __init__(self): pass def case(self): ''' Raise a TestStepFail to fail the test case. ''' pass
3
2
10
0
9
2
1
0.39
1
1
1
0
2
0
2
108
25
1
18
3
15
7
5
3
2
1
3
0
2
2,143
ARMmbed/icetea
ARMmbed_icetea/test/test_plugin/plugin.py
test.test_plugin.plugin.Plugin
class Plugin(PluginBase): def __init__(self): super(Plugin, self).__init__() def get_bench_api(self): return {"test_plugin": self.test_plugin} def test_plugin(self): # pylint: disable=no-self-use return 1
class Plugin(PluginBase): def __init__(self): pass def get_bench_api(self): pass def test_plugin(self): pass
4
0
2
0
2
0
1
0.14
1
1
0
0
3
0
3
10
9
2
7
4
3
1
7
4
3
1
2
0
3
2,144
ARMmbed/icetea
ARMmbed_icetea/test/test_schemavalidation.py
test.test_schemavalidation.ValidatorTestcase
class ValidatorTestcase(unittest.TestCase): def setUp(self): with open(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "icetea_lib", 'tc_schema.json'))) as data_file: self.tc_meta_schema = json.load(data_file) def test_validation_successful(self): meta = {"name": "test_case", "title": "test_case", "status": "development", "purpose": "unittest", "component": ["validator"], "type": "smoke", "requirements": { "duts": { "*": { "count": 1, "type": "process", "platform_name": "test_plat", "application": { "version": "1.0.0", "name": "app_name", "bin": "binary", "cli_ready_trigger": "trigger", "cli_ready_trigger_timeout": 10, "init_cli_cmds": [], "post_cli_cmds": [], "bin_args": ["arg1", "arg2"] }, "location": [], } } }, "external": { "ExtApp": "ExtAppName" } } validate(meta, self.tc_meta_schema) def test_validation_successful_with_extra_fields_and_missing_fields(self): meta = {"extra_field": {"This field does not exist in the schema": "data"}} validate(meta, self.tc_meta_schema) def test_validation_causes_error(self): meta = {"name": "test_case", "title": "test_case", "status": "development", "purpose": "unittest", "component": "validator", # This should cause an error "type": "smoke", "requirements": { "duts": { "*": { "count": 1, "type": "process", "platform_name": "test_plat", "application": { "version": "1.0.0", "name": "app_name", "bin": "binary", "cli_ready_trigger": "trigger", "cli_ready_trigger_timeout": 10, "init_cli_cmds": [], "post_cli_cmds": [], "bin_args": ["arg1", "arg2"] }, "location": [0.0, 0.0], } } }, "external": { "ExtApp": "ExtAppName" } } with self.assertRaises(ValidationError): validate(meta, self.tc_meta_schema) meta["component"] = ["validator"] meta["status"] = "Not_exists" # This should cause an error with self.assertRaises(ValidationError): validate(meta, self.tc_meta_schema)
class ValidatorTestcase(unittest.TestCase): def setUp(self): pass def test_validation_successful(self): pass def test_validation_successful_with_extra_fields_and_missing_fields(self): pass def test_validation_causes_error(self): pass
5
0
20
1
19
1
1
0.03
1
1
0
0
4
1
4
76
85
7
78
10
73
2
18
9
13
1
2
1
4
2,145
ARMmbed/icetea
ARMmbed_icetea/test/tests/matching_test/component1and2_test.py
test.tests.matching_test.component1and2_test.Testcase
class Testcase(Bench): def __init__(self): Bench.__init__(self, name="ut_2component_test", title="unittest matching", status="development", type="acceptance", purpose="dummy", component=["icetea_ut", "component1", "component2"], requirements={ "duts": { '*': { "count": 0 } } } ) def case(self): raise TestStepFail("This is a failing test case")
class Testcase(Bench): def __init__(self): pass def case(self): pass
3
0
9
0
9
0
1
0
1
1
1
0
2
0
2
108
20
1
19
3
16
0
5
3
2
1
3
0
2
2,146
ARMmbed/icetea
ARMmbed_icetea/test/test_run_retcodes_suc.py
test.test_run_retcodes_suc.Testcase
class Testcase(Bench): """ Test case that should pass. """ def __init__(self): Bench.__init__(self, name="test_run_retcodes_success", title="unittest dut crash in testcase", status="development", type="acceptance", purpose="dummy", component=["Icetea_ut"], requirements={ "duts": { '*': { "count": 0, "allowed_platforms": ["TEST_PLAT"] } }} ) def case(self): # pylint: disable=missing-docstring pass
class Testcase(Bench): ''' Test case that should pass. ''' def __init__(self): pass def case(self): pass
3
1
9
0
9
1
1
0.21
1
0
0
0
2
0
2
108
23
1
19
3
16
4
5
3
2
1
3
0
2
2,147
ARMmbed/icetea
ARMmbed_icetea/test/tests/matching_test/component1_test.py
test.tests.matching_test.component1_test.Testcase
class Testcase(Bench): def __init__(self): Bench.__init__(self, name="ut_component1_test", title="unittest matching", status="development", type="acceptance", purpose="dummy", component=["icetea_ut", "component1"], requirements={ "duts": { '*': { "count": 0 } } } ) def case(self): pass
class Testcase(Bench): def __init__(self): pass def case(self): pass
3
0
9
0
9
0
1
0
1
0
0
0
2
0
2
108
20
1
19
3
16
0
5
3
2
1
3
0
2
2,148
ARMmbed/icetea
ARMmbed_icetea/test/tests/json_output_test/json_output_test_case.py
test.tests.json_output_test.json_output_test_case.Testcase
class Testcase(Bench): """ Test case for verifying json output feature. """ def __init__(self): Bench.__init__(self, name="json_output_test", title="Test list output as json", status="development", type="acceptance", purpose="dummy", component=["Icetea_ut"], requirements={ } ) def setup(self): pass def case(self): pass def teardown(self): pass
class Testcase(Bench): ''' Test case for verifying json output feature. ''' def __init__(self): pass def setup(self): pass def case(self): pass def teardown(self): pass
5
1
4
0
4
0
1
0.17
1
0
0
0
4
0
4
110
24
3
18
5
13
3
9
5
4
1
3
0
4
2,149
ARMmbed/icetea
ARMmbed_icetea/test/tests/failing_testcase.py
test.tests.failing_testcase.Testcase
class Testcase(Bench): """ Test case for testing failing a test case. """ def __init__(self): Bench.__init__(self, name="ut_failing_tc", title="unittest failure in testcase", status="development", type="acceptance", purpose="dummy", component=["Icetea_ut"], requirements={ "duts": { '*': { "count": 0 } } } ) def case(self): # pylint: disable=missing-docstring,no-self-use raise TestStepFail("This is a failing test case")
class Testcase(Bench): ''' Test case for testing failing a test case. ''' def __init__(self): pass def case(self): pass
3
1
9
0
9
1
1
0.21
1
1
1
0
2
0
2
108
23
1
19
3
16
4
5
3
2
1
3
0
2
2,150
ARMmbed/icetea
ARMmbed_icetea/test/tests/failing_command.py
test.tests.failing_command.Testcase
class Testcase(Bench): """ Test case for testing failing command return codes. """ def __init__(self): Bench.__init__(self, name="ut_dut_failing_command", title="unittest dut crash in testcase", status="development", type="acceptance", purpose="dummy", component=["Icetea_ut"], requirements={ "duts": { '*': { "count": 1, "type": "process", "application": { "bin": "test/dut/dummyDut" }, } } } ) def case(self): # pylint: disable=missing-docstring # Failing command with retcode try: self.command(1, "retcode -1") except TestStepFail: pass self.command(1, "retcode 0") # Failing command with timeout try: self.command(1, "sleep 5", timeout=4) except TestStepTimeout: print("TIMEOUT")
class Testcase(Bench): ''' Test case for testing failing command return codes. ''' def __init__(self): pass def case(self): pass
3
1
17
1
15
2
2
0.19
1
2
2
0
2
0
2
108
38
2
31
3
28
6
13
3
10
3
3
1
4
2,151
ARMmbed/icetea
ARMmbed_icetea/test/tests/matching_test/feature1_test.py
test.tests.matching_test.feature1_test.Testcase
class Testcase(Bench): def __init__(self): Bench.__init__(self, name="ut_feature1_test", title="unittest matching", status="development", type="acceptance", purpose="dummy", component=["icetea_ut"], feature=["feature1"], requirements={ "duts": { '*': { "count": 0 } } } ) def case(self): pass
class Testcase(Bench): def __init__(self): pass def case(self): pass
3
0
10
0
10
0
1
0
1
0
0
0
2
0
2
108
21
1
20
3
17
0
5
3
2
1
3
0
2
2,152
ARMmbed/icetea
ARMmbed_icetea/test/testbase/lv1/lv2/level2.py
test.testbase.lv1.lv2.level2.Testcase
class Testcase(Bench): def __init__(self): Bench.__init__(self, name="subsubdirtest", title="Level 2 testcase test file", status="maintenance", purpose="dummy", component=["None"], type="smoke", requirements={ "duts": { '*': { "count": 0 } } } ) def case(self): pass
class Testcase(Bench): def __init__(self): pass def case(self): pass
3
0
9
0
9
0
1
0
1
0
0
0
2
0
2
108
21
2
19
3
16
0
5
3
2
1
3
0
2
2,153
ARMmbed/icetea
ARMmbed_icetea/test/testbase/lv1/level1.py
test.testbase.lv1.level1.Testcase
class Testcase(Bench): def __init__(self): Bench.__init__(self, name="subdirtest", title="Level 1 testcase test file", status="development", purpose="dummy", component=["None"], type="compatibility", requirements={ "duts": { '*': { "count": 0 } } }, execution={ "skip": { "value": True, "reason": "Because" } } ) def case(self): pass
class Testcase(Bench): def __init__(self): pass def case(self): pass
3
0
12
0
12
0
1
0
1
0
0
0
2
0
2
108
27
2
25
3
22
0
5
3
2
1
3
0
2
2,154
ARMmbed/icetea
ARMmbed_icetea/test/testbase/level0.py
test.testbase.level0.Testcase
class Testcase(Bench): """ Test case search test case. """ def __init__(self): Bench.__init__(self, name="rootdirtest", title="Level 0 testcase test file", status="released", purpose="dummy", component=["None"], type="installation", requirements={ "duts": { '*': { "count": 0 } } } ) def case(self): pass
class Testcase(Bench): ''' Test case search test case. ''' def __init__(self): pass def case(self): pass
3
1
9
0
9
0
1
0.16
1
0
0
0
2
0
2
108
23
1
19
3
16
3
5
3
2
1
3
0
2
2,155
ARMmbed/icetea
ARMmbed_icetea/test/testbase/lv1/lv2/lv3/level3.py
test.testbase.lv1.lv2.lv3.level3.Testcase
class Testcase(Bench): def __init__(self): Bench.__init__(self, name="subsubsubdirtest", title="Level 3 testcase test file", status="broken", purpose="dummy", component=["None"], type="regression", requirements={ "duts": { '*': { "count": 0 } } } ) def case(self): pass
class Testcase(Bench): def __init__(self): pass def case(self): pass
3
0
9
0
9
0
1
0
1
0
0
0
2
0
2
108
21
2
19
3
16
0
5
3
2
1
3
0
2
2,156
ARMmbed/icetea
ARMmbed_icetea/test/testbase/dummy_multiples.py
test.testbase.dummy_multiples.TestcaseBase
class TestcaseBase(Bench): def __init__(self, test_name): Bench.__init__(self, name=test_name, title="dummy", status="unknown", type="functional", purpose="dummy", requirements={ "duts": { '*': { "count": 0 } } } ) def case(self): pass
class TestcaseBase(Bench): def __init__(self, test_name): pass def case(self): pass
3
0
9
0
9
0
1
0
1
0
0
2
2
0
2
108
20
2
18
3
15
0
5
3
2
1
3
0
2
2,157
ARMmbed/icetea
ARMmbed_icetea/test/testbase/dummy_multiples.py
test.testbase.dummy_multiples.SecondTest
class SecondTest(TestcaseBase): IS_TEST = True def __init__(self): TestcaseBase.__init__(self, "second_dummy_test")
class SecondTest(TestcaseBase): def __init__(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
109
5
1
4
3
2
0
4
3
2
1
4
0
1
2,158
ARMmbed/icetea
ARMmbed_icetea/test/testbase/dummy_multiples.py
test.testbase.dummy_multiples.FirstTest
class FirstTest(TestcaseBase): IS_TEST = True def __init__(self): TestcaseBase.__init__(self, "first_dummy_test")
class FirstTest(TestcaseBase): def __init__(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
109
5
1
4
3
2
0
4
3
2
1
4
0
1
2,159
ARMmbed/icetea
ARMmbed_icetea/test/testbase/dummy.py
test.testbase.dummy.Testcase
class Testcase(Bench): def __init__(self): Bench.__init__(self, name="dummy", title="dummy", status="unknown", type="functional", purpose="dummy", requirements={ "duts": { '*': { "count": 0 } } } ) def case(self): if "--fail" in self.unknown: raise TestStepError(str(self.unknown))
class Testcase(Bench): def __init__(self): pass def case(self): pass
3
0
9
0
9
0
2
0
1
2
1
0
2
0
2
108
20
1
19
3
16
0
6
3
3
2
3
1
3
2,160
ARMmbed/icetea
ARMmbed_icetea/test/test_tools.py
test.test_tools.TestTools
class TestTools(unittest.TestCase): def test_load_class_success(self): sys.path.append(os.path.dirname(__file__)) # Test that loadClass can import a class that is initializable module = tools.load_class("test_tools.TestClass", verbose=False, silent=True) self.assertIsNotNone(module) module_instance = module() self.assertTrue(module_instance.test) del module_instance def test_load_class_fail(self): with self.assertRaises(Exception): tools.load_class('testbase.level1.Testcase', verbose=False, silent=True) self.assertIsNone(tools.load_class('', verbose=False, silent=True)) self.assertIsNone(tools.load_class(5, verbose=False, silent=True)) self.assertIsNone(tools.load_class([], verbose=False, silent=True)) self.assertIsNone(tools.load_class({}, verbose=False, silent=True)) def test_combine_urls(self): self.assertEquals(tools.combine_urls("/path/one/", "path2"), "/path/one/path2") self.assertEquals(tools.combine_urls("/path/one", "path2"), "/path/one/path2") self.assertEquals(tools.combine_urls("/path/one/", "/path2"), "/path/one/path2") self.assertEquals(tools.combine_urls("/path/one", "/path2"), "/path/one/path2") def test_hex_escape_tester(self): failing_message = "\x00\x00\x00\x00\x00\x00\x01\xc8" success_message = "\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xc8" converted = tools.hex_escape_str(failing_message) self.assertEqual(converted, success_message) def test_get_fw_version(self): version = None try: setup_path = os.path.abspath(os.path.dirname(__file__)+'/..') with open(os.path.join(setup_path, 'setup.py')) as setup_file: lines = setup_file.readlines() for line in lines: match = re.search(r"VERSION = \"([\S]{5,})\"", line) if match: version = match.group(1) break except Exception: # pylint: disable=broad-except pass got_version = tools.get_fw_version() self.assertEqual(got_version, version) with mock.patch("icetea_lib.tools.tools.require") as mocked_require: mocked_require.side_effect = [DistributionNotFound] got_version = tools.get_fw_version() self.assertEqual(got_version, version) def test_check_int(self): integer = "10" prefixedinteger = "-10" decimal = "10.1" self.assertTrue(tools.check_int(integer)) self.assertTrue(tools.check_int(prefixedinteger)) self.assertFalse(tools.check_int(decimal)) self.assertFalse(tools.check_int(1)) def test_remove_empty_from_dict(self): dictionary = {"test": "val", "test2": None} dictionary = tools.remove_empty_from_dict(dictionary) self.assertDictEqual({"test": "val"}, dictionary) def test_setordelete(self): dictionary = {"test": "val", "test2": "val2"} tools.set_or_delete(dictionary, "test", "val3") self.assertEqual(dictionary.get("test"), "val3") tools.set_or_delete(dictionary, "test2", None) self.assertTrue("test2" not in dictionary) def test_getargspec(self): expected_args = ["arg1", "arg2"] spec = tools.getargspec(testingfunction) for item in expected_args: self.assertTrue(item in spec.args) def test_strip_escape(self): test_data_no_escapes = "aaaa" self.assertEqual(tools.strip_escape(test_data_no_escapes), "aaaa") test_data_encoded = "aaaa".encode("utf-8") self.assertEqual(tools.strip_escape(test_data_encoded), "aaaa") mock_str = mock.MagicMock() mock_str.decode = mock.MagicMock(side_effect=[UnicodeDecodeError]) with self.assertRaises(TypeError): tools.strip_escape(mock_str) def test_json_duplicate_keys(self): dict1 = '{"x": "1", "y": "1", "x": "2"}' with self.assertRaises(ValueError): json.loads(dict1, object_pairs_hook=tools.find_duplicate_keys) dict2 = '{"x": "1", "y": {"x": "2"}}' expected = {"y": {"x": "2"}, "x": "1"} self.assertDictEqual(json.loads(dict2, object_pairs_hook=tools.find_duplicate_keys), expected) def test_create_combined_set(self): test_phrase = "filter3 and (filter1 or filter2)" test_list = test_phrase.split(" ") combined, _ = tools._create_combined_set(test_list, 2) self.assertEqual(combined, "(filter1 or filter2)") test_phrase = "(filter3 and (filter1 or filter2))" test_list = test_phrase.split(" ") combined, _ = tools._create_combined_set(test_list, 0) self.assertEqual(combined, "(filter3 and (filter1 or filter2))") test_phrase = "filter3 and (filter1 or filter2" test_list = test_phrase.split(" ") combined, _ = tools._create_combined_set(test_list, 2) self.assertIsNone(combined) def test_create_combined_words(self): test_phrase = "filter3 and 'filter1 with filter2'" test_list = test_phrase.split(" ") combined, _ = tools._create_combined_words(test_list, 2) self.assertEqual(combined, "'filter1 with filter2'") def test_create_match_bool(self): test_data = list() test_data.append("filter1") test_data.append("filter1,filter2") test_data.append("filter1 or filter2") test_data.append("(filter1 or filter2)") test_data.append("filter1 and filter2") test_data.append("filter3 and (filter1 or filter2)") test_data.append("filter1 and 'filter2 with filter3'") test_data.append("filter1 and ('filter2 with filter3' or filter1)") test_data.append("(filter1 or filter2 and (((not (filter3)) " "and not filter4) and not filter5))") def eval_func(str_to_match, args): # pylint: disable=unused-argument if str_to_match == "filter1": return True elif str_to_match == "filter2": return False elif str_to_match == "filter3": return True elif str_to_match == "filter4": return True elif str_to_match == "filter5": return False elif str_to_match == "filter2 with filter3": return True # Check that no exceptions are raised for test_string in test_data: tools.create_match_bool(test_string, eval_func, None) self.assertTrue(tools.create_match_bool(test_data[0], eval_func, None)) self.assertTrue(tools.create_match_bool(test_data[1], eval_func, None)) self.assertTrue(tools.create_match_bool(test_data[2], eval_func, None)) self.assertTrue(tools.create_match_bool(test_data[3], eval_func, None)) self.assertFalse(tools.create_match_bool(test_data[4], eval_func, None)) self.assertTrue(tools.create_match_bool(test_data[5], eval_func, None)) self.assertTrue(tools.create_match_bool(test_data[6], eval_func, None)) self.assertTrue(tools.create_match_bool(test_data[7], eval_func, None)) self.assertTrue(tools.create_match_bool(test_data[8], eval_func, None)) test_data.append("filter3 and (filter1 or filter2") with self.assertRaises(SyntaxError): tools.create_match_bool(test_data[9], eval_func, None)
class TestTools(unittest.TestCase): def test_load_class_success(self): pass def test_load_class_fail(self): pass def test_combine_urls(self): pass def test_hex_escape_tester(self): pass def test_get_fw_version(self): pass def test_check_int(self): pass def test_remove_empty_from_dict(self): pass def test_setordelete(self): pass def test_getargspec(self): pass def test_strip_escape(self): pass def test_json_duplicate_keys(self): pass def test_create_combined_set(self): pass def test_create_combined_words(self): pass def test_create_match_bool(self): pass def eval_func(str_to_match, args): pass
16
0
11
1
10
0
2
0.03
1
7
0
0
14
0
14
86
167
23
142
51
126
4
134
49
118
7
2
4
26
2,161
ARMmbed/icetea
ARMmbed_icetea/test/test_tools.py
test.test_tools.TestClass
class TestClass(object): def __init__(self): self.test = True
class TestClass(object): def __init__(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
1
1
1
3
0
3
3
1
0
3
3
1
1
1
0
1
2,162
ARMmbed/icetea
ARMmbed_icetea/test/test_testcasefilter.py
test.test_testcasefilter.TCFilterTestcase
class TCFilterTestcase(unittest.TestCase): def setUp(self): self.schemapath = os.path.abspath(os.path.join(__file__, os.path.pardir, os.path.pardir, "icetea_lib")) def test_create_filter_simple(self): filt = TestcaseFilter().tc("test_cmdline") self.assertDictEqual(filt._filter, {'status': False, 'group': False, 'name': 'test_cmdline', 'comp': False, 'platform': False, 'list': False, 'subtype': False, 'type': False, 'feature': False}) with self.assertRaises(TypeError): TestcaseFilter().tc(0) with self.assertRaises(IndexError): TestcaseFilter().tc([]) with self.assertRaises(TypeError): TestcaseFilter().tc(None) with self.assertRaises(TypeError): TestcaseFilter().tc(True) self.assertDictEqual(TestcaseFilter().tc(1)._filter, {'status': False, 'group': False, 'name': False, 'comp': False, 'platform': False, 'list': [0], 'subtype': False, 'type': False, 'feature': False}) self.assertDictEqual(TestcaseFilter().tc([1, 4])._filter, {'status': False, 'group': False, 'name': False, 'comp': False, 'platform': False, 'list': [0, 3], 'subtype': False, 'type': False, 'feature': False}) def test_create_filter_complex(self): filt = TestcaseFilter() filt.tc("test_test") filt.component("test_comp") filt.group("test_group") filt.status("test_status") filt.testtype("test_type") filt.subtype("test_subtype") filt.feature("test_feature") filt.platform("test_platform") self.assertDictEqual(filt._filter, {"status": "test_status", "group": "test_group", "name": "test_test", "type": "test_type", "subtype": "test_subtype", "comp": "test_comp", 'list': False, 'feature': "test_feature", "platform": "test_platform"}) with self.assertRaises(TypeError): filt.component(2) def test_create_filter_list(self): filt = TestcaseFilter() filt.tc("test_test,test_test2") self.assertDictEqual(filt._filter, {"status": False, "group": False, "name": False, "type": False, "subtype": False, "comp": False, 'list': ["test_test", "test_test2"], 'feature': False, "platform": False}) def test_match(self): testcase = TestcaseContainer.find_testcases( "examples.test_cmdline", "." + os.path.sep + "examples", TCMetaSchema().get_meta_schema()) filt = TestcaseFilter().tc("test_cmdline") self.assertTrue(filt.match(testcase[0], 0)) filt.component("cmdline,testcomponent") filt.group("examples") self.assertTrue(filt.match(testcase[0], 0)) filt.tc("test_something_else") self.assertFalse(filt.match(testcase[0], 0)) filt = TestcaseFilter().tc([1]) self.assertTrue(filt.match(testcase[0], 0)) self.assertFalse(filt.match(testcase[0], 1)) def test_match_complex(self): filt = TestcaseFilter().feature("feature1 or feature2") testcase = TestcaseContainer.find_testcases("test.tests.matching_test.feature2_test", "." + os.path.sep + "test" + os.path.sep + "tests" + os.path.sep + "matching_test", TCMetaSchema(self.schemapath).get_meta_schema()) self.assertTrue(filt.match(testcase[0], 0)) testcase = TestcaseContainer.find_testcases("test.tests.matching_test.feature1_test", "." + os.path.sep + "test" + os.path.sep + "tests" + os.path.sep + "matching_test", TCMetaSchema(self.schemapath).get_meta_schema()) self.assertTrue(filt.match(testcase[0], 0)) testcase = TestcaseContainer.find_testcases( "test.tests.matching_test.feature_and_component_test", "." + os.path.sep + "test" + os.path.sep + "tests" + os.path.sep + "matching_test", TCMetaSchema().get_meta_schema()) filt = filt.component("component2") self.assertTrue(filt.match(testcase[0], 0)) filt = filt.component("component1") self.assertFalse(filt.match(testcase[0], 0)) filt = TestcaseFilter().feature("not feature2") testcase = TestcaseContainer.find_testcases("test.tests.matching_test.feature2_test", "." + os.path.sep + "test" + os.path.sep + "tests" + os.path.sep + "matching_test", TCMetaSchema(self.schemapath).get_meta_schema()) self.assertFalse(filt.match(testcase[0], 0)) filt = TestcaseFilter().component("component1") testcase = TestcaseContainer.find_testcases("test.tests.matching_test.component1_test", "." + os.path.sep + "test" + os.path.sep + "tests" + os.path.sep + "matching_test", TCMetaSchema(self.schemapath).get_meta_schema()) self.assertTrue(filt.match(testcase[0], 0)) testcase = TestcaseContainer.find_testcases("test.tests.matching_test.component1and2_test", "." + os.path.sep + "test" + os.path.sep + "tests" + os.path.sep + "matching_test", TCMetaSchema(self.schemapath).get_meta_schema()) self.assertTrue(filt.match(testcase[0], 0)) def test_match_platform(self): meta = {"allowed_platforms": ["PLAT1", "PLAT2"]} filters = {"platform": "PLAT1"} string_to_match = "PLAT1" result = TestcaseFilter._match_platform(string_to_match, (meta, filters)) self.assertTrue(result) string_to_match = "PLAT3" result = TestcaseFilter._match_platform(string_to_match, (meta, filters)) self.assertFalse(result)
class TCFilterTestcase(unittest.TestCase): def setUp(self): pass def test_create_filter_simple(self): pass def test_create_filter_complex(self): pass def test_create_filter_list(self): pass def test_match(self): pass def test_match_complex(self): pass def test_match_platform(self): pass
8
0
19
1
18
0
1
0
1
5
3
0
7
1
7
79
142
14
128
20
120
0
73
20
65
1
2
1
7
2,163
ARMmbed/icetea
ARMmbed_icetea/test/test_testcasecontainer.py
test.test_testcasecontainer.MockInstance
class MockInstance(object): def __init__(self, name, version, type=None, skip_val=True, skip_info=None): self.info = skip_info if skip_info else {"only_type": "process"} self.config = { "compatible": { "framework": { "name": name, "version": version} }, "requirements": { "duts": { "*": { "type": type } } } } self.skip_val = skip_val def get_result(self): return Result() def get_test_name(self): return "Icetea" def skip(self): return self.skip_val def skip_info(self): return self.info def skip_reason(self): return "test"
class MockInstance(object): def __init__(self, name, version, type=None, skip_val=True, skip_info=None): pass def get_result(self): pass def get_test_name(self): pass def skip(self): pass def skip_info(self): pass def skip_reason(self): pass
7
0
4
0
4
0
1
0
1
1
1
0
6
3
6
6
32
5
27
10
20
0
15
10
8
2
1
0
7
2,164
ARMmbed/icetea
ARMmbed_icetea/test/test_searcher.py
test.test_searcher.TestVerify
class TestVerify(unittest.TestCase): def test_default(self): lines = [ 'aapeli', 'beeveli', 'oopeli', 'huhheli', 'strange bird'] self.assertTrue(verify_message(lines, ['oopeli', 'huhheli'])) self.assertFalse(verify_message(lines, ['oopeli', 'huhhelis'])) self.assertFalse(verify_message(lines, ['oopeli', 'huhhe li'])) self.assertFalse(verify_message(lines, [False])) self.assertTrue(verify_message(lines, ['strange bird'])) def test_invert(self): lines = [ 'aapeli', 'beeveli', 'oopeli', 'huhheli'] self.assertTrue(verify_message(lines, ['oopeli', Invert('uups')])) self.assertFalse(verify_message(lines, ['oopeli', Invert('huhheli')])) self.assertFalse(verify_message(lines, ['oopeli', Invert('huhheli')])) def test_regex(self): lines = [ 'aapeli', 'beeveli', 'oopeli', 'huhheli'] self.assertTrue(verify_message(lines, ['^aa', '^be', '^oopeli'])) self.assertFalse(verify_message(lines, ['^aa', '^opeli'])) def test_string(self): lines = [ 'aapeli', 'beeveli', 'oopeli', 'huhheli'] self.assertTrue(verify_message(lines, "aapeli")) self.assertTrue(verify_message(lines, "oop")) self.assertFalse(verify_message(lines, "ai")) def test_set(self): lines = [ 'aapeli', 'beeveli', 'oopeli', 'huhheli'] self.assertTrue(verify_message(lines, {"aapeli"})) self.assertTrue(verify_message(lines, {"oop"})) self.assertFalse(verify_message(lines, {"ai"})) self.assertFalse(verify_message(lines, {1})) def test_false_type(self): with self.assertRaises(TypeError): verify_message([], 1)
class TestVerify(unittest.TestCase): def test_default(self): pass def test_invert(self): pass def test_regex(self): pass def test_string(self): pass def test_set(self): pass def test_false_type(self): pass
7
0
9
0
9
0
1
0
1
2
1
0
6
0
6
78
57
5
52
12
45
0
31
12
24
1
2
1
6
2,165
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/tests/unit/test_tlv_decode.py
tests.unit.test_tlv_decode.TestDecode
class TestDecode(BaseCase): def test_nullstring(self): self.assertEqual( binary_tlv_to_python(''.encode()), {} ) def test_get_id_length_1(self): self.assertEqual(get_id_length(0b11011111), 1) def test_get_id_length_2(self): self.assertEqual(get_id_length(0b11111111), 2) def test_get_value_length_1(self): self.assertEqual(get_value_length(0b11101111), 1) def test_get_value_length_2(self): self.assertEqual(get_value_length(0b11110111), 2) def test_get_value_length_3(self): self.assertEqual(get_value_length(0b11111111), 3) def test_get_value_length_custom(self): # for example: # both bits for the relevant mask are zero, which means it defers # to the remaining bits (instead of the hardcoded values) # the remainder are the least significant bits - here, 110 self.assertEqual(get_value_length(0b11100110), 6) def test_combine_bytes_two(self): b1 = 0b00000001 # 1 b2 = 0b00000101 # 5 b3 = b1 + b2 # 261 instead of 6 self.assertEqual(b3, 6) self.assertEqual( combine_bytes((b1, b2)), 261 ) def test_combine_bytes_three(self): b1 = 0b00000001 # 1 b2 = 0b00000101 # 5 b3 = 0b00011111 # 31 b4 = b1 + b2 + b3 # 66847 instead of 37 self.assertEqual(b4, 37) self.assertEqual( combine_bytes((b1, b2, b3)), 66847 )
class TestDecode(BaseCase): def test_nullstring(self): pass def test_get_id_length_1(self): pass def test_get_id_length_2(self): pass def test_get_value_length_1(self): pass def test_get_value_length_2(self): pass def test_get_value_length_3(self): pass def test_get_value_length_custom(self): pass def test_combine_bytes_two(self): pass def test_combine_bytes_three(self): pass
10
0
4
0
4
1
1
0.3
1
0
0
0
9
0
9
81
49
8
37
17
27
11
28
17
18
1
3
0
9
2,166
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/tests/unit/test_tlv_b64_examples.py
tests.unit.test_tlv_b64_examples.TestValueZero
class TestValueZero(B64.TestCase): b64 = "iAsLSAAIAAAAAAAAAAA=" result = {'11': {'0': 0}}
class TestValueZero(B64.TestCase): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
74
3
0
3
3
2
0
3
3
2
0
4
0
0
2,167
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/tests/unit/test_tlv_b64_examples.py
tests.unit.test_tlv_b64_examples.TestValueBlank
class TestValueBlank(B64.TestCase): b64 = "VQ==" result = {'0': ''}
class TestValueBlank(B64.TestCase): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
74
3
0
3
3
2
0
3
3
2
0
4
0
0
2,168
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/tests/unit/test_tlv_b64_examples.py
tests.unit.test_tlv_b64_examples.TestResource
class TestResource(B64.TestCase): """ a random device from the integration lab """ b64 = "CAALyAEIAAAAAAAAACI=" result = {'0': 241790033863361294262861858}
class TestResource(B64.TestCase): ''' a random device from the integration lab ''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
74
6
0
3
3
2
3
3
3
2
0
4
0
0
2,169
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/tests/unit/test_tlv_b64_examples.py
tests.unit.test_tlv_b64_examples.B64
class B64(object): # hides the inheritance from unittest class TestCase(BaseCase): b64 = None # an ascii string containing b64 encoded data result = None # the python-native data we expect to decode decoded = None # we'll store the result here in the test def test_run(self): self.decoded = maybe_decode_payload(self.b64) self.assertion() def assertion(self): self.assertEqual(self.decoded, self.result)
class B64(object): class TestCase(BaseCase): def test_run(self): pass def assertion(self): pass
4
0
3
0
3
0
1
0.4
1
0
0
0
0
0
0
0
14
3
10
7
6
4
10
7
6
1
1
0
2
2,170
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/tests/unit/test_tlv_b64_examples.py
tests.unit.test_tlv_b64_examples.TestDevice
class TestDevice(B64.TestCase): """ a random device from the integration lab """ b64 = ( "iAsLSAAIAAAAAAAAAADBEFXIABAAAAAAAAAAAAAAAAAAAAAA" "yAEQAAAAAAAAAAAAAAAAAAAAAMECMMgRD2Rldl9kZXZpY2VfdHlwZcg" "SFGRldl9oYXJkd2FyZV92ZXJzaW9uyBUIAAAAAAAAAADIDQgAAAAAWdH0Bw==" ) result = { '0': 0, '1': 0, '11': {'0': 0}, '13': 1506931719, '16': 'U', '17': 'dev_device_type', '18': 'dev_hardware_version', '2': '0', '21': 0 }
class TestDevice(B64.TestCase): ''' a random device from the integration lab ''' pass
1
1
0
0
0
0
0
0.18
1
0
0
0
0
0
0
74
20
0
17
3
16
3
3
3
2
0
4
0
0
2,171
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/tests/unit/test_pagination.py
tests.unit.test_pagination.TestNoCache
class TestNoCache(Test): paginator = partial(PaginatedResponse, _results_cache=False) def test_is_not_caching(self): p = self.paginator(ListResponse) self.assertFalse(p._is_caching) all(p) self.assertIsNone(p._results_cache) def test_all(self): p = self.paginator(ListResponse) next(p) self.assert_list_compat(p.all(), [D(1), D(2), D(3), D(4)])
class TestNoCache(Test): def test_is_not_caching(self): pass def test_all(self): pass
3
0
5
0
5
0
1
0
1
2
2
0
2
0
2
95
13
2
11
6
8
0
11
6
8
1
4
0
2
2,172
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/tests/unit/test_pagination.py
tests.unit.test_pagination.TestStubber
class TestStubber(BaseCase, ListCompatMixin): def test_stubber_basics(self): self.assertEqual(D(0), D(0)) self.assertNotEqual(D(0), D(1)) def test_stubber_at_zero(self): R = ListResponse(stubber_total=4) self.assertTrue(R.has_more) self.assert_list_compat(R.data, [D(0), D(1), D(2), D(3)]) def test_stubber_limit(self): # aka page size R = ListResponse(stubber_total=12, after=3, limit=3) self.assert_list_compat(R.data, [D(4), D(5), D(6)]) def test_stubber_after(self): R = ListResponse(after=2) self.assertEqual(R.data[0], D(3)) self.assertEqual(R.data[1], D(4)) self.assertEqual(len(R.data), 2) def test_stubber_has_more(self): R = ListResponse(stubber_total=3, limit=2) self.assertTrue(R.has_more, '[0, 1] 2 -> more') self.assert_list_compat(R.data, [D(0), D(1)]) R = ListResponse(stubber_total=4, limit=2, after=0) self.assertTrue(R.has_more, '0, [1, 2], 3 -> more') self.assert_list_compat(R.data, [D(1), D(2)]) R = ListResponse(stubber_total=3, limit=2, after=0) self.assertFalse(R.has_more, '0, [1, 2] -> no more') self.assert_list_compat(R.data, [D(1), D(2)]) R = ListResponse(stubber_total=3, limit=2, after=1) self.assertFalse(R.has_more, '0, 1, [2] -> no more') self.assert_list_compat(R.data, [D(2)]) R = ListResponse(stubber_total=3, limit=3) self.assertFalse(R.has_more, '[0, 1, 2] -> no more') self.assert_list_compat(R.data, [D(0), D(1), D(2)])
class TestStubber(BaseCase, ListCompatMixin): def test_stubber_basics(self): pass def test_stubber_at_zero(self): pass def test_stubber_limit(self): pass def test_stubber_after(self): pass def test_stubber_has_more(self): pass
6
0
7
1
6
0
1
0.03
2
2
2
0
5
0
5
78
41
8
32
10
26
1
32
10
26
1
3
0
5
2,173
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/tests/unit/test_sort_params.py
tests.unit.test_sort_params.TestSortParams
class TestSortParams(BaseCase): @classmethod def setUpClass(cls): cls.api = BaseAPI() def _run(self, expected, **kwargs): outcome = self.api._verify_sort_options(kwargs) self.assertEqual(outcome, expected) def test_simple_invalid_str(self): with self.assertRaises(ValueError): self._run(None, order='banana') @unittest.expectedFailure def test_simple_invalid_int(self): with self.assertRaises(ValueError): self._run(None, order=1337) def test_simple_valid_asc(self): self._run({'order': 'ASC'}, order='ASC') def test_simple_valid_desc(self): self._run({'order': 'DESC'}, order='desc') def test_limit_low(self): with self.assertRaises(ValueError): self._run(None, limit=1) def test_limit_high(self): with self.assertRaises(ValueError): self._run(None, limit=1e12) def test_limit_just_right(self): self._run({'limit': 500}, limit=500) def test_limit_and_sort(self): self._run({'limit': 3, 'order': 'ASC', 'irrelevant': 'banana'}, limit=3, order='asc', irrelevant='banana')
class TestSortParams(BaseCase): @classmethod def setUpClass(cls): pass def _run(self, expected, **kwargs): pass def test_simple_invalid_str(self): pass @unittest.expectedFailure def test_simple_invalid_int(self): pass def test_simple_valid_asc(self): pass def test_simple_valid_desc(self): pass def test_limit_low(self): pass def test_limit_high(self): pass def test_limit_just_right(self): pass def test_limit_and_sort(self): pass
13
0
3
0
3
0
1
0
1
2
1
0
9
0
10
82
38
10
28
14
15
0
26
12
15
1
3
1
10
2,174
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/tests/unit/test_tlv_b64_examples.py
tests.unit.test_tlv_b64_examples.TestFirmware
class TestFirmware(B64.TestCase): """ a random device from the integration lab """ b64 = "CAAeyAMIAAAAAAAAAADIBQj//////////8IGLTHCBy0x" result = {'0': 1380430991696447557863828761305475282422786975014656077075657751739706673}
class TestFirmware(B64.TestCase): ''' a random device from the integration lab ''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
74
6
0
3
3
2
3
3
3
2
0
4
0
0
2,175
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/tests/unit/test_webhook_handler.py
tests.unit.test_webhook_handler.Test
class Test(BaseCase): @classmethod def setUpClass(cls): cls.api = ConnectAPI() def test_async_response(self): asyncid = 'w349yw4ti7y34ti7eghiey54t' # make a fake listener result = AsyncConsumer(asyncid, self.api._db) self.assertFalse(result.is_done) # fake a response coming from a webhook receiver json_payload = json.dumps({ 'async-responses': [{ 'id': asyncid, 'status': 1, 'ct': 'tlv', 'payload': "Q2hhbmdlIG1lIQ==" }] }) self.api.notify_webhook_received(payload=json_payload) self.assertTrue(result.is_done) self.assertEqual(result.value, {'104': 'ang', '8301': 'e!'}) self.assertEqual(result.async_id, asyncid) def test_subscription_response(self): """Checks the behaviour of notification system when used with subscriptions They're different to get_resource_value, and use callbacks for some reason We patch the API call as we don't care about actually making a request Our callback is serviced by the random thread made in `add_resource_subscription_async` So we have to wait a bit for that to occur """ path = '3200/0/5500' device_id = '015bb66a92a30000000000010010006d' mutable = [] def some_callback(device_id, path, value, status=mutable): mutable.extend((device_id, path, value)) with mock.patch('mbed_cloud._backends.mds.SubscriptionsApi.add_resource_subscription'): self.api.add_resource_subscription_async( device_id=device_id, resource_path=path, callback_fn=some_callback ) json_payload = json.dumps({ 'notifications': [{ 'ep': device_id, 'path': path, 'ct': 'tlv', 'payload': "Q2hhbmdlIG1lIQ==" }] }) self.api.notify_webhook_received(payload=json_payload) timeout_seconds = 0.5 delay = 0.02 for i in range(int(timeout_seconds/delay)): if mutable: break time.sleep(delay) else: raise Exception('didnt see subscription after %s seconds' % timeout_seconds) self.assertEqual(mutable, [device_id, path, {'8301': 'e!', '104': 'ang'}])
class Test(BaseCase): @classmethod def setUpClass(cls): pass def test_async_response(self): pass def test_subscription_response(self): '''Checks the behaviour of notification system when used with subscriptions They're different to get_resource_value, and use callbacks for some reason We patch the API call as we don't care about actually making a request Our callback is serviced by the random thread made in `add_resource_subscription_async` So we have to wait a bit for that to occur ''' pass def some_callback(device_id, path, value, status=mutable): pass
6
1
17
3
13
2
2
0.16
1
5
2
0
2
0
3
75
70
12
50
16
44
8
31
15
26
3
3
2
6
2,176
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/src/mbed_cloud/foundation/entities/branding/enums.py
mbed_cloud.foundation.entities.branding.enums.SubtenantDarkThemeImageReferenceEnum
class SubtenantDarkThemeImageReferenceEnum(BaseEnum): """Represents expected values of `SubtenantDarkThemeImageReferenceEnum` This is used by Entities in the "branding" category. .. note:: If new values are added to the enum in the API they will be passed through unchanged by the SDK, but will not be on this list. If this occurs please update the SDK to the most recent version. """ BRAND_LOGO_EMAIL = "brand_logo_email" BRAND_LOGO_LANDSCAPE = "brand_logo_landscape" BRAND_LOGO_PORTRAIT = "brand_logo_portrait" BRAND_LOGO_SQUARE = "brand_logo_square" CAROUSEL_IMAGE_LANDSCAPE_0 = "carousel_image_landscape_0" CAROUSEL_IMAGE_LANDSCAPE_1 = "carousel_image_landscape_1" CAROUSEL_IMAGE_LANDSCAPE_2 = "carousel_image_landscape_2" CAROUSEL_IMAGE_LANDSCAPE_3 = "carousel_image_landscape_3" CAROUSEL_IMAGE_LANDSCAPE_4 = "carousel_image_landscape_4" CAROUSEL_IMAGE_LANDSCAPE_5 = "carousel_image_landscape_5" CAROUSEL_IMAGE_LANDSCAPE_6 = "carousel_image_landscape_6" CAROUSEL_IMAGE_LANDSCAPE_7 = "carousel_image_landscape_7" CAROUSEL_IMAGE_LANDSCAPE_8 = "carousel_image_landscape_8" CAROUSEL_IMAGE_LANDSCAPE_9 = "carousel_image_landscape_9" CAROUSEL_IMAGE_PORTRAIT_0 = "carousel_image_portrait_0" CAROUSEL_IMAGE_PORTRAIT_1 = "carousel_image_portrait_1" CAROUSEL_IMAGE_PORTRAIT_2 = "carousel_image_portrait_2" CAROUSEL_IMAGE_PORTRAIT_3 = "carousel_image_portrait_3" CAROUSEL_IMAGE_PORTRAIT_4 = "carousel_image_portrait_4" CAROUSEL_IMAGE_PORTRAIT_5 = "carousel_image_portrait_5" CAROUSEL_IMAGE_PORTRAIT_6 = "carousel_image_portrait_6" CAROUSEL_IMAGE_PORTRAIT_7 = "carousel_image_portrait_7" CAROUSEL_IMAGE_PORTRAIT_8 = "carousel_image_portrait_8" CAROUSEL_IMAGE_PORTRAIT_9 = "carousel_image_portrait_9" CAROUSEL_IMAGE_SQUARE_0 = "carousel_image_square_0" CAROUSEL_IMAGE_SQUARE_1 = "carousel_image_square_1" CAROUSEL_IMAGE_SQUARE_2 = "carousel_image_square_2" CAROUSEL_IMAGE_SQUARE_3 = "carousel_image_square_3" CAROUSEL_IMAGE_SQUARE_4 = "carousel_image_square_4" CAROUSEL_IMAGE_SQUARE_5 = "carousel_image_square_5" CAROUSEL_IMAGE_SQUARE_6 = "carousel_image_square_6" CAROUSEL_IMAGE_SQUARE_7 = "carousel_image_square_7" CAROUSEL_IMAGE_SQUARE_8 = "carousel_image_square_8" CAROUSEL_IMAGE_SQUARE_9 = "carousel_image_square_9" DESKTOP_BACKGROUND_LANDSCAPE = "desktop_background_landscape" DESKTOP_BACKGROUND_PORTRAIT = "desktop_background_portrait" DESKTOP_BACKGROUND_SQUARE = "desktop_background_square" values = frozenset( ( "brand_logo_email", "brand_logo_landscape", "brand_logo_portrait", "brand_logo_square", "carousel_image_landscape_0", "carousel_image_landscape_1", "carousel_image_landscape_2", "carousel_image_landscape_3", "carousel_image_landscape_4", "carousel_image_landscape_5", "carousel_image_landscape_6", "carousel_image_landscape_7", "carousel_image_landscape_8", "carousel_image_landscape_9", "carousel_image_portrait_0", "carousel_image_portrait_1", "carousel_image_portrait_2", "carousel_image_portrait_3", "carousel_image_portrait_4", "carousel_image_portrait_5", "carousel_image_portrait_6", "carousel_image_portrait_7", "carousel_image_portrait_8", "carousel_image_portrait_9", "carousel_image_square_0", "carousel_image_square_1", "carousel_image_square_2", "carousel_image_square_3", "carousel_image_square_4", "carousel_image_square_5", "carousel_image_square_6", "carousel_image_square_7", "carousel_image_square_8", "carousel_image_square_9", "desktop_background_landscape", "desktop_background_portrait", "desktop_background_square", ) )
class SubtenantDarkThemeImageReferenceEnum(BaseEnum): '''Represents expected values of `SubtenantDarkThemeImageReferenceEnum` This is used by Entities in the "branding" category. .. note:: If new values are added to the enum in the API they will be passed through unchanged by the SDK, but will not be on this list. If this occurs please update the SDK to the most recent version. '''
1
1
0
0
0
0
0
0.08
1
0
0
0
0
0
0
1
89
4
79
39
78
6
39
39
38
0
2
0
0
2,177
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/src/mbed_cloud/foundation/entities/branding/subtenant_light_theme_color.py
mbed_cloud.foundation.entities.branding.subtenant_light_theme_color.SubtenantLightThemeColor
class SubtenantLightThemeColor(Entity): """Represents the `SubtenantLightThemeColor` entity in Pelion Device Management""" # List of fields that are serialised between the API and SDK _api_fieldnames = ["color", "reference", "updated_at"] # List of fields that are available for the user of the SDK _sdk_fieldnames = _api_fieldnames # Renames to be performed by the SDK when receiving data {<API Field Name>: <SDK Field Name>} _renames = {} # Renames to be performed by the SDK when sending data {<SDK Field Name>: <API Field Name>} _renames_to_api = {} def __init__(self, _client=None, color=None, reference=None, updated_at=None): """Creates a local `SubtenantLightThemeColor` instance Parameters can be supplied on creation of the instance or given by setting the properties on the instance after creation. Parameters marked as `required` must be set for one or more operations on the entity. For details on when they are required please see the documentation for the setter method. :param color: The color given as name (purple) or as a hex code. :type color: str :param reference: Color name. :type reference: str :param updated_at: Last update time in UTC. :type updated_at: datetime """ super().__init__(_client=_client) # inline imports for avoiding circular references and bulk imports # fields self._color = fields.StringField(value=color) self._reference = fields.StringField(value=reference, enum=enums.SubtenantLightThemeColorReferenceEnum) self._updated_at = fields.DateTimeField(value=updated_at) @property def color(self): """The color given as name (purple) or as a hex code. api example: '#f3f93e' :rtype: str """ return self._color.value @color.setter def color(self, value): """Set value of `color` :param value: value to set :type value: str """ self._color.set(value) @property def reference(self): """Color name. :rtype: str """ return self._reference.value @reference.setter def reference(self, value): """Set value of `reference` :param value: value to set :type value: str """ self._reference.set(value) @property def updated_at(self): """Last update time in UTC. api example: '2018-02-14T15:24:14Z' :rtype: datetime """ return self._updated_at.value def delete(self, account_id): """Reset branding color to default. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/accounts/{account_id}/branding-colors/light/{reference}>`_. :param account_id: Account ID. :type account_id: str :rtype: """ return self._client.call_api( method="delete", path="/v3/accounts/{account_id}/branding-colors/light/{reference}", content_type="application/json", path_params={"account_id": fields.StringField(account_id).to_api(), "reference": self._reference.to_api()}, unpack=self, ) def read(self, account_id): """Get light theme branding color. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/accounts/{account_id}/branding-colors/light/{reference}>`_. :param account_id: Account ID. :type account_id: str :rtype: SubtenantLightThemeColor """ return self._client.call_api( method="get", path="/v3/accounts/{account_id}/branding-colors/light/{reference}", content_type="application/json", path_params={"account_id": fields.StringField(account_id).to_api(), "reference": self._reference.to_api()}, unpack=self, ) def update(self, account_id): """Updates light theme branding color. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/accounts/{account_id}/branding-colors/light/{reference}>`_. :param account_id: Account ID. :type account_id: str :rtype: SubtenantLightThemeColor """ # Conditionally setup the message body, fields which have not been set will not be sent to the API. # This avoids null fields being rejected and allows the default value to be used. body_params = {} if self._color.value_set: body_params["color"] = self._color.to_api() if self._updated_at.value_set: body_params["updated_at"] = self._updated_at.to_api() return self._client.call_api( method="put", path="/v3/accounts/{account_id}/branding-colors/light/{reference}", content_type="application/json", path_params={"account_id": fields.StringField(account_id).to_api(), "reference": self._reference.to_api()}, body_params=body_params, unpack=self, )
class SubtenantLightThemeColor(Entity): '''Represents the `SubtenantLightThemeColor` entity in Pelion Device Management''' def __init__(self, _client=None, color=None, reference=None, updated_at=None): '''Creates a local `SubtenantLightThemeColor` instance Parameters can be supplied on creation of the instance or given by setting the properties on the instance after creation. Parameters marked as `required` must be set for one or more operations on the entity. For details on when they are required please see the documentation for the setter method. :param color: The color given as name (purple) or as a hex code. :type color: str :param reference: Color name. :type reference: str :param updated_at: Last update time in UTC. :type updated_at: datetime ''' pass @property def color(self): '''The color given as name (purple) or as a hex code. api example: '#f3f93e' :rtype: str ''' pass @color.setter def color(self): '''Set value of `color` :param value: value to set :type value: str ''' pass @property def reference(self): '''Color name. :rtype: str ''' pass @reference.setter def reference(self): '''Set value of `reference` :param value: value to set :type value: str ''' pass @property def updated_at(self): '''Last update time in UTC. api example: '2018-02-14T15:24:14Z' :rtype: datetime ''' pass def delete(self, account_id): '''Reset branding color to default. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/accounts/{account_id}/branding-colors/light/{reference}>`_. :param account_id: Account ID. :type account_id: str :rtype: ''' pass def read(self, account_id): '''Get light theme branding color. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/accounts/{account_id}/branding-colors/light/{reference}>`_. :param account_id: Account ID. :type account_id: str :rtype: SubtenantLightThemeColor ''' pass def updated_at(self): '''Updates light theme branding color. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/accounts/{account_id}/branding-colors/light/{reference}>`_. :param account_id: Account ID. :type account_id: str :rtype: SubtenantLightThemeColor ''' pass
15
10
14
3
5
6
1
1.07
1
4
3
0
9
3
9
20
158
44
55
23
40
59
31
18
21
3
2
1
11
2,178
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/src/mbed_cloud/foundation/entities/branding/subtenant_dark_theme_image.py
mbed_cloud.foundation.entities.branding.subtenant_dark_theme_image.SubtenantDarkThemeImage
class SubtenantDarkThemeImage(Entity): """Represents the `SubtenantDarkThemeImage` entity in Pelion Device Management""" # List of fields that are serialised between the API and SDK _api_fieldnames = ["reference", "static_uri", "updated_at"] # List of fields that are available for the user of the SDK _sdk_fieldnames = _api_fieldnames # Renames to be performed by the SDK when receiving data {<API Field Name>: <SDK Field Name>} _renames = {} # Renames to be performed by the SDK when sending data {<SDK Field Name>: <API Field Name>} _renames_to_api = {} def __init__(self, _client=None, reference=None, static_uri=None, updated_at=None): """Creates a local `SubtenantDarkThemeImage` instance Parameters can be supplied on creation of the instance or given by setting the properties on the instance after creation. Parameters marked as `required` must be set for one or more operations on the entity. For details on when they are required please see the documentation for the setter method. :param reference: Name of the image. :type reference: str :param static_uri: The static link to the image. :type static_uri: str :param updated_at: Last update time in UTC. :type updated_at: datetime """ super().__init__(_client=_client) # inline imports for avoiding circular references and bulk imports # fields self._reference = fields.StringField(value=reference, enum=enums.SubtenantDarkThemeImageReferenceEnum) self._static_uri = fields.StringField(value=static_uri) self._updated_at = fields.DateTimeField(value=updated_at) @property def reference(self): """Name of the image. :rtype: str """ return self._reference.value @reference.setter def reference(self, value): """Set value of `reference` :param value: value to set :type value: str """ self._reference.set(value) @property def static_uri(self): """The static link to the image. api example: 'https://static.mbed.com/123456789.jpg' :rtype: str """ return self._static_uri.value @property def updated_at(self): """Last update time in UTC. api example: '2018-02-14T15:24:14Z' :rtype: datetime """ return self._updated_at.value def delete(self, account_id): """Revert an image to dark theme default. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/accounts/{account_id}/branding-images/dark/{reference}/clear>`_. :param account_id: Account ID. :type account_id: str :rtype: SubtenantDarkThemeImage """ return self._client.call_api( method="post", path="/v3/accounts/{account_id}/branding-images/dark/{reference}/clear", content_type="application/json", path_params={"account_id": fields.StringField(account_id).to_api(), "reference": self._reference.to_api()}, unpack=self, ) def read(self, account_id): """Get metadata of a dark theme image. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/accounts/{account_id}/branding-images/dark/{reference}>`_. :param account_id: Account ID. :type account_id: str :rtype: SubtenantDarkThemeImage """ return self._client.call_api( method="get", path="/v3/accounts/{account_id}/branding-images/dark/{reference}", content_type="application/json", path_params={"account_id": fields.StringField(account_id).to_api(), "reference": self._reference.to_api()}, unpack=self, ) def update(self, account_id, image): """Upload a dark theme image. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/accounts/{account_id}/branding-images/dark/{reference}/upload-multipart>`_. :param account_id: Account ID. :type account_id: str :param image: The image in PNG or JPEG format as multipart form data. Files can be provided as a file object or a path to an existing file on disk. :type image: file :rtype: SubtenantDarkThemeImage """ auto_close_image = False # If image is a string rather than a file, treat as a path and attempt to open the file. if image and isinstance(image, six.string_types): image = open(image, "rb") auto_close_image = True try: return self._client.call_api( method="post", path="/v3/accounts/{account_id}/branding-images/dark/{reference}/upload-multipart", path_params={ "account_id": fields.StringField(account_id).to_api(), "reference": self._reference.to_api(), }, stream_params={"image": ("image.png", image, "image/png")}, unpack=self, ) finally: # Calling the API may result in an exception being raised so close the files in a finally statement. # Note: Files are only closed if they were opened by the method. if auto_close_image: image.close()
class SubtenantDarkThemeImage(Entity): '''Represents the `SubtenantDarkThemeImage` entity in Pelion Device Management''' def __init__(self, _client=None, reference=None, static_uri=None, updated_at=None): '''Creates a local `SubtenantDarkThemeImage` instance Parameters can be supplied on creation of the instance or given by setting the properties on the instance after creation. Parameters marked as `required` must be set for one or more operations on the entity. For details on when they are required please see the documentation for the setter method. :param reference: Name of the image. :type reference: str :param static_uri: The static link to the image. :type static_uri: str :param updated_at: Last update time in UTC. :type updated_at: datetime ''' pass @property def reference(self): '''Name of the image. :rtype: str ''' pass @reference.setter def reference(self): '''Set value of `reference` :param value: value to set :type value: str ''' pass @property def static_uri(self): '''The static link to the image. api example: 'https://static.mbed.com/123456789.jpg' :rtype: str ''' pass @property def updated_at(self): '''Last update time in UTC. api example: '2018-02-14T15:24:14Z' :rtype: datetime ''' pass def delete(self, account_id): '''Revert an image to dark theme default. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/accounts/{account_id}/branding-images/dark/{reference}/clear>`_. :param account_id: Account ID. :type account_id: str :rtype: SubtenantDarkThemeImage ''' pass def read(self, account_id): '''Get metadata of a dark theme image. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/accounts/{account_id}/branding-images/dark/{reference}>`_. :param account_id: Account ID. :type account_id: str :rtype: SubtenantDarkThemeImage ''' pass def updated_at(self): '''Upload a dark theme image. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/accounts/{account_id}/branding-images/dark/{reference}/upload-multipart>`_. :param account_id: Account ID. :type account_id: str :param image: The image in PNG or JPEG format as multipart form data. Files can be provided as a file object or a path to an existing file on disk. :type image: file :rtype: SubtenantDarkThemeImage ''' pass
13
9
17
4
6
7
1
1.04
1
4
3
0
8
3
8
19
160
44
57
21
44
59
31
17
22
3
2
2
10
2,179
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/src/mbed_cloud/foundation/entities/branding/subtenant_dark_theme_color.py
mbed_cloud.foundation.entities.branding.subtenant_dark_theme_color.SubtenantDarkThemeColor
class SubtenantDarkThemeColor(Entity): """Represents the `SubtenantDarkThemeColor` entity in Pelion Device Management""" # List of fields that are serialised between the API and SDK _api_fieldnames = ["color", "reference", "updated_at"] # List of fields that are available for the user of the SDK _sdk_fieldnames = _api_fieldnames # Renames to be performed by the SDK when receiving data {<API Field Name>: <SDK Field Name>} _renames = {} # Renames to be performed by the SDK when sending data {<SDK Field Name>: <API Field Name>} _renames_to_api = {} def __init__(self, _client=None, color=None, reference=None, updated_at=None): """Creates a local `SubtenantDarkThemeColor` instance Parameters can be supplied on creation of the instance or given by setting the properties on the instance after creation. Parameters marked as `required` must be set for one or more operations on the entity. For details on when they are required please see the documentation for the setter method. :param color: The color given as name (purple) or as a hex code. :type color: str :param reference: Color name. :type reference: str :param updated_at: Last update time in UTC. :type updated_at: datetime """ super().__init__(_client=_client) # inline imports for avoiding circular references and bulk imports # fields self._color = fields.StringField(value=color) self._reference = fields.StringField(value=reference, enum=enums.SubtenantDarkThemeColorReferenceEnum) self._updated_at = fields.DateTimeField(value=updated_at) @property def color(self): """The color given as name (purple) or as a hex code. api example: '#f3f93e' :rtype: str """ return self._color.value @color.setter def color(self, value): """Set value of `color` :param value: value to set :type value: str """ self._color.set(value) @property def reference(self): """Color name. :rtype: str """ return self._reference.value @reference.setter def reference(self, value): """Set value of `reference` :param value: value to set :type value: str """ self._reference.set(value) @property def updated_at(self): """Last update time in UTC. api example: '2018-02-14T15:24:14Z' :rtype: datetime """ return self._updated_at.value def delete(self, account_id): """Reset branding color to default. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/accounts/{account_id}/branding-colors/dark/{reference}>`_. :param account_id: Account ID. :type account_id: str :rtype: """ return self._client.call_api( method="delete", path="/v3/accounts/{account_id}/branding-colors/dark/{reference}", content_type="application/json", path_params={"account_id": fields.StringField(account_id).to_api(), "reference": self._reference.to_api()}, unpack=self, ) def read(self, account_id): """Get dark theme branding color. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/accounts/{account_id}/branding-colors/dark/{reference}>`_. :param account_id: Account ID. :type account_id: str :rtype: SubtenantDarkThemeColor """ return self._client.call_api( method="get", path="/v3/accounts/{account_id}/branding-colors/dark/{reference}", content_type="application/json", path_params={"account_id": fields.StringField(account_id).to_api(), "reference": self._reference.to_api()}, unpack=self, ) def update(self, account_id): """Updates a dark theme branding color. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/accounts/{account_id}/branding-colors/dark/{reference}>`_. :param account_id: Account ID. :type account_id: str :rtype: SubtenantDarkThemeColor """ # Conditionally setup the message body, fields which have not been set will not be sent to the API. # This avoids null fields being rejected and allows the default value to be used. body_params = {} if self._color.value_set: body_params["color"] = self._color.to_api() if self._updated_at.value_set: body_params["updated_at"] = self._updated_at.to_api() return self._client.call_api( method="put", path="/v3/accounts/{account_id}/branding-colors/dark/{reference}", content_type="application/json", path_params={"account_id": fields.StringField(account_id).to_api(), "reference": self._reference.to_api()}, body_params=body_params, unpack=self, )
class SubtenantDarkThemeColor(Entity): '''Represents the `SubtenantDarkThemeColor` entity in Pelion Device Management''' def __init__(self, _client=None, color=None, reference=None, updated_at=None): '''Creates a local `SubtenantDarkThemeColor` instance Parameters can be supplied on creation of the instance or given by setting the properties on the instance after creation. Parameters marked as `required` must be set for one or more operations on the entity. For details on when they are required please see the documentation for the setter method. :param color: The color given as name (purple) or as a hex code. :type color: str :param reference: Color name. :type reference: str :param updated_at: Last update time in UTC. :type updated_at: datetime ''' pass @property def color(self): '''The color given as name (purple) or as a hex code. api example: '#f3f93e' :rtype: str ''' pass @color.setter def color(self): '''Set value of `color` :param value: value to set :type value: str ''' pass @property def reference(self): '''Color name. :rtype: str ''' pass @reference.setter def reference(self): '''Set value of `reference` :param value: value to set :type value: str ''' pass @property def updated_at(self): '''Last update time in UTC. api example: '2018-02-14T15:24:14Z' :rtype: datetime ''' pass def delete(self, account_id): '''Reset branding color to default. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/accounts/{account_id}/branding-colors/dark/{reference}>`_. :param account_id: Account ID. :type account_id: str :rtype: ''' pass def read(self, account_id): '''Get dark theme branding color. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/accounts/{account_id}/branding-colors/dark/{reference}>`_. :param account_id: Account ID. :type account_id: str :rtype: SubtenantDarkThemeColor ''' pass def updated_at(self): '''Updates a dark theme branding color. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/accounts/{account_id}/branding-colors/dark/{reference}>`_. :param account_id: Account ID. :type account_id: str :rtype: SubtenantDarkThemeColor ''' pass
15
10
14
3
5
6
1
1.07
1
4
3
0
9
3
9
20
158
44
55
23
40
59
31
18
21
3
2
1
11
2,180
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/src/mbed_cloud/foundation/entities/branding/light_theme_image.py
mbed_cloud.foundation.entities.branding.light_theme_image.LightThemeImage
class LightThemeImage(Entity): """Represents the `LightThemeImage` entity in Pelion Device Management""" # List of fields that are serialised between the API and SDK _api_fieldnames = ["reference", "static_uri", "updated_at"] # List of fields that are available for the user of the SDK _sdk_fieldnames = _api_fieldnames # Renames to be performed by the SDK when receiving data {<API Field Name>: <SDK Field Name>} _renames = {} # Renames to be performed by the SDK when sending data {<SDK Field Name>: <API Field Name>} _renames_to_api = {} def __init__(self, _client=None, reference=None, static_uri=None, updated_at=None): """Creates a local `LightThemeImage` instance Parameters can be supplied on creation of the instance or given by setting the properties on the instance after creation. Parameters marked as `required` must be set for one or more operations on the entity. For details on when they are required please see the documentation for the setter method. :param reference: Name of the image. :type reference: str :param static_uri: The static link to the image. :type static_uri: str :param updated_at: Last update time in UTC. :type updated_at: datetime """ super().__init__(_client=_client) # inline imports for avoiding circular references and bulk imports # fields self._reference = fields.StringField(value=reference, enum=enums.LightThemeImageReferenceEnum) self._static_uri = fields.StringField(value=static_uri) self._updated_at = fields.DateTimeField(value=updated_at) @property def reference(self): """Name of the image. :rtype: str """ return self._reference.value @reference.setter def reference(self, value): """Set value of `reference` :param value: value to set :type value: str """ self._reference.set(value) @property def static_uri(self): """The static link to the image. api example: 'https://static.mbed.com/123456789.jpg' :rtype: str """ return self._static_uri.value @property def updated_at(self): """Last update time in UTC. api example: '2018-02-14T15:24:14Z' :rtype: datetime """ return self._updated_at.value def delete(self): """Revert an image to light theme default. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/branding-images/light/{reference}/clear>`_. :rtype: LightThemeImage """ return self._client.call_api( method="post", path="/v3/branding-images/light/{reference}/clear", content_type="application/json", path_params={"reference": self._reference.to_api()}, unpack=self, ) def list(self, filter=None, order=None, max_results=None, page_size=None, include=None): """Get metadata of all light theme images. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/branding-images/light>`_. :param filter: Filtering when listing entities is not supported by the API for this entity. :type filter: mbed_cloud.client.api_filter.ApiFilter :param order: The order of the records based on creation time, ASC or DESC. Default value is ASC :type order: str :param max_results: Total maximum number of results to retrieve :type max_results: int :param page_size: The number of results to return for each page. :type page_size: int :param include: Comma separated additional data to return. :type include: str :return: An iterator object which yields instances of an entity. :rtype: mbed_cloud.pagination.PaginatedResponse(LightThemeImage) """ from mbed_cloud.foundation._custom_methods import paginate from mbed_cloud.foundation import LightThemeImage from mbed_cloud import ApiFilter # Be permissive and accept an instance of a dictionary as this was how the Legacy interface worked. if isinstance(filter, dict): filter = ApiFilter(filter_definition=filter, field_renames=LightThemeImage._renames_to_api) # The preferred method is an ApiFilter instance as this should be easier to use. elif isinstance(filter, ApiFilter): # If filter renames have not be defined then configure the ApiFilter so that any renames # performed by the SDK are reversed when the query parameters are created. if filter.field_renames is None: filter.field_renames = LightThemeImage._renames_to_api elif filter is not None: raise TypeError("The 'filter' parameter may be either 'dict' or 'ApiFilter'.") return paginate( self=self, foreign_key=LightThemeImage, filter=filter, order=order, max_results=max_results, page_size=page_size, include=include, wraps=self._paginate_list, ) def _paginate_list(self, after=None, filter=None, order=None, limit=None, include=None): """Get metadata of all light theme images. :param after: Not supported by the API. :type after: str :param filter: Optional API filter for listing resources. :type filter: mbed_cloud.client.api_filter.ApiFilter :param order: Not supported by the API. :type order: str :param limit: Not supported by the API. :type limit: int :param include: Not supported by the API. :type include: str :rtype: mbed_cloud.pagination.PaginatedResponse """ # Filter query parameters query_params = filter.to_api() if filter else {} # Add in other query parameters return self._client.call_api( method="get", path="/v3/branding-images/light", content_type="application/json", unpack=False ) def read(self): """Get metadata of a light theme image. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/branding-images/light/{reference}>`_. :rtype: LightThemeImage """ return self._client.call_api( method="get", path="/v3/branding-images/light/{reference}", content_type="application/json", path_params={"reference": self._reference.to_api()}, unpack=self, ) def update(self, image): """Upload a light theme image. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/branding-images/light/{reference}/upload-multipart>`_. :param image: The image in PNG or JPEG format as multipart form data. Files can be provided as a file object or a path to an existing file on disk. :type image: file :rtype: LightThemeImage """ auto_close_image = False # If image is a string rather than a file, treat as a path and attempt to open the file. if image and isinstance(image, six.string_types): image = open(image, "rb") auto_close_image = True try: return self._client.call_api( method="post", path="/v3/branding-images/light/{reference}/upload-multipart", stream_params={"image": ("image.png", image, "image/png")}, path_params={"reference": self._reference.to_api()}, unpack=self, ) finally: # Calling the API may result in an exception being raised so close the files in a finally statement. # Note: Files are only closed if they were opened by the method. if auto_close_image: image.close()
class LightThemeImage(Entity): '''Represents the `LightThemeImage` entity in Pelion Device Management''' def __init__(self, _client=None, reference=None, static_uri=None, updated_at=None): '''Creates a local `LightThemeImage` instance Parameters can be supplied on creation of the instance or given by setting the properties on the instance after creation. Parameters marked as `required` must be set for one or more operations on the entity. For details on when they are required please see the documentation for the setter method. :param reference: Name of the image. :type reference: str :param static_uri: The static link to the image. :type static_uri: str :param updated_at: Last update time in UTC. :type updated_at: datetime ''' pass @property def reference(self): '''Name of the image. :rtype: str ''' pass @reference.setter def reference(self): '''Set value of `reference` :param value: value to set :type value: str ''' pass @property def static_uri(self): '''The static link to the image. api example: 'https://static.mbed.com/123456789.jpg' :rtype: str ''' pass @property def updated_at(self): '''Last update time in UTC. api example: '2018-02-14T15:24:14Z' :rtype: datetime ''' pass def delete(self): '''Revert an image to light theme default. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/branding-images/light/{reference}/clear>`_. :rtype: LightThemeImage ''' pass def list(self, filter=None, order=None, max_results=None, page_size=None, include=None): '''Get metadata of all light theme images. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/branding-images/light>`_. :param filter: Filtering when listing entities is not supported by the API for this entity. :type filter: mbed_cloud.client.api_filter.ApiFilter :param order: The order of the records based on creation time, ASC or DESC. Default value is ASC :type order: str :param max_results: Total maximum number of results to retrieve :type max_results: int :param page_size: The number of results to return for each page. :type page_size: int :param include: Comma separated additional data to return. :type include: str :return: An iterator object which yields instances of an entity. :rtype: mbed_cloud.pagination.PaginatedResponse(LightThemeImage) ''' pass def _paginate_list(self, after=None, filter=None, order=None, limit=None, include=None): '''Get metadata of all light theme images. :param after: Not supported by the API. :type after: str :param filter: Optional API filter for listing resources. :type filter: mbed_cloud.client.api_filter.ApiFilter :param order: Not supported by the API. :type order: str :param limit: Not supported by the API. :type limit: int :param include: Not supported by the API. :type include: str :rtype: mbed_cloud.pagination.PaginatedResponse ''' pass def read(self): '''Get metadata of a light theme image. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/branding-images/light/{reference}>`_. :rtype: LightThemeImage ''' pass def updated_at(self): '''Upload a light theme image. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/branding-images/light/{reference}/upload-multipart>`_. :param image: The image in PNG or JPEG format as multipart form data. Files can be provided as a file object or a path to an existing file on disk. :type image: file :rtype: LightThemeImage ''' pass
15
11
20
5
7
8
2
1.11
1
7
4
0
10
3
10
21
230
61
80
27
62
89
44
23
30
5
2
2
17
2,181
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/src/mbed_cloud/foundation/entities/branding/light_theme_color.py
mbed_cloud.foundation.entities.branding.light_theme_color.LightThemeColor
class LightThemeColor(Entity): """Represents the `LightThemeColor` entity in Pelion Device Management""" # List of fields that are serialised between the API and SDK _api_fieldnames = ["color", "reference", "updated_at"] # List of fields that are available for the user of the SDK _sdk_fieldnames = _api_fieldnames # Renames to be performed by the SDK when receiving data {<API Field Name>: <SDK Field Name>} _renames = {} # Renames to be performed by the SDK when sending data {<SDK Field Name>: <API Field Name>} _renames_to_api = {} def __init__(self, _client=None, color=None, reference=None, updated_at=None): """Creates a local `LightThemeColor` instance Parameters can be supplied on creation of the instance or given by setting the properties on the instance after creation. Parameters marked as `required` must be set for one or more operations on the entity. For details on when they are required please see the documentation for the setter method. :param color: The color given as name (purple) or as a hex code. :type color: str :param reference: Color name. :type reference: str :param updated_at: Last update time in UTC. :type updated_at: datetime """ super().__init__(_client=_client) # inline imports for avoiding circular references and bulk imports # fields self._color = fields.StringField(value=color) self._reference = fields.StringField(value=reference, enum=enums.LightThemeColorReferenceEnum) self._updated_at = fields.DateTimeField(value=updated_at) @property def color(self): """The color given as name (purple) or as a hex code. api example: '#f3f93e' :rtype: str """ return self._color.value @color.setter def color(self, value): """Set value of `color` :param value: value to set :type value: str """ self._color.set(value) @property def reference(self): """Color name. :rtype: str """ return self._reference.value @reference.setter def reference(self, value): """Set value of `reference` :param value: value to set :type value: str """ self._reference.set(value) @property def updated_at(self): """Last update time in UTC. api example: '2018-02-14T15:24:14Z' :rtype: datetime """ return self._updated_at.value def delete(self): """Reset branding color to default. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/branding-colors/light/{reference}>`_. :rtype: """ return self._client.call_api( method="delete", path="/v3/branding-colors/light/{reference}", content_type="application/json", path_params={"reference": self._reference.to_api()}, unpack=self, ) def list(self, filter=None, order=None, max_results=None, page_size=None, include=None): """Get light theme branding colors. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/branding-colors/light>`_. :param filter: Filtering when listing entities is not supported by the API for this entity. :type filter: mbed_cloud.client.api_filter.ApiFilter :param order: The order of the records based on creation time, ASC or DESC. Default value is ASC :type order: str :param max_results: Total maximum number of results to retrieve :type max_results: int :param page_size: The number of results to return for each page. :type page_size: int :param include: Comma separated additional data to return. :type include: str :return: An iterator object which yields instances of an entity. :rtype: mbed_cloud.pagination.PaginatedResponse(LightThemeColor) """ from mbed_cloud.foundation._custom_methods import paginate from mbed_cloud.foundation import LightThemeColor from mbed_cloud import ApiFilter # Be permissive and accept an instance of a dictionary as this was how the Legacy interface worked. if isinstance(filter, dict): filter = ApiFilter(filter_definition=filter, field_renames=LightThemeColor._renames_to_api) # The preferred method is an ApiFilter instance as this should be easier to use. elif isinstance(filter, ApiFilter): # If filter renames have not be defined then configure the ApiFilter so that any renames # performed by the SDK are reversed when the query parameters are created. if filter.field_renames is None: filter.field_renames = LightThemeColor._renames_to_api elif filter is not None: raise TypeError("The 'filter' parameter may be either 'dict' or 'ApiFilter'.") return paginate( self=self, foreign_key=LightThemeColor, filter=filter, order=order, max_results=max_results, page_size=page_size, include=include, wraps=self._paginate_list, ) def _paginate_list(self, after=None, filter=None, order=None, limit=None, include=None): """Get light theme branding colors. :param after: Not supported by the API. :type after: str :param filter: Optional API filter for listing resources. :type filter: mbed_cloud.client.api_filter.ApiFilter :param order: Not supported by the API. :type order: str :param limit: Not supported by the API. :type limit: int :param include: Not supported by the API. :type include: str :rtype: mbed_cloud.pagination.PaginatedResponse """ # Filter query parameters query_params = filter.to_api() if filter else {} # Add in other query parameters return self._client.call_api( method="get", path="/v3/branding-colors/light", content_type="application/json", unpack=False ) def read(self): """Get light theme branding color. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/branding-colors/light/{reference}>`_. :rtype: LightThemeColor """ return self._client.call_api( method="get", path="/v3/branding-colors/light/{reference}", content_type="application/json", path_params={"reference": self._reference.to_api()}, unpack=self, ) def update(self): """Updates light theme branding color. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/branding-colors/light/{reference}>`_. :rtype: LightThemeColor """ # Conditionally setup the message body, fields which have not been set will not be sent to the API. # This avoids null fields being rejected and allows the default value to be used. body_params = {} if self._color.value_set: body_params["color"] = self._color.to_api() if self._updated_at.value_set: body_params["updated_at"] = self._updated_at.to_api() return self._client.call_api( method="put", path="/v3/branding-colors/light/{reference}", content_type="application/json", body_params=body_params, path_params={"reference": self._reference.to_api()}, unpack=self, )
class LightThemeColor(Entity): '''Represents the `LightThemeColor` entity in Pelion Device Management''' def __init__(self, _client=None, color=None, reference=None, updated_at=None): '''Creates a local `LightThemeColor` instance Parameters can be supplied on creation of the instance or given by setting the properties on the instance after creation. Parameters marked as `required` must be set for one or more operations on the entity. For details on when they are required please see the documentation for the setter method. :param color: The color given as name (purple) or as a hex code. :type color: str :param reference: Color name. :type reference: str :param updated_at: Last update time in UTC. :type updated_at: datetime ''' pass @property def color(self): '''The color given as name (purple) or as a hex code. api example: '#f3f93e' :rtype: str ''' pass @color.setter def color(self): '''Set value of `color` :param value: value to set :type value: str ''' pass @property def reference(self): '''Color name. :rtype: str ''' pass @reference.setter def reference(self): '''Set value of `reference` :param value: value to set :type value: str ''' pass @property def updated_at(self): '''Last update time in UTC. api example: '2018-02-14T15:24:14Z' :rtype: datetime ''' pass def delete(self): '''Reset branding color to default. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/branding-colors/light/{reference}>`_. :rtype: ''' pass def list(self, filter=None, order=None, max_results=None, page_size=None, include=None): '''Get light theme branding colors. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/branding-colors/light>`_. :param filter: Filtering when listing entities is not supported by the API for this entity. :type filter: mbed_cloud.client.api_filter.ApiFilter :param order: The order of the records based on creation time, ASC or DESC. Default value is ASC :type order: str :param max_results: Total maximum number of results to retrieve :type max_results: int :param page_size: The number of results to return for each page. :type page_size: int :param include: Comma separated additional data to return. :type include: str :return: An iterator object which yields instances of an entity. :rtype: mbed_cloud.pagination.PaginatedResponse(LightThemeColor) ''' pass def _paginate_list(self, after=None, filter=None, order=None, limit=None, include=None): '''Get light theme branding colors. :param after: Not supported by the API. :type after: str :param filter: Optional API filter for listing resources. :type filter: mbed_cloud.client.api_filter.ApiFilter :param order: Not supported by the API. :type order: str :param limit: Not supported by the API. :type limit: int :param include: Not supported by the API. :type include: str :rtype: mbed_cloud.pagination.PaginatedResponse ''' pass def read(self): '''Get light theme branding color. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/branding-colors/light/{reference}>`_. :rtype: LightThemeColor ''' pass def updated_at(self): '''Updates light theme branding color. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/branding-colors/light/{reference}>`_. :rtype: LightThemeColor ''' pass
17
12
18
4
6
8
2
1.1
1
7
4
0
11
3
11
22
231
61
81
29
61
89
44
24
29
5
2
2
18
2,182
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/src/mbed_cloud/foundation/entities/branding/enums.py
mbed_cloud.foundation.entities.branding.enums.SubtenantLightThemeImageReferenceEnum
class SubtenantLightThemeImageReferenceEnum(BaseEnum): """Represents expected values of `SubtenantLightThemeImageReferenceEnum` This is used by Entities in the "branding" category. .. note:: If new values are added to the enum in the API they will be passed through unchanged by the SDK, but will not be on this list. If this occurs please update the SDK to the most recent version. """ BRAND_LOGO_EMAIL = "brand_logo_email" BRAND_LOGO_LANDSCAPE = "brand_logo_landscape" BRAND_LOGO_PORTRAIT = "brand_logo_portrait" BRAND_LOGO_SQUARE = "brand_logo_square" CAROUSEL_IMAGE_LANDSCAPE_0 = "carousel_image_landscape_0" CAROUSEL_IMAGE_LANDSCAPE_1 = "carousel_image_landscape_1" CAROUSEL_IMAGE_LANDSCAPE_2 = "carousel_image_landscape_2" CAROUSEL_IMAGE_LANDSCAPE_3 = "carousel_image_landscape_3" CAROUSEL_IMAGE_LANDSCAPE_4 = "carousel_image_landscape_4" CAROUSEL_IMAGE_LANDSCAPE_5 = "carousel_image_landscape_5" CAROUSEL_IMAGE_LANDSCAPE_6 = "carousel_image_landscape_6" CAROUSEL_IMAGE_LANDSCAPE_7 = "carousel_image_landscape_7" CAROUSEL_IMAGE_LANDSCAPE_8 = "carousel_image_landscape_8" CAROUSEL_IMAGE_LANDSCAPE_9 = "carousel_image_landscape_9" CAROUSEL_IMAGE_PORTRAIT_0 = "carousel_image_portrait_0" CAROUSEL_IMAGE_PORTRAIT_1 = "carousel_image_portrait_1" CAROUSEL_IMAGE_PORTRAIT_2 = "carousel_image_portrait_2" CAROUSEL_IMAGE_PORTRAIT_3 = "carousel_image_portrait_3" CAROUSEL_IMAGE_PORTRAIT_4 = "carousel_image_portrait_4" CAROUSEL_IMAGE_PORTRAIT_5 = "carousel_image_portrait_5" CAROUSEL_IMAGE_PORTRAIT_6 = "carousel_image_portrait_6" CAROUSEL_IMAGE_PORTRAIT_7 = "carousel_image_portrait_7" CAROUSEL_IMAGE_PORTRAIT_8 = "carousel_image_portrait_8" CAROUSEL_IMAGE_PORTRAIT_9 = "carousel_image_portrait_9" CAROUSEL_IMAGE_SQUARE_0 = "carousel_image_square_0" CAROUSEL_IMAGE_SQUARE_1 = "carousel_image_square_1" CAROUSEL_IMAGE_SQUARE_2 = "carousel_image_square_2" CAROUSEL_IMAGE_SQUARE_3 = "carousel_image_square_3" CAROUSEL_IMAGE_SQUARE_4 = "carousel_image_square_4" CAROUSEL_IMAGE_SQUARE_5 = "carousel_image_square_5" CAROUSEL_IMAGE_SQUARE_6 = "carousel_image_square_6" CAROUSEL_IMAGE_SQUARE_7 = "carousel_image_square_7" CAROUSEL_IMAGE_SQUARE_8 = "carousel_image_square_8" CAROUSEL_IMAGE_SQUARE_9 = "carousel_image_square_9" DESKTOP_BACKGROUND_LANDSCAPE = "desktop_background_landscape" DESKTOP_BACKGROUND_PORTRAIT = "desktop_background_portrait" DESKTOP_BACKGROUND_SQUARE = "desktop_background_square" values = frozenset( ( "brand_logo_email", "brand_logo_landscape", "brand_logo_portrait", "brand_logo_square", "carousel_image_landscape_0", "carousel_image_landscape_1", "carousel_image_landscape_2", "carousel_image_landscape_3", "carousel_image_landscape_4", "carousel_image_landscape_5", "carousel_image_landscape_6", "carousel_image_landscape_7", "carousel_image_landscape_8", "carousel_image_landscape_9", "carousel_image_portrait_0", "carousel_image_portrait_1", "carousel_image_portrait_2", "carousel_image_portrait_3", "carousel_image_portrait_4", "carousel_image_portrait_5", "carousel_image_portrait_6", "carousel_image_portrait_7", "carousel_image_portrait_8", "carousel_image_portrait_9", "carousel_image_square_0", "carousel_image_square_1", "carousel_image_square_2", "carousel_image_square_3", "carousel_image_square_4", "carousel_image_square_5", "carousel_image_square_6", "carousel_image_square_7", "carousel_image_square_8", "carousel_image_square_9", "desktop_background_landscape", "desktop_background_portrait", "desktop_background_square", ) )
class SubtenantLightThemeImageReferenceEnum(BaseEnum): '''Represents expected values of `SubtenantLightThemeImageReferenceEnum` This is used by Entities in the "branding" category. .. note:: If new values are added to the enum in the API they will be passed through unchanged by the SDK, but will not be on this list. If this occurs please update the SDK to the most recent version. '''
1
1
0
0
0
0
0
0.08
1
0
0
0
0
0
0
1
89
4
79
39
78
6
39
39
38
0
2
0
0
2,183
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/src/mbed_cloud/foundation/entities/branding/enums.py
mbed_cloud.foundation.entities.branding.enums.SubtenantLightThemeColorReferenceEnum
class SubtenantLightThemeColorReferenceEnum(BaseEnum): """Represents expected values of `SubtenantLightThemeColorReferenceEnum` This is used by Entities in the "branding" category. .. note:: If new values are added to the enum in the API they will be passed through unchanged by the SDK, but will not be on this list. If this occurs please update the SDK to the most recent version. """ CANVAS_BACKGROUND = "canvas_background" CANVAS_BACKGROUND_FONT_COLOR = "canvas_background_font_color" ERROR_COLOR = "error_color" ERROR_FONT_COLOR = "error_font_color" INFO_COLOR = "info_color" INFO_FONT_COLOR = "info_font_color" PRIMARY = "primary" PRIMARY_FONT_COLOR = "primary_font_color" SECONDARY = "secondary" SECONDARY_FONT_COLOR = "secondary_font_color" SUCCESS_COLOR = "success_color" SUCCESS_FONT_COLOR = "success_font_color" WARNING_COLOR = "warning_color" WARNING_FONT_COLOR = "warning_font_color" WORKSPACE_BACKGROUND = "workspace_background" WORKSPACE_BACKGROUND_FONT_COLOR = "workspace_background_font_color" values = frozenset( ( "canvas_background", "canvas_background_font_color", "error_color", "error_font_color", "info_color", "info_font_color", "primary", "primary_font_color", "secondary", "secondary_font_color", "success_color", "success_font_color", "warning_color", "warning_font_color", "workspace_background", "workspace_background_font_color", ) )
class SubtenantLightThemeColorReferenceEnum(BaseEnum): '''Represents expected values of `SubtenantLightThemeColorReferenceEnum` This is used by Entities in the "branding" category. .. note:: If new values are added to the enum in the API they will be passed through unchanged by the SDK, but will not be on this list. If this occurs please update the SDK to the most recent version. '''
1
1
0
0
0
0
0
0.16
1
0
0
0
0
0
0
1
47
4
37
18
36
6
18
18
17
0
2
0
0
2,184
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/src/mbed_cloud/foundation/entities/branding/enums.py
mbed_cloud.foundation.entities.branding.enums.SubtenantDarkThemeColorReferenceEnum
class SubtenantDarkThemeColorReferenceEnum(BaseEnum): """Represents expected values of `SubtenantDarkThemeColorReferenceEnum` This is used by Entities in the "branding" category. .. note:: If new values are added to the enum in the API they will be passed through unchanged by the SDK, but will not be on this list. If this occurs please update the SDK to the most recent version. """ CANVAS_BACKGROUND = "canvas_background" CANVAS_BACKGROUND_FONT_COLOR = "canvas_background_font_color" ERROR_COLOR = "error_color" ERROR_FONT_COLOR = "error_font_color" INFO_COLOR = "info_color" INFO_FONT_COLOR = "info_font_color" PRIMARY = "primary" PRIMARY_FONT_COLOR = "primary_font_color" SECONDARY = "secondary" SECONDARY_FONT_COLOR = "secondary_font_color" SUCCESS_COLOR = "success_color" SUCCESS_FONT_COLOR = "success_font_color" WARNING_COLOR = "warning_color" WARNING_FONT_COLOR = "warning_font_color" WORKSPACE_BACKGROUND = "workspace_background" WORKSPACE_BACKGROUND_FONT_COLOR = "workspace_background_font_color" values = frozenset( ( "canvas_background", "canvas_background_font_color", "error_color", "error_font_color", "info_color", "info_font_color", "primary", "primary_font_color", "secondary", "secondary_font_color", "success_color", "success_font_color", "warning_color", "warning_font_color", "workspace_background", "workspace_background_font_color", ) )
class SubtenantDarkThemeColorReferenceEnum(BaseEnum): '''Represents expected values of `SubtenantDarkThemeColorReferenceEnum` This is used by Entities in the "branding" category. .. note:: If new values are added to the enum in the API they will be passed through unchanged by the SDK, but will not be on this list. If this occurs please update the SDK to the most recent version. '''
1
1
0
0
0
0
0
0.16
1
0
0
0
0
0
0
1
47
4
37
18
36
6
18
18
17
0
2
0
0
2,185
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/src/mbed_cloud/foundation/entities/branding/enums.py
mbed_cloud.foundation.entities.branding.enums.LightThemeImageReferenceEnum
class LightThemeImageReferenceEnum(BaseEnum): """Represents expected values of `LightThemeImageReferenceEnum` This is used by Entities in the "branding" category. .. note:: If new values are added to the enum in the API they will be passed through unchanged by the SDK, but will not be on this list. If this occurs please update the SDK to the most recent version. """ BRAND_LOGO_EMAIL = "brand_logo_email" BRAND_LOGO_LANDSCAPE = "brand_logo_landscape" BRAND_LOGO_PORTRAIT = "brand_logo_portrait" BRAND_LOGO_SQUARE = "brand_logo_square" CAROUSEL_IMAGE_LANDSCAPE_0 = "carousel_image_landscape_0" CAROUSEL_IMAGE_LANDSCAPE_1 = "carousel_image_landscape_1" CAROUSEL_IMAGE_LANDSCAPE_2 = "carousel_image_landscape_2" CAROUSEL_IMAGE_LANDSCAPE_3 = "carousel_image_landscape_3" CAROUSEL_IMAGE_LANDSCAPE_4 = "carousel_image_landscape_4" CAROUSEL_IMAGE_LANDSCAPE_5 = "carousel_image_landscape_5" CAROUSEL_IMAGE_LANDSCAPE_6 = "carousel_image_landscape_6" CAROUSEL_IMAGE_LANDSCAPE_7 = "carousel_image_landscape_7" CAROUSEL_IMAGE_LANDSCAPE_8 = "carousel_image_landscape_8" CAROUSEL_IMAGE_LANDSCAPE_9 = "carousel_image_landscape_9" CAROUSEL_IMAGE_PORTRAIT_0 = "carousel_image_portrait_0" CAROUSEL_IMAGE_PORTRAIT_1 = "carousel_image_portrait_1" CAROUSEL_IMAGE_PORTRAIT_2 = "carousel_image_portrait_2" CAROUSEL_IMAGE_PORTRAIT_3 = "carousel_image_portrait_3" CAROUSEL_IMAGE_PORTRAIT_4 = "carousel_image_portrait_4" CAROUSEL_IMAGE_PORTRAIT_5 = "carousel_image_portrait_5" CAROUSEL_IMAGE_PORTRAIT_6 = "carousel_image_portrait_6" CAROUSEL_IMAGE_PORTRAIT_7 = "carousel_image_portrait_7" CAROUSEL_IMAGE_PORTRAIT_8 = "carousel_image_portrait_8" CAROUSEL_IMAGE_PORTRAIT_9 = "carousel_image_portrait_9" CAROUSEL_IMAGE_SQUARE_0 = "carousel_image_square_0" CAROUSEL_IMAGE_SQUARE_1 = "carousel_image_square_1" CAROUSEL_IMAGE_SQUARE_2 = "carousel_image_square_2" CAROUSEL_IMAGE_SQUARE_3 = "carousel_image_square_3" CAROUSEL_IMAGE_SQUARE_4 = "carousel_image_square_4" CAROUSEL_IMAGE_SQUARE_5 = "carousel_image_square_5" CAROUSEL_IMAGE_SQUARE_6 = "carousel_image_square_6" CAROUSEL_IMAGE_SQUARE_7 = "carousel_image_square_7" CAROUSEL_IMAGE_SQUARE_8 = "carousel_image_square_8" CAROUSEL_IMAGE_SQUARE_9 = "carousel_image_square_9" DESKTOP_BACKGROUND_LANDSCAPE = "desktop_background_landscape" DESKTOP_BACKGROUND_PORTRAIT = "desktop_background_portrait" DESKTOP_BACKGROUND_SQUARE = "desktop_background_square" values = frozenset( ( "brand_logo_email", "brand_logo_landscape", "brand_logo_portrait", "brand_logo_square", "carousel_image_landscape_0", "carousel_image_landscape_1", "carousel_image_landscape_2", "carousel_image_landscape_3", "carousel_image_landscape_4", "carousel_image_landscape_5", "carousel_image_landscape_6", "carousel_image_landscape_7", "carousel_image_landscape_8", "carousel_image_landscape_9", "carousel_image_portrait_0", "carousel_image_portrait_1", "carousel_image_portrait_2", "carousel_image_portrait_3", "carousel_image_portrait_4", "carousel_image_portrait_5", "carousel_image_portrait_6", "carousel_image_portrait_7", "carousel_image_portrait_8", "carousel_image_portrait_9", "carousel_image_square_0", "carousel_image_square_1", "carousel_image_square_2", "carousel_image_square_3", "carousel_image_square_4", "carousel_image_square_5", "carousel_image_square_6", "carousel_image_square_7", "carousel_image_square_8", "carousel_image_square_9", "desktop_background_landscape", "desktop_background_portrait", "desktop_background_square", ) )
class LightThemeImageReferenceEnum(BaseEnum): '''Represents expected values of `LightThemeImageReferenceEnum` This is used by Entities in the "branding" category. .. note:: If new values are added to the enum in the API they will be passed through unchanged by the SDK, but will not be on this list. If this occurs please update the SDK to the most recent version. '''
1
1
0
0
0
0
0
0.08
1
0
0
0
0
0
0
1
89
4
79
39
78
6
39
39
38
0
2
0
0
2,186
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/tests/unit/test_pagination.py
tests.unit.test_pagination.Test
class Test(BaseCase, ListCompatMixin): """ Ths test sequence uses a stub implementation of a 'list' API endpoint Which uses 'after' as a form of cursor to perform pagination The sequence is run a second time with TestNoCache, wherein `_is_caching` is set False. Some tests behave differently without caching. (namely, without the cache you can't repeatedly list an exhausted iterator). """ paginator = PaginatedResponse def test_wrapped(self): def wrapper(x): x.wrapped = True return x p = self.paginator(ListResponse, wrapper) first = next(p) second = p.next() self.assertEqual(first, D(0)) self.assertTrue(first.wrapped) self.assertTrue(second.wrapped) def test_empty_response(self): p = self.paginator(ListResponse, stubber_total=0) self.assert_list_compat(p, []) def test_one_response(self): p = self.paginator(ListResponse, stubber_total=2) self.assert_list_compat(p, [D(0), D(1)]) def test_has_more(self): getter = partial(ListResponse) p = PaginatedResponse(getter) self.assertEqual([next(p) for _ in range(4)], [D(0), D(1), D(2), D(3)]) def test_partial_state(self): # cheats a bit, writes internal state p = self.paginator(ListResponse, stubber_total=12) p._current_data_page = [D(i) for i in range(5, 9)] # 5, 6, 7, 8 p._next_id = 8 self.assertEqual(None, p._total_count) self.assertEqual(12, len(p)) self.assert_list_compat([D(i) for i in range(5, 12)], p) # 5, 6, 7, 8, 9, 10, 11 def test_single_page_state(self): # cheats a bit, reads internal state p = self.paginator(ListResponse, stubber_total=12, page_size=4) d = next(p) self.assertEqual(d, D(0)) # 0 self.assert_list_compat(p._current_data_page, [D(i) for i in range(1, 4)]) # 1, 2, 3 def test_exhausted(self): p = self.paginator(ListResponse) self.assertFalse(p._is_exhausted) x = list(p) # exhaust the generator self.assertTrue(p._is_exhausted) self.assertEqual(p._current_count, 5) self.assertEqual(p._get_total_concrete(), 5) self.assertEqual(5, len(x)) if p._is_caching: self.assert_list_compat(x, list(p)) # iterating again returns same data with self.assertRaises(StopIteration): next(p) def test_limit(self): p = self.paginator(ListResponse, stubber_total=7, limit=5) self.assertEqual(5, len(list(p))) def test_max_results(self): p = self.paginator(ListResponse, stubber_total=7, max_results=5) self.assertEqual(5, len(list(p))) def test_page_size(self): p = self.paginator(ListResponse, stubber_total=7, page_size=5) self.assertEqual(7, len(list(p))) def test_count(self): p = self.paginator(ListResponse, stubber_total=7) self.assertEqual(7, p.count()) def test_bool_false(self): # check boolean of object is exactly a boolean False p = self.paginator(ListResponse, stubber_total=0) self.assertIs(bool(p), False) def test_bool_true(self): # check boolean of object is exactly a boolean True p = self.paginator(ListResponse) self.assertIs(bool(p), True) def test_repr(self): p = self.paginator(ListResponse) self.assertEqual('<PaginatedResponse D<0>,D<1>,D<2>...>', repr(p)) def test_all(self): p = self.paginator(ListResponse) next(p) self.assert_list_compat(p.all(), [D(0), D(1), D(2), D(3), D(4)]) def test_first(self): p = self.paginator(ListResponse) self.assertEqual(p.first(), D(0)) def test_first_or_none(self): p = self.paginator(ListResponse, stubber_total=0) self.assertIs(p.first(), None) def test_first_all_iter(self): p = self.paginator(ListResponse) iter_first = next(p) iter_rest = list(p) explicit_first = p.first() self.assertEqual(iter_first, D(0)) self.assertEqual(explicit_first, D(0)) self.assert_list_compat(iter_rest, [D(1), D(2), D(3), D(4)]) if p._is_caching: explicit_all = iter(p) self.assert_list_compat(explicit_all, [D(0), D(1), D(2), D(3), D(4)]) else: with self.assertRaises(StopIteration): iter(p) def test_to_dict(self): p = self.paginator(ListResponse, stubber_total=2) self.assertEqual( { 'after': None, 'data': [D(0), D(1)], 'has_more': False, 'limit': None, 'order': 'ASC', 'page_size': None, 'total_count': 2, }, p.to_dict() ) def test_data_deprecation(self): p = self.paginator(ListResponse, stubber_total=2) if p._is_caching: # this is how a lot of old code was written (.data[0]) self.assertEqual(list(p)[0], p.data[0]) # elevate warnings to errors and check we throw one on calling .data import warnings warnings.simplefilter('error') with self.assertRaises(DeprecationWarning): self.assertTrue(p.data) warnings.resetwarnings()
class Test(BaseCase, ListCompatMixin): ''' Ths test sequence uses a stub implementation of a 'list' API endpoint Which uses 'after' as a form of cursor to perform pagination The sequence is run a second time with TestNoCache, wherein `_is_caching` is set False. Some tests behave differently without caching. (namely, without the cache you can't repeatedly list an exhausted iterator). ''' def test_wrapped(self): pass def wrapper(x): pass def test_empty_response(self): pass def test_one_response(self): pass def test_has_more(self): pass def test_partial_state(self): pass def test_single_page_state(self): pass def test_exhausted(self): pass def test_limit(self): pass def test_max_results(self): pass def test_page_size(self): pass def test_count(self): pass def test_bool_false(self): pass def test_bool_true(self): pass def test_repr(self): pass def test_all(self): pass def test_first(self): pass def test_first_or_none(self): pass def test_first_all_iter(self): pass def test_to_dict(self): pass def test_data_deprecation(self): pass
22
1
6
0
5
1
1
0.17
2
9
3
1
20
0
20
93
152
25
114
54
91
19
102
53
79
2
3
2
24
2,187
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/src/mbed_cloud/foundation/entities/branding/enums.py
mbed_cloud.foundation.entities.branding.enums.LightThemeColorReferenceEnum
class LightThemeColorReferenceEnum(BaseEnum): """Represents expected values of `LightThemeColorReferenceEnum` This is used by Entities in the "branding" category. .. note:: If new values are added to the enum in the API they will be passed through unchanged by the SDK, but will not be on this list. If this occurs please update the SDK to the most recent version. """ CANVAS_BACKGROUND = "canvas_background" CANVAS_BACKGROUND_FONT_COLOR = "canvas_background_font_color" ERROR_COLOR = "error_color" ERROR_FONT_COLOR = "error_font_color" INFO_COLOR = "info_color" INFO_FONT_COLOR = "info_font_color" PRIMARY = "primary" PRIMARY_FONT_COLOR = "primary_font_color" SECONDARY = "secondary" SECONDARY_FONT_COLOR = "secondary_font_color" SUCCESS_COLOR = "success_color" SUCCESS_FONT_COLOR = "success_font_color" WARNING_COLOR = "warning_color" WARNING_FONT_COLOR = "warning_font_color" WORKSPACE_BACKGROUND = "workspace_background" WORKSPACE_BACKGROUND_FONT_COLOR = "workspace_background_font_color" values = frozenset( ( "canvas_background", "canvas_background_font_color", "error_color", "error_font_color", "info_color", "info_font_color", "primary", "primary_font_color", "secondary", "secondary_font_color", "success_color", "success_font_color", "warning_color", "warning_font_color", "workspace_background", "workspace_background_font_color", ) )
class LightThemeColorReferenceEnum(BaseEnum): '''Represents expected values of `LightThemeColorReferenceEnum` This is used by Entities in the "branding" category. .. note:: If new values are added to the enum in the API they will be passed through unchanged by the SDK, but will not be on this list. If this occurs please update the SDK to the most recent version. '''
1
1
0
0
0
0
0
0.16
1
0
0
0
0
0
0
1
47
4
37
18
36
6
18
18
17
0
2
0
0
2,188
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/src/mbed_cloud/foundation/entities/branding/subtenant_light_theme_image.py
mbed_cloud.foundation.entities.branding.subtenant_light_theme_image.SubtenantLightThemeImage
class SubtenantLightThemeImage(Entity): """Represents the `SubtenantLightThemeImage` entity in Pelion Device Management""" # List of fields that are serialised between the API and SDK _api_fieldnames = ["reference", "static_uri", "updated_at"] # List of fields that are available for the user of the SDK _sdk_fieldnames = _api_fieldnames # Renames to be performed by the SDK when receiving data {<API Field Name>: <SDK Field Name>} _renames = {} # Renames to be performed by the SDK when sending data {<SDK Field Name>: <API Field Name>} _renames_to_api = {} def __init__(self, _client=None, reference=None, static_uri=None, updated_at=None): """Creates a local `SubtenantLightThemeImage` instance Parameters can be supplied on creation of the instance or given by setting the properties on the instance after creation. Parameters marked as `required` must be set for one or more operations on the entity. For details on when they are required please see the documentation for the setter method. :param reference: Name of the image. :type reference: str :param static_uri: The static link to the image. :type static_uri: str :param updated_at: Last update time in UTC. :type updated_at: datetime """ super().__init__(_client=_client) # inline imports for avoiding circular references and bulk imports # fields self._reference = fields.StringField(value=reference, enum=enums.SubtenantLightThemeImageReferenceEnum) self._static_uri = fields.StringField(value=static_uri) self._updated_at = fields.DateTimeField(value=updated_at) @property def reference(self): """Name of the image. :rtype: str """ return self._reference.value @reference.setter def reference(self, value): """Set value of `reference` :param value: value to set :type value: str """ self._reference.set(value) @property def static_uri(self): """The static link to the image. api example: 'https://static.mbed.com/123456789.jpg' :rtype: str """ return self._static_uri.value @property def updated_at(self): """Last update time in UTC. api example: '2018-02-14T15:24:14Z' :rtype: datetime """ return self._updated_at.value def delete(self, account_id): """Revert an image to light theme default. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/accounts/{account_id}/branding-images/light/{reference}/clear>`_. :param account_id: Account ID. :type account_id: str :rtype: SubtenantLightThemeImage """ return self._client.call_api( method="post", path="/v3/accounts/{account_id}/branding-images/light/{reference}/clear", content_type="application/json", path_params={"account_id": fields.StringField(account_id).to_api(), "reference": self._reference.to_api()}, unpack=self, ) def read(self, account_id): """Get metadata of a light theme image. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/accounts/{account_id}/branding-images/light/{reference}>`_. :param account_id: Account ID. :type account_id: str :rtype: SubtenantLightThemeImage """ return self._client.call_api( method="get", path="/v3/accounts/{account_id}/branding-images/light/{reference}", content_type="application/json", path_params={"account_id": fields.StringField(account_id).to_api(), "reference": self._reference.to_api()}, unpack=self, ) def update(self, account_id, image): """Upload a light theme image. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/accounts/{account_id}/branding-images/light/{reference}/upload-multipart>`_. :param account_id: Account ID. :type account_id: str :param image: The image in PNG or JPEG format as multipart form data. Files can be provided as a file object or a path to an existing file on disk. :type image: file :rtype: SubtenantLightThemeImage """ auto_close_image = False # If image is a string rather than a file, treat as a path and attempt to open the file. if image and isinstance(image, six.string_types): image = open(image, "rb") auto_close_image = True try: return self._client.call_api( method="post", path="/v3/accounts/{account_id}/branding-images/light/{reference}/upload-multipart", path_params={ "account_id": fields.StringField(account_id).to_api(), "reference": self._reference.to_api(), }, stream_params={"image": ("image.png", image, "image/png")}, unpack=self, ) finally: # Calling the API may result in an exception being raised so close the files in a finally statement. # Note: Files are only closed if they were opened by the method. if auto_close_image: image.close()
class SubtenantLightThemeImage(Entity): '''Represents the `SubtenantLightThemeImage` entity in Pelion Device Management''' def __init__(self, _client=None, reference=None, static_uri=None, updated_at=None): '''Creates a local `SubtenantLightThemeImage` instance Parameters can be supplied on creation of the instance or given by setting the properties on the instance after creation. Parameters marked as `required` must be set for one or more operations on the entity. For details on when they are required please see the documentation for the setter method. :param reference: Name of the image. :type reference: str :param static_uri: The static link to the image. :type static_uri: str :param updated_at: Last update time in UTC. :type updated_at: datetime ''' pass @property def reference(self): '''Name of the image. :rtype: str ''' pass @reference.setter def reference(self): '''Set value of `reference` :param value: value to set :type value: str ''' pass @property def static_uri(self): '''The static link to the image. api example: 'https://static.mbed.com/123456789.jpg' :rtype: str ''' pass @property def updated_at(self): '''Last update time in UTC. api example: '2018-02-14T15:24:14Z' :rtype: datetime ''' pass def delete(self, account_id): '''Revert an image to light theme default. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/accounts/{account_id}/branding-images/light/{reference}/clear>`_. :param account_id: Account ID. :type account_id: str :rtype: SubtenantLightThemeImage ''' pass def read(self, account_id): '''Get metadata of a light theme image. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/accounts/{account_id}/branding-images/light/{reference}>`_. :param account_id: Account ID. :type account_id: str :rtype: SubtenantLightThemeImage ''' pass def updated_at(self): '''Upload a light theme image. `REST API Documentation <https://os.mbed.com/search/?q=Service+API+References+/v3/accounts/{account_id}/branding-images/light/{reference}/upload-multipart>`_. :param account_id: Account ID. :type account_id: str :param image: The image in PNG or JPEG format as multipart form data. Files can be provided as a file object or a path to an existing file on disk. :type image: file :rtype: SubtenantLightThemeImage ''' pass
13
9
17
4
6
7
1
1.04
1
4
3
0
8
3
8
19
160
44
57
21
44
59
31
17
22
3
2
2
10
2,189
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/tests/unit/test_pagination.py
tests.unit.test_pagination.ListResponse
class ListResponse: def __init__(self, stubber_total=5, limit=None, include=None, after=None, **kwargs): """Statelessly stubs the behaviour of APIs to match the swagger specs we create [D0, D1, ... DN] data objects that contain an ID :param stubber_total: actual total number of results :param limit: requested page size :param include: list of fields to include :param after: return results after this ID :returns: a list of data objects """ # upper index to return from results list upper_bound = None # in the apis 'after' refers to IDs (right-aligned) # so increment to convert to indices (left-aligned) after = after + 1 if after is not None else 0 # apis typically have a minimum limit of 2, if it is set if limit is not None: limit = max(2, limit) upper_bound = after + limit # has_more indicates whether there's another page of results self.has_more = after + (limit or 0) < stubber_total # slicing the range operator provides truncation of upper_bound self.data = [D(i) for i in range(stubber_total)[slice(after, upper_bound)]] if include: self.total_count = stubber_total
class ListResponse: def __init__(self, stubber_total=5, limit=None, include=None, after=None, **kwargs): '''Statelessly stubs the behaviour of APIs to match the swagger specs we create [D0, D1, ... DN] data objects that contain an ID :param stubber_total: actual total number of results :param limit: requested page size :param include: list of fields to include :param after: return results after this ID :returns: a list of data objects ''' pass
2
1
30
6
10
14
4
1.27
0
3
1
0
1
3
1
1
31
6
11
6
9
14
11
6
9
4
0
1
4
2,190
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/tests/unit/foundation/test_entity.py
tests.unit.foundation.test_entity.TestEntity
class TestEntity(BaseCase): def test_to_api(self): entity_fields = { "a_simple_field": "hello", "a_renamed_field": "world", "a_datetime_field": datetime.datetime(2019, 3, 28, 23, 58, 0), "a_date_field": datetime.date(2019, 3, 29), } my_entity = SimpleEntity(**entity_fields) entity_fields.update({ "a_datetime_field": "2019-03-28T23:58:00Z", "a_date_field": "2019-03-29", }) self.assertEqual(my_entity.to_api(), entity_fields)
class TestEntity(BaseCase): def test_to_api(self): pass
2
0
13
0
13
0
1
0
1
3
1
0
1
0
1
73
15
1
14
4
12
0
6
4
4
1
3
0
1
2,191
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/tests/unit/test_pagination.py
tests.unit.test_pagination.D
class D: """A data object""" def __init__(self, id): self.id = id def __eq__(self, other): return self.id == other.id def __hash__(self): return self.id def __str__(self): return 'D<%s>' % self.id def __repr__(self): return str(self)
class D: '''A data object''' def __init__(self, id): pass def __eq__(self, other): pass def __hash__(self): pass def __str__(self): pass def __repr__(self): pass
6
1
2
0
2
0
1
0.09
0
1
0
0
5
1
5
5
16
4
11
7
5
1
11
7
5
1
0
0
5
2,192
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/src/mbed_cloud/foundation/entities/branding/enums.py
mbed_cloud.foundation.entities.branding.enums.DarkThemeImageReferenceEnum
class DarkThemeImageReferenceEnum(BaseEnum): """Represents expected values of `DarkThemeImageReferenceEnum` This is used by Entities in the "branding" category. .. note:: If new values are added to the enum in the API they will be passed through unchanged by the SDK, but will not be on this list. If this occurs please update the SDK to the most recent version. """ BRAND_LOGO_EMAIL = "brand_logo_email" BRAND_LOGO_LANDSCAPE = "brand_logo_landscape" BRAND_LOGO_PORTRAIT = "brand_logo_portrait" BRAND_LOGO_SQUARE = "brand_logo_square" CAROUSEL_IMAGE_LANDSCAPE_0 = "carousel_image_landscape_0" CAROUSEL_IMAGE_LANDSCAPE_1 = "carousel_image_landscape_1" CAROUSEL_IMAGE_LANDSCAPE_2 = "carousel_image_landscape_2" CAROUSEL_IMAGE_LANDSCAPE_3 = "carousel_image_landscape_3" CAROUSEL_IMAGE_LANDSCAPE_4 = "carousel_image_landscape_4" CAROUSEL_IMAGE_LANDSCAPE_5 = "carousel_image_landscape_5" CAROUSEL_IMAGE_LANDSCAPE_6 = "carousel_image_landscape_6" CAROUSEL_IMAGE_LANDSCAPE_7 = "carousel_image_landscape_7" CAROUSEL_IMAGE_LANDSCAPE_8 = "carousel_image_landscape_8" CAROUSEL_IMAGE_LANDSCAPE_9 = "carousel_image_landscape_9" CAROUSEL_IMAGE_PORTRAIT_0 = "carousel_image_portrait_0" CAROUSEL_IMAGE_PORTRAIT_1 = "carousel_image_portrait_1" CAROUSEL_IMAGE_PORTRAIT_2 = "carousel_image_portrait_2" CAROUSEL_IMAGE_PORTRAIT_3 = "carousel_image_portrait_3" CAROUSEL_IMAGE_PORTRAIT_4 = "carousel_image_portrait_4" CAROUSEL_IMAGE_PORTRAIT_5 = "carousel_image_portrait_5" CAROUSEL_IMAGE_PORTRAIT_6 = "carousel_image_portrait_6" CAROUSEL_IMAGE_PORTRAIT_7 = "carousel_image_portrait_7" CAROUSEL_IMAGE_PORTRAIT_8 = "carousel_image_portrait_8" CAROUSEL_IMAGE_PORTRAIT_9 = "carousel_image_portrait_9" CAROUSEL_IMAGE_SQUARE_0 = "carousel_image_square_0" CAROUSEL_IMAGE_SQUARE_1 = "carousel_image_square_1" CAROUSEL_IMAGE_SQUARE_2 = "carousel_image_square_2" CAROUSEL_IMAGE_SQUARE_3 = "carousel_image_square_3" CAROUSEL_IMAGE_SQUARE_4 = "carousel_image_square_4" CAROUSEL_IMAGE_SQUARE_5 = "carousel_image_square_5" CAROUSEL_IMAGE_SQUARE_6 = "carousel_image_square_6" CAROUSEL_IMAGE_SQUARE_7 = "carousel_image_square_7" CAROUSEL_IMAGE_SQUARE_8 = "carousel_image_square_8" CAROUSEL_IMAGE_SQUARE_9 = "carousel_image_square_9" DESKTOP_BACKGROUND_LANDSCAPE = "desktop_background_landscape" DESKTOP_BACKGROUND_PORTRAIT = "desktop_background_portrait" DESKTOP_BACKGROUND_SQUARE = "desktop_background_square" values = frozenset( ( "brand_logo_email", "brand_logo_landscape", "brand_logo_portrait", "brand_logo_square", "carousel_image_landscape_0", "carousel_image_landscape_1", "carousel_image_landscape_2", "carousel_image_landscape_3", "carousel_image_landscape_4", "carousel_image_landscape_5", "carousel_image_landscape_6", "carousel_image_landscape_7", "carousel_image_landscape_8", "carousel_image_landscape_9", "carousel_image_portrait_0", "carousel_image_portrait_1", "carousel_image_portrait_2", "carousel_image_portrait_3", "carousel_image_portrait_4", "carousel_image_portrait_5", "carousel_image_portrait_6", "carousel_image_portrait_7", "carousel_image_portrait_8", "carousel_image_portrait_9", "carousel_image_square_0", "carousel_image_square_1", "carousel_image_square_2", "carousel_image_square_3", "carousel_image_square_4", "carousel_image_square_5", "carousel_image_square_6", "carousel_image_square_7", "carousel_image_square_8", "carousel_image_square_9", "desktop_background_landscape", "desktop_background_portrait", "desktop_background_square", ) )
class DarkThemeImageReferenceEnum(BaseEnum): '''Represents expected values of `DarkThemeImageReferenceEnum` This is used by Entities in the "branding" category. .. note:: If new values are added to the enum in the API they will be passed through unchanged by the SDK, but will not be on this list. If this occurs please update the SDK to the most recent version. '''
1
1
0
0
0
0
0
0.08
1
0
0
0
0
0
0
1
89
4
79
39
78
6
39
39
38
0
2
0
0
2,193
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/tests/unit/asynchronous/test_subscribers.py
tests.unit.asynchronous.test_subscribers.TestGetResourceValue
class TestGetResourceValue(BaseCase): def setUp(self): """Mock the HTTP request method so that the long poll does not received anything.""" self.patch = mock.patch('urllib3.PoolManager.request') mocked = self.patch.start() mocked.return_value.data = b'' mocked.return_value.status = 200 self.api = ConnectAPI(dict(autostart_notification_thread=False)) def tearDown(self): self.patch.stop() def test_async_wait(self): """Test a all registration notifications in a single message""" async_result = self.api.get_resource_value_async("abc123", "/3/0/0") example_data = { "async-responses": [{ "ct": "text/plain", "payload": "My4zMQ==", "max-age": "60", "id": async_result.async_id, "error": None, "status": 202 }], } self.api.notify_webhook_received(payload=json.dumps(example_data)) self.assertEqual('3.31', async_result.wait()) def test_async_wait_error(self): """Test a all registration notifications in a single message""" async_result = self.api.get_resource_value_async("abc123", "/3/0/0") example_data = { "async-responses": [{ "ct": "text/plain", "payload": "My4zMQ==", "max-age": "60", "id": async_result.async_id, "error": "TIMEOUT", "status": 504 }], } self.api.notify_webhook_received(payload=json.dumps(example_data)) # An Async response with an error should raise an exception with self.assertRaises(CloudAsyncError) as e: async_result.wait() self.assertTrue(str(e.exception).startswith("(504) 'TIMEOUT' Async response for")) self.assertEqual("TIMEOUT", e.exception.reason) self.assertEqual(504, e.exception.status) def test_async_value_error(self): """Test a all registration notifications in a single message""" async_result = self.api.get_resource_value_async("abc123", "/3/0/0") example_data = { "async-responses": [{ "ct": "text/plain", "payload": None, "max-age": "60", "id": async_result.async_id, "error": "AN ERROR", "status": 499 }], } self.api.notify_webhook_received(payload=json.dumps(example_data)) # Attempted to get the value when there is an error and no payload should raise an exception with self.assertRaises(CloudUnhandledError) as e: async_result.value self.assertEqual("(499) 'AN ERROR' Attempted to decode async request which returned an error.", str(e.exception)) self.assertEqual("AN ERROR", e.exception.reason) self.assertEqual(499, e.exception.status)
class TestGetResourceValue(BaseCase): def setUp(self): '''Mock the HTTP request method so that the long poll does not received anything.''' pass def tearDown(self): pass def test_async_wait(self): '''Test a all registration notifications in a single message''' pass def test_async_wait_error(self): '''Test a all registration notifications in a single message''' pass def test_async_value_error(self): '''Test a all registration notifications in a single message''' pass
6
4
15
2
12
1
1
0.1
1
5
3
0
5
2
5
77
81
15
60
17
54
6
32
15
26
1
3
1
5
2,194
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/tests/unit/client/test_client.py
tests.unit.client.test_client.TestClient
class TestClient(BaseCase): """Test creation of API filters.""" @classmethod def setUpClass(cls): cls.client = SDK().client def setUp(self): httpretty.register_uri( httpretty.GET, self.client.config.host + MOCK_PATH, body='{"origin": "127.0.0.1"}' ) def test_standard_headers(self): self.client.call_api("GET", MOCK_PATH, content_type="application/pelion") last_request = httpretty.last_request() self.assertEqual("Bearer " + self.client.config.api_key, last_request.headers["Authorization"]) self.assertIn("mbed-cloud-sdk-python", last_request.headers["User-Agent"]) self.assertEqual("application/pelion", last_request.headers["Content-Type"]) def test_path_params(self): self.client.call_api("GET", "/foo/{variable}", path_params={"variable": "bar"}) last_request = httpretty.last_request() self.assertEqual(last_request.path, MOCK_PATH) def test_json_message(self): self.client.call_api("GET", MOCK_PATH, body_params={"badger": "gopher"}) last_request = httpretty.last_request() self.assertEqual(last_request.body, six.b('{"badger": "gopher"}')) self.assertEqual("application/json", last_request.headers["Content-Type"]) def test_binary_message(self): binary_data = six.b('Badger Gopher Squirrel Ferret') self.client.call_api("GET", MOCK_PATH, binary_data=binary_data) last_request = httpretty.last_request() self.assertEqual(last_request.body, binary_data) self.assertEqual("application/octet-stream", last_request.headers["Content-Type"]) def test_multipart_message(self): file_stream = six.StringIO("Badger Gopher Squirrel Ferret") self.client.call_api("GET", MOCK_PATH, stream_params={"datafile": file_stream}) last_request = httpretty.last_request() self.assertIn("Badger Gopher Squirrel Ferret", last_request.parsed_body) self.assertIn("multipart/form-data", last_request.headers["Content-Type"])
class TestClient(BaseCase): '''Test creation of API filters.''' @classmethod def setUpClass(cls): pass def setUpClass(cls): pass def test_standard_headers(self): pass def test_path_params(self): pass def test_json_message(self): pass def test_binary_message(self): pass def test_multipart_message(self): pass
9
1
6
1
5
0
1
0.03
1
0
0
0
6
0
7
79
50
12
37
16
28
1
32
15
24
1
3
0
7
2,195
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/tests/unit/foundation/test_api_filter.py
tests.unit.foundation.test_api_filter.TestApiFilter
class TestApiFilter(BaseCase): """Test creation of API filters.""" def test_string_type(self): filter_definition = {"name": {"eq": "Badger"}} expected_filter = {"name__eq": "Badger"} expected_query_string = "name__eq=Badger" api_filter = ApiFilter(filter_definition) self.assertEqual(expected_filter, api_filter.to_api()) self.assertEqual(expected_query_string, api_filter.to_query_string()) def test_integer_type(self): filter_definition = {"name": {"neq": -50}} expected_filter = {"name__neq": -50} api_filter = ApiFilter(filter_definition) self.assertEqual(expected_filter, api_filter.to_api()) def test_float_type(self): filter_definition = {"name": {"gte": -1.7}} expected_filter = {"name__gte": -1.7} api_filter = ApiFilter(filter_definition) self.assertEqual(expected_filter, api_filter.to_api()) def test_boolean_type(self): filter_definition = {"name": {"like": True}} expected_filter = {"name__like": "true"} api_filter = ApiFilter(filter_definition) self.assertEqual(expected_filter, api_filter.to_api()) def test_datetime_type(self): filter_definition = {"name": {"eq": datetime(2019, 3, 7, 13, 33, 47)}} expected_filter = {"name__eq": "2019-03-07T13:33:47Z"} api_filter = ApiFilter(filter_definition) self.assertEqual(expected_filter, api_filter.to_api()) def test_date_type(self): filter_definition = {"name": {"eq": date(2019, 3, 7)}} expected_filter = {"name__eq": "2019-03-07"} api_filter = ApiFilter(filter_definition) self.assertEqual(expected_filter, api_filter.to_api()) def test_list_type(self): filter_definition = {"name": {"in": ["Badger", "Gopher"]}} expected_filter = {"name__in": "Badger,Gopher"} expected_query_string = "name__in=Badger,Gopher" api_filter = ApiFilter(filter_definition) self.assertEqual(expected_filter, api_filter.to_api()) self.assertEqual(expected_query_string, api_filter.to_query_string()) def test_dict_type(self): filter_definition = {"name": {"nin": {"Animal": "Badger"}}} expected_filter = {"name__nin": '{"Animal": "Badger"}'} api_filter = ApiFilter(filter_definition) self.assertEqual(expected_filter, api_filter.to_api()) def test_none(self): filter_definition = {"name": {"eq": None}} expected_filter = {"name__eq": "null"} api_filter = ApiFilter(filter_definition) self.assertEqual(expected_filter, api_filter.to_api()) def test_entity(self): my_user = User(id="my_user_id") filter_definition = {"sub_entity": {"eq": my_user}} expected_filter = {"sub_entity__eq": "my_user_id"} api_filter = ApiFilter(filter_definition) self.assertEqual(expected_filter, api_filter.to_api()) def test_missing_operator(self): filter_definition = {"name": date(2019, 3, 7)} expected_filter = {"name__eq": "2019-03-07"} api_filter = ApiFilter(filter_definition) self.assertEqual(expected_filter, api_filter.to_api()) def test_rename(self): filter_definition = {"SDK_name": {"eq": "Badger"}} renames = {"SDK_name": "API_name"} expected_filter = {"API_name__eq": "Badger"} api_filter = ApiFilter(filter_definition, renames) self.assertEqual(expected_filter, api_filter.to_api()) def test_add_filter(self): api_filter = ApiFilter() self.assertEqual({}, api_filter.to_api()) api_filter.add_filter("created_at", "gte", datetime(2019, 1, 1)) expected_filter = {"created_at__gte": "2019-01-01T00:00:00Z"} self.assertEqual(expected_filter, api_filter.to_api()) api_filter.add_filter("created_at", "lte", date(2019, 12, 31)) expected_filter = {"created_at__gte": "2019-01-01T00:00:00Z", "created_at__lte": "2019-12-31"} self.assertEqual(expected_filter, api_filter.to_api()) api_filter.add_filter("status", "eq", True) expected_filter = { "created_at__gte": "2019-01-01T00:00:00Z", "created_at__lte": "2019-12-31", "status__eq": "true" } expected_query_string = "created_at__gte=2019-01-01T00:00:00Z&created_at__lte=2019-12-31&status__eq=true" self.assertEqual(expected_filter, api_filter.to_api()) self.assertEqual(expected_query_string, api_filter.to_query_string()) def test_single_list_filter(self): filter_definition = {"name": {"in": ["Gopher"]}} expected_filter = {"name__in": "Gopher"} api_filter = ApiFilter(filter_definition) self.assertEqual(expected_filter, api_filter.to_api()) def test_compound_list_filter(self): filter_definition = {"name": {"in": ["Badger", 17, 20.5, True, date(2019, 12, 31), datetime(2019, 1, 1), None]}} expected_filter = {"name__in": "Badger,17,20.5,true,2019-12-31,2019-01-01T00:00:00Z,null"} api_filter = ApiFilter(filter_definition) self.assertEqual(expected_filter, api_filter.to_api()) def test_nested_list_filter(self): filter_definition = {"name": {"in": ["Badger", [17, 20.5], True, datetime(2019, 1, 1), None]}} expected_filter = {"name__in": "Badger,17,20.5,true,2019-01-01T00:00:00Z,null"} api_filter = ApiFilter(filter_definition) self.assertEqual(expected_filter, api_filter.to_api()) def test_list_of_entities_filter(self): user_one = User(id="user1") user_two = User(id="user2") filter_definition = {"sub_entity": {"in": [user_one, user_two]}} expected_filter = {"sub_entity__in": "user1,user2"} api_filter = ApiFilter(filter_definition) self.assertEqual(expected_filter, api_filter.to_api()) def test_compound_filter(self): filter_definition = { "created_at": { "gte": datetime(2019, 1, 1), "lte": date(2019, 12, 31), }, "colour": {"like": "purple"}, "integer": {"neq": 42}, "float": {"neq": 13.98}, "state": {"in": ["OPEN", "CLOSED"]}, "city": {"nin": ["Cambridge", "London"]}, "strange": {"eq": {"hello": "world"}}, "done": False, "firmware_checksum": None, } renames = { "colour": "API_colour", "state": "API_state", "strange": "API_strange", "firmware_checksum": "API_fw_csum", } expected_filter = { "created_at__gte": "2019-01-01T00:00:00Z", "created_at__lte": "2019-12-31", "API_colour__like": "purple", "integer__neq": 42, "float__neq": 13.98, "API_state__in": "OPEN,CLOSED", "city__nin": "Cambridge,London", "API_strange__eq": '{"hello": "world"}', "done__eq": "false", "API_fw_csum__eq": "null"} api_filter = ApiFilter(filter_definition, renames) self.assertEqual(expected_filter, api_filter.to_api()) def test_legacy_filter(self): filter_definition = { "created_at": { "$gte": datetime(2019, 1, 1), "$lte": date(2019, 12, 31), }, "colour": {"$like": "purple"}, "integer": {"$neq": 42}, "float": {"$neq": 13.98}, "state": {"$in": ["OPEN", "CLOSED"]}, "city": {"$nin": ["Cambridge", "London"]}, "strange": {"$eq": {"hello": "world"}}, "done": False, "firmware_checksum": None, } renames = { "colour": "API_colour", "state": "API_state", "strange": "API_strange", "firmware_checksum": "API_fw_csum", } expected_filter = { "created_at__gte": "2019-01-01T00:00:00Z", "created_at__lte": "2019-12-31", "API_colour__like": "purple", "integer__neq": 42, "float__neq": 13.98, "API_state__in": "OPEN,CLOSED", "city__nin": "Cambridge,London", "API_strange__eq": '{"hello": "world"}', "done__eq": "false", "API_fw_csum__eq": "null"} api_filter = ApiFilter(filter_definition, renames) self.assertEqual(expected_filter, api_filter.to_api())
class TestApiFilter(BaseCase): '''Test creation of API filters.''' def test_string_type(self): pass def test_integer_type(self): pass def test_float_type(self): pass def test_boolean_type(self): pass def test_datetime_type(self): pass def test_date_type(self): pass def test_list_type(self): pass def test_dict_type(self): pass def test_none(self): pass def test_entity(self): pass def test_missing_operator(self): pass def test_rename(self): pass def test_add_filter(self): pass def test_single_list_filter(self): pass def test_compound_list_filter(self): pass def test_nested_list_filter(self): pass def test_list_of_entities_filter(self): pass def test_compound_filter(self): pass def test_legacy_filter(self): pass
20
1
10
1
9
0
1
0.01
1
4
2
0
19
0
19
91
218
42
175
85
155
1
115
85
95
1
3
0
19
2,196
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/tests/unit/foundation/test_device_update.py
tests.unit.foundation.test_device_update.TestFirmwareImage
class TestFirmwareImage(BaseCase): """Test creation of firware imamge request.""" @classmethod def setUpClass(cls): cls.sdk = SDK() def setUp(self): httpretty.register_uri( httpretty.POST, self.sdk.config.host + "/v3/firmware-images/", body='{"origin": "127.0.0.1"}' ) def test_image_upload(self): """Example of renewing a certificate on a device.""" file = io.BytesIO(six.b("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F")) image = self.sdk.foundation.firmware_image(description="Test Description", name="Test Name") image.create(firmware_image_file=file) last_request = httpretty.last_request() # The content type needs to set as multipart and define the boundary self.assertIn("multipart/form-data; boundary=", last_request.headers["Content-Type"]) # The message needs to have three sections self.assertIn( 'Content-Disposition: form-data; name="description"\r\nContent-Type: text/plain\r\n\r\nTest Description', last_request.parsed_body) self.assertIn( 'Content-Disposition: form-data; name="name"\r\nContent-Type: text/plain\r\n\r\nTest Name', last_request.parsed_body) self.assertIn( 'Content-Disposition: form-data; name="datafile"; filename="firmware_image_file.bin"\r\n' 'Content-Type: application/octet-stream', last_request.parsed_body)
class TestFirmwareImage(BaseCase): '''Test creation of firware imamge request.''' @classmethod def setUpClass(cls): pass def setUpClass(cls): pass def test_image_upload(self): '''Example of renewing a certificate on a device.''' pass
5
2
10
1
8
1
1
0.15
1
0
0
0
2
0
3
75
37
7
26
8
21
4
14
7
10
1
3
0
3
2,197
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/tests/unit/foundation/test_entity.py
tests.unit.foundation.test_entity.SimpleEntity
class SimpleEntity(Entity): """Represents the `User` entity in Pelion Device Management""" # List of fields that are serialised between the API and SDK _api_fieldnames = [ "a_simple_field", "a_renamed_field", "a_datetime_field", "a_date_field", ] # List of fields that are available for the user of the SDK _sdk_fieldnames = _api_fieldnames # Renames to be performed by the SDK when receiving data {<API Field Name>: <SDK Field Name>} _renames = { "badly_named_field": "a_renamed_field", } # Renames to be performed by the SDK when sending data {<SDK Field Name>: <API Field Name>} _renames_to_api = {} def __init__( self, _client=None, a_simple_field=None, a_renamed_field=None, a_datetime_field=None, a_date_field=None, ): super(SimpleEntity, self).__init__(_client=_client) # inline imports for avoiding circular references and bulk imports # fields self._a_simple_field = fields.StringField(value=a_simple_field) self._a_renamed_field = fields.StringField(value=a_renamed_field) self._a_datetime_field = fields.DateTimeField(value=a_datetime_field) self._a_date_field = fields.DateField(value=a_date_field) @property def a_simple_field(self): return self._a_simple_field.value @a_simple_field.setter def a_simple_field(self, value): self._a_simple_field.set(value) @property def a_renamed_field(self): return self._a_renamed_field.value @a_renamed_field.setter def a_renamed_field(self, value): self._a_renamed_field.set(value) @property def a_datetime_field(self): return self._a_datetime_field.value @a_datetime_field.setter def a_datetime_field(self, value): self._a_datetime_field.set(value) @property def a_date_field(self): return self._a_date_field.value @a_date_field.setter def a_date_field(self, value): self._a_date_field.set(value)
class SimpleEntity(Entity): '''Represents the `User` entity in Pelion Device Management''' def __init__( self, _client=None, a_simple_field=None, a_renamed_field=None, a_datetime_field=None, a_date_field=None, ): pass @property def a_simple_field(self): pass @a_simple_field.setter def a_simple_field(self): pass @property def a_renamed_field(self): pass @a_renamed_field.setter def a_renamed_field(self): pass @property def a_datetime_field(self): pass @a_datetime_field.setter def a_datetime_field(self): pass @property def a_date_field(self): pass @a_date_field.setter def a_date_field(self): pass
18
1
4
0
3
0
1
0.14
1
4
3
0
9
4
9
20
71
15
49
33
24
7
27
18
17
1
2
0
9
2,198
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/tests/unit/foundation/test_fields.py
tests.unit.foundation.test_fields.TZ
class TZ(datetime.tzinfo): def utcoffset(self, dt): return datetime.timedelta(minutes=-120)
class TZ(datetime.tzinfo): def utcoffset(self, dt): pass
2
0
2
0
2
0
1
0
1
1
0
0
1
0
1
6
3
0
3
2
1
0
3
2
1
1
1
0
1
2,199
ARMmbed/mbed-cloud-sdk-python
ARMmbed_mbed-cloud-sdk-python/tests/unit/foundation/test_fields.py
tests.unit.foundation.test_fields.TestDateField
class TestDateField(BaseCase): def test_date_object(self): field = fields.DateField(value=datetime.date(2019, 3, 29)) self.assertEqual(field.to_api(), "2019-03-29") self.assertEqual(field.to_literal(), "2019-03-29") def test_datetime_string(self): field = fields.DateField(value="2019-03-28T23:58:00") self.assertEqual(field.to_api(), "2019-03-28") self.assertEqual(field.to_literal(), "2019-03-28") def test_date_string(self): field = fields.DateField(value="2019-03-29") self.assertEqual(field.to_api(), "2019-03-29") self.assertEqual(field.to_literal(), "2019-03-29")
class TestDateField(BaseCase): def test_date_object(self): pass def test_datetime_string(self): pass def test_date_string(self): pass
4
0
4
0
4
0
1
0
1
2
1
0
3
0
3
75
16
3
13
7
9
0
13
7
9
1
3
0
3