def test_add_existing(session):
    add("invenio/kwalitee")
    add("invenio/kwalitee")
    assert_that(Account.query.filter_by(name="invenio").count(),
                equal_to(1))
    assert_that(Repository.query.filter_by(name="kwalitee").count(),
                equal_to(1))
    def test_find_virtual_disk(self):
        spec = vim.vm.ConfigSpec()
        vm_config = self.vm_config
        devices = self.dummy_devices()
        for device in devices:
            vm_config.add_device(spec, device)
        cfg_info = FakeConfigInfo()
        device_type = vim.vm.device.VirtualDisk
        datastore = "ds1"
        filename = "folder/foo"
        path = vmdk_path(datastore, filename)

        find_disk = vm_config.disk_matcher(datastore, filename)
        disk = vm_config.find_device(devices, device_type, matcher=find_disk)
        assert_that(disk, equal_to(None))

        vm_config.add_scsi_disk(cfg_info, spec, datastore, "nope")

        self.assertRaises(DeviceNotFoundException, vm_config.get_device,
                          devices, device_type, matcher=find_disk)

        vm_config.add_scsi_disk(cfg_info, spec, datastore,
                                filename)
        device_changes = spec.deviceChange
        device_list = []
        for device_change in device_changes:
            device_list.append(device_change.device)

        disk = vm_config.find_device(device_list, device_type,
                                     matcher=find_disk)
        assert_that(disk.backing.fileName, equal_to(path))
def _check_func_key(info, line_number):
    line = user_action_webi.find_func_key_line(line_number)

    key_num = info['Key']
    key_type = info['Type']
    key_label = info['Label']
    key_destination = info['Destination']
    key_supervision = info['Supervision']

    key_num_field = user_action_webi.find_key_number_field(line)
    value = _extract_dropdown_value(key_num_field)
    assert_that(value, equal_to(key_num), "func key num differs (%s instead of %s)" % (value, key_num))

    key_type_field = user_action_webi.find_key_type_field(line)
    value = _extract_dropdown_value(key_type_field)
    assert_that(value, equal_to(key_type), "func key type differs (%s instead of %s)" % (value, key_type))

    destination_value = _extract_destination_value(key_type, line)
    assert_that(destination_value, equal_to(key_destination), "func key destination differs (%s instead of %s)" % (value, key_destination))

    key_label_field = user_action_webi.find_key_label_field(line)
    value = key_label_field.get_attribute('value')
    assert_that(value, equal_to(key_label), "func key label differs (%s instead of %s)" % (value, key_label))

    key_supervision_field = user_action_webi.find_key_supervision_field(line)
    value = _extract_dropdown_value(key_supervision_field)
    assert_that(value, equal_to(key_supervision), "func key supervision differs (%s instead of %s)" % (value, key_supervision))
Example #4
0
    def test_parse_observation_rawnames(self):
        astrom_data = self.parse(TEST_FILE_1)

        assert_that(astrom_data.observations, has_length(3))
        assert_that(astrom_data.observations[0].rawname, equal_to("1584431p15"))
        assert_that(astrom_data.observations[1].rawname, equal_to("1584449p15"))
        assert_that(astrom_data.observations[2].rawname, equal_to("1584453p15"))
    def test_basic_parsing(self, tftp_reader_mock):
        tftp_reader_mock.return_value = """
!
vlan 1000
name VLAN_1_0_0_0
!
!
vlan 2000
name VLAN_2_0_0_0
!
"""
        config = SwitchConfiguration("127.0.0.1", name="my_switch", ports=[
            Port("GigabitEthernet0/1")
        ])

        parser = SwitchTftpParser(config)

        parser.parse("hostname", "filename", ConfigCommandProcessor)

        tftp_reader_mock.assert_called_with("hostname", "filename")

        vlan1000 = config.get_vlan(1000)
        assert_that(vlan1000.name, equal_to("VLAN_1_0_0_0"))

        vlan2000 = config.get_vlan(2000)
        assert_that(vlan2000.name, equal_to("VLAN_2_0_0_0"))
 def test_delete_files(self, api_client, datasets_api, dataset_key):
     files = ['filename.ext']
     api_client.delete_files(dataset_key, files)
     assert_that(datasets_api.delete_files_and_sync_sources,
                 called().times(1).with_args(equal_to('agentid'),
                                             equal_to('datasetid'),
                                             equal_to(files)))
 def test_update_dataset(self, api_client, datasets_api, dataset_key):
     patch_request = {'tags': ['tag1', 'tag2']}
     api_client.update_dataset(dataset_key, **patch_request)
     assert_that(datasets_api.patch_dataset,
                 called().times(1).with_args(equal_to('agentid'),
                                             equal_to('datasetid'),
                                             has_properties(patch_request)))
Example #8
0
def Diagnostics_FixIt_Available_test(app):
    contents = ReadFile(PathToTestFile("FixIt_Clang_cpp11.cpp"))

    event_data = BuildRequest(
        contents=contents,
        event_name="FileReadyToParse",
        filetype="cpp",
        compilation_flags=["-x", "c++", "-std=c++03", "-Wall", "-Wextra", "-pedantic"],
    )

    response = app.post_json("/event_notification", event_data).json

    pprint(response)

    assert_that(
        response,
        has_items(
            has_entries(
                {
                    "location": has_entries({"line_num": 16, "column_num": 3}),
                    "text": equal_to("switch condition type 'A' " "requires explicit conversion to 'int'"),
                    "fixit_available": True,
                }
            ),
            has_entries(
                {
                    "location": has_entries({"line_num": 11, "column_num": 3}),
                    "text": equal_to("explicit conversion functions are a C++11 extension"),
                    "fixit_available": False,
                }
            ),
        ),
    )
 def test_upload_files(self, api_client, uploads_api, dataset_key):
     files = ['filename.ext']
     api_client.upload_files(dataset_key, files)
     assert_that(uploads_api.upload_files,
                 called().times(1).with_args(equal_to('agentid'),
                                             equal_to('datasetid'),
                                             equal_to(files)))
Example #10
0
 def test_get_interfaces(self):
     dm = VNXVdm(name='VDM_ESA', cli=t_nas())
     ifs = dm.get_interfaces()
     assert_that(len(ifs), equal_to(1))
     interface = ifs[0]
     assert_that(interface.name, equal_to('10-110-24-195'))
     assert_that(interface.share_type, equal_to(VNXShareType.NFS))
def test_known_pull_request_task(app, owner, repository, session):
    """Task pull_request /pulls/1 that already exists."""
    httpretty.reset()
    cs1 = CommitStatus(repository,
                       "1",
                       "https://github.com/pulls/1",
                       {"message": [], "files": {}})
    cs2 = CommitStatus(repository,
                       "2",
                       "https://github.com/pulls/2",
                       {"message": [], "files": {}})
    session.add(cs1)
    session.add(cs2)
    session.commit()

    bs = BranchStatus(cs2,
                      "test:my-branch",
                      "https://github.com/pulls/1",
                      {"commits": [cs1, cs2], "files": {}})
    session.add(bs)
    session.commit()
    assert_that(bs.is_pending(), equal_to(False))

    httpretty.enable()
    pull_request(bs.id,
                 "https://api.github.com/pulls/1",
                 "http://kwalitee.invenio-software.org/status/2",
                 {"ACCESS_TOKEN": "deadbeef"})
    httpretty.disable()

    latest_requests = httpretty.HTTPretty.latest_requests
    assert_that(len(latest_requests), equal_to(0),
                "No requests are expected")
def task_finishes_with_status(context, status):
    """Wait for task finished: status != syncing"""

    i = 0
    task_status = None
    while i < MAX_WAIT_TASK_FINISHED:
        body, response = \
            context.glancesync_api_client.get_task_api_client(context.region_name).get_task_details(context.task_id)

        assert_that(str(response.status_code), is_(equal_to("200")),
                    "HTTP Status code is for TASK request not the expected one.")

        assert_that(body, has_key('status'),
                    "The response of TASK request does not contain the expected attribute.")

        task_status = body['status']
        if task_status != "syncing":
            break

        __logger__.info("#%s Waiting for TASK final status. Status: %s", i, status)
        time.sleep(WAIT_SECONDS)
        i += 1

    assert_that(task_status, is_(equal_to(status)),
                "The task has not been successfully executed.")
 def test_char_diffs_counted(self):
     assert_that(self.calculator.calculate_distance("ABC", "ABB"),
                 equal_to(1))
     assert_that(self.calculator.calculate_distance("ABC", "AED"),
                 equal_to(2))
     assert_that(self.calculator.calculate_distance("ABC", "FED"),
                 equal_to(3))
Example #14
0
    def test_executes_actions_during_deadline_extension(self):
        # given
        self.PriorityQueue().empty.return_value = False
        self.PriorityQueue().queue = []
        end_time = 20
        observation_time, executed_first_pass = 0, [Mock(end_time=end_time-1)]
        observation_whilst_planning = 10
        executed_second_pass = [Mock(end_time=end_time)]
        self.execute_action_queue.side_effect = [
            (ExecutionResult(executed_first_pass, {observation_time}, observation_time), {}),
            (ExecutionResult(executed_second_pass, {observation_whilst_planning}, observation_whilst_planning), {})
        ]
        self.execute_partial_actions.return_value = []
        model = Mock(name="model")
        execution_extension = 100
        plan = executed_first_pass + executed_second_pass

        # when
        actual = simulator.run_plan(model, plan, Mock(name="sim_time"), execution_extension)

        # then
        assert_that(self.execute_action_queue.call_count, is_(2))
        self.execute_action_queue.assert_has_calls([
            call.execute_action_queue(model, self.PriorityQueue(), break_on_new_knowledge=True,
                deadline=Decimal("infinity")),
            call.execute_action_queue(model, self.PriorityQueue(), break_on_new_knowledge=False,
                deadline=observation_time+execution_extension, stalled={})
        ])
        assert_that(actual.executed, equal_to(plan))
        assert_that(actual.observations, contains(observation_time, observation_whilst_planning))
        assert_that(actual.simulation_time, equal_to(end_time))
    def test_status_endpoint_returns_ok(self, get_patch):
        get_patch.return_value = okay_response()

        response = self.app.get("/_status")
        assert_that(response.status_code, equal_to(200))
        assert_that(json.loads(response.data)['status'],
                    equal_to('ok'))
Example #16
0
    def test_put(self):
        collector = CollectorFactory()

        data_source = DataSourceFactory(provider=collector.type.provider)

        collector_update = {
            "slug": collector.slug,
            "type_id": collector.type.id,
            "data_source_id": data_source.id,
            "data_set": {
                "data_type": collector.data_set.data_type.name,
                "data_group": collector.data_set.data_group.name
            }
        }

        response = self.client.put(
            '/collector/{}'.format(collector.slug),
            data=to_json(collector_update),
            HTTP_AUTHORIZATION='Bearer development-oauth-access-token',
            content_type='application/json')

        assert_that(response.status_code, equal_to(200))
        resp_json = json.loads(response.content)
        assert_that(resp_json['data_source']['name'],
                    equal_to(data_source.name))
Example #17
0
    def test_starts_actions_and_adds_back_to_queue(self):
        # given
        start_time = 0
        deadline = 10
        action_to_start = Action(start_time, deadline+1)
        action_to_start.agent = Mock(name="agent")
        action_to_start.is_applicable = Mock(return_val=True)
        action_to_start.apply = Mock(name="apply")
        model = Mock(name="model")
        execution_queue = PriorityQueue()
        execution_queue.put(ActionState(action_to_start, start_time, ExecutionState.pre_start))

        # when
        actual, _stalled = simulator.execute_action_queue(model, execution_queue,
            break_on_new_knowledge=False, deadline=deadline)

        # then
        assert_that(execution_queue.queue, has_length(1))
        time, state, action = execution_queue.queue[0]
        assert_that(time, equal_to(action_to_start.end_time))
        assert_that(state, equal_to(ExecutionState.executing))
        assert_that(action, equal_to(action_to_start))
        assert_that(actual.executed, is_(empty()))
        assert_that(is_not(action_to_start.apply.called))
        assert_that(actual.simulation_time, equal_to(start_time))
 def test_vector_comparison(self):
     testvectors = [
         {
             'x': 1,
             'y': 1
         },
         {
             'x': 0.5,
             'y': 0.5
         },
         {
             'x': 2.3,
             'y': 2.3
         }
     ]
     result = find_shortest_vector(testvectors)
     assert_that(result['x'], equal_to(0.5))
     testvectors = [
         {
             'x': 0,
             'y': 1
         },
         {
             'x': 0,
             'y': 0.5
         },
         {
             'x': 0,
             'y': 2.3
         }
     ]
     result = find_shortest_vector(testvectors)
     assert_that(result['y'], equal_to(0.5))
Example #19
0
    def test_get(self):
        provider = ProviderFactory(
            credentials_schema={
                "$schema": "http://json-schema.org/schema#",
                "type": "object",
                "properties": {
                    "password": {"type": "string"},
                },
                "required": ["password"],
                "additionalProperties": False,
            })
        response = self.client.get(
            '/provider/{}'.format(provider.name),
            HTTP_AUTHORIZATION='Bearer development-oauth-access-token',
            content_type='application/json')

        assert_that(response.status_code, equal_to(200))

        resp_json = json.loads(response.content)

        assert_that(resp_json['id'], equal_to(str(provider.id)))
        assert_that(resp_json['slug'], equal_to(provider.slug))
        assert_that(resp_json['name'], equal_to(provider.name))
        assert_that(resp_json['credentials_schema'], equal_to(
            provider.credentials_schema))
def test_health_check_custom_check():
    """
    Should return Custom health check results.

    """
    loader = load_from_dict(
        health_convention=dict(
            include_build_info="false",
        ),
    )
    graph = create_object_graph(name="example", testing=True, loader=loader)
    graph.use("health_convention")

    client = graph.flask.test_client()

    graph.health_convention.checks["foo"] = lambda graph: "hi"

    response = client.get("/api/health")
    assert_that(response.status_code, is_(equal_to(200)))
    data = loads(response.get_data().decode("utf-8"))
    assert_that(data, is_(equal_to({
        "name": "example",
        "ok": True,
        "checks": {
            "foo": {
                "message": "hi",
                "ok": True,
            },
        },
    })))
def test_health_check_custom_check_failed():
    """
    Should return 503 on health check failure.

    """
    loader = load_from_dict(
        health_convention=dict(
            include_build_info="false",
        ),
    )
    graph = create_object_graph(name="example", testing=True, loader=loader)
    graph.use("health_convention")

    client = graph.flask.test_client()

    def fail(graph):
        raise Exception("failure!")

    graph.health_convention.checks["foo"] = fail

    response = client.get("/api/health")
    assert_that(response.status_code, is_(equal_to(503)))
    data = loads(response.get_data().decode("utf-8"))
    assert_that(data, is_(equal_to({
        "name": "example",
        "ok": False,
        "checks": {
            "foo": {
                "message": "failure!",
                "ok": False,
            },
        },
    })))
Example #22
0
    def test_get_items_without_language(self):
        self.driver.set_dom_element([By.ID, 'table'])
        self.driver.set_dom_element([By.XPATH, './/tr'], parent_id=[By.ID, 'table'], children=4,
                                    return_values=[{'text': 'first'}, {'text': 'second'}, {'text': 'third'},
                                                   {'text': 'fourth'}])
        self.driver.set_expected_command(Command.GET_ELEMENT_TEXT, {'sessionId': self.driver.session_id,
                                                                    'id': self.driver.get_id_for_stored_element(
                                                                        [By.XPATH, './/tr'], 1)})
        self.driver.set_expected_command(Command.GET_ELEMENT_TEXT, {'sessionId': self.driver.session_id,
                                                                    'id': self.driver.get_id_for_stored_element(
                                                                        [By.XPATH, './/tr'], 2)})
        self.driver.set_expected_command(Command.GET_ELEMENT_TEXT, {'sessionId': self.driver.session_id,
                                                                    'id': self.driver.get_id_for_stored_element(
                                                                        [By.XPATH, './/tr'], 3)})
        self.driver.set_expected_command(Command.GET_ELEMENT_TEXT, {'sessionId': self.driver.session_id,
                                                                    'id': self.driver.get_id_for_stored_element(
                                                                        [By.XPATH, './/tr'], 4)})
        #
        items = Table(self.driver, 'table', [By.XPATH, './/tr'], Item, 'item', [By.ID, 'table']).get_items()
        #
        labels = [i.get_text() for i in items]

        assert_that(labels, equal_to(['first', 'second', 'third', 'fourth']),
                    "It should retrieve labels from stored elements")
        assert_that(self.driver.has_fulfilled_expectations(), equal_to(True),
                    "exercising get_items should result in calling Command.GET_ELEMENT_TEXT a number of times.")
Example #23
0
    def test_given_an_extension_then_returns_type_and_typeval(self):
        extension_row = self.add_extension(type='queue', typeval='1234')

        extension_type, typeval = extension_dao.get_type_typeval(extension_row.id)

        assert_that(extension_type, equal_to('queue'))
        assert_that(typeval, equal_to('1234'))
Example #24
0
    def test_loading_images(self):
        observer = Mock()
        events.subscribe(events.IMG_LOADED, observer.on_img_loaded)
        loaded_reading1 = Mock()
        image1 = Mock()
        loaded_reading2 = Mock()
        image2 = Mock()

        assert_that(self.download_manager.start_downloading_workunit.call_count,
                    equal_to(1))
        assert_that(self.model.get_loaded_image_count(), equal_to(0))

        # Simulate receiving callback
        self.model._on_image_loaded(loaded_reading1, image1)
        assert_that(self.model.get_loaded_image_count(), equal_to(1))
        assert_that(observer.on_img_loaded.call_count, equal_to(1))

        # Simulate receiving callback
        self.model._on_image_loaded(loaded_reading2, image2)
        assert_that(self.model.get_loaded_image_count(), equal_to(2))
        assert_that(observer.on_img_loaded.call_count, equal_to(2))

        # Check event args
        call_args_list = observer.on_img_loaded.call_args_list
        assert_that(call_args_list, has_length(2))

        msg0 = call_args_list[0][0][0]
        assert_that(msg0.topic, equal_to(events.IMG_LOADED))
        assert_that(msg0.data, equal_to(loaded_reading1))

        msg1 = call_args_list[1][0][0]
        assert_that(msg1.topic, equal_to(events.IMG_LOADED))
        assert_that(msg1.data, equal_to(loaded_reading2))
Example #25
0
    def test_record_progress_only_after_source_finished(self):
        first_file = self.model.get_current_filename()

        assert_that(self.concurrent_progress_manager.get_processed_indices(first_file),
                    has_length(0))

        self.model.accept_current_item()
        assert_that(self.concurrent_progress_manager.is_done(first_file),
                    equal_to(False))
        assert_that(self.concurrent_progress_manager.get_processed_indices(first_file),
                    has_length(0))

        self.model.next_item()
        self.model.accept_current_item()
        assert_that(self.concurrent_progress_manager.is_done(first_file),
                    equal_to(False))
        assert_that(self.concurrent_progress_manager.get_processed_indices(first_file),
                    has_length(0))

        self.model.next_item()
        self.model.accept_current_item()
        assert_that(self.concurrent_progress_manager.is_done(first_file),
                    equal_to(False))
        assert_that(self.concurrent_progress_manager.get_processed_indices(first_file),
                    contains_inanyorder(0))
Example #26
0
def test_create_delete_file_interface(unity_gf):
    ip = '2.2.2.2'
    fi = unity_gf.nas_server.create_file_interface(
        'spb_eth2', ip, role=FileInterfaceRoleEnum.PRODUCTION)
    assert_that(fi.existed, equal_to(True))
    assert_that(fi.ip_address, equal_to(ip))
    fi.delete()
Example #27
0
 def test_get_properties(self):
     port = UnityIpPort('spa_eth2', cli=t_rest())
     assert_that(port.name, equal_to('SP A Ethernet Port 2'))
     assert_that(port.short_name, equal_to('Ethernet Port 2'))
     assert_that(port.sp, instance_of(UnityStorageProcessor))
     assert_that(port.is_link_up, equal_to(True))
     assert_that(port.mac_address, equal_to('00:60:16:5C:08:E1'))
Example #28
0
    def test_bent_vertical(self):
        """
        Test that horizontal corridor with bend can be made
        """
        edge_connection = Connection(connection=None,
                                     location=(9, 0),
                                     direction="down",
                                     section=self.section)

        room_connection = Connection(connection=None,
                                     location=(2, 9),
                                     direction="up",
                                     section=self.section)

        add_section_connection(self.section, edge_connection)
        add_room_connection(self.section, (2, 9), "up")

        generator = CorridorGenerator(start_point=edge_connection,
                                      end_point=room_connection,
                                      wall_tile=None,
                                      floor_tile=self.floor_rock)

        generator.generate()

        assert_that(wall_tile(self.level, (9, 0)),
                    is_(equal_to(None)))
        assert_that(wall_tile(self.level, (2, 9)),
                    is_(equal_to(None)))
        assert_that(self.level, is_fully_accessible())
Example #29
0
def ping_to_vtep(bridge_name, port_index, dest_ip,
                 interval=0.5, count=4, retries=1):
    try:
        time.sleep(2)
        sender = BM.get_iface_for_port(bridge_name, port_index)
        f1 = sender.ping_ipv4_addr(dest_ip, interval=interval, count=count)
        wait_on_futures([f1])
        output_stream, exec_id = f1.result()
        exit_status = sender.compute_host.check_exit_status(exec_id,
                                                            output_stream,
                                                            timeout=60)

        assert_that(exit_status, equal_to(0),
                    "Ping to from {0}.{1} to {2} failed.".format(bridge_name,
                                                                 port_index,
                                                                 dest_ip))
    except Exception:
        if retries == 0:
            assert_that(-1, equal_to(0),
                        "Ping to from {0}.{1} to {2} failed.".format(bridge_name,
                                                                     port_index,
                                                                     dest_ip))

        ping_to_vtep(bridge_name, port_index, dest_ip, count, interval,
                     retries - 1)
Example #30
0
    def test_serialize_with_dataset(self):
        module = ModuleFactory(
            slug='a-module',
            type=self.module_type,
            order=1,
            data_set=self.data_set,
            dashboard=self.dashboard_a,
            query_parameters={"foo": "bar"})

        serialization = module.serialize()

        assert_that(serialization['slug'], equal_to('a-module'))
        assert_that(
            serialization['type']['id'],
            equal_to(str(self.module_type.id)))
        assert_that(
            serialization['dashboard']['id'],
            equal_to(str(self.dashboard_a.id)))

        assert_that(
            serialization['query_parameters'],
            has_entry('foo', 'bar'))
        assert_that(
            serialization, has_entry(
                'data_group',
                equal_to(self.data_set.data_group.name)))
        assert_that(
            serialization, has_entry(
                'data_type',
                equal_to(self.data_set.data_type.name)))
Example #31
0
 def assert_has_exact_calls(self, calls, any_order=False):
     self.assert_has_calls(calls, any_order)
     assert_that(self.call_count, equal_to(len(calls)))
 def test_should_find_almost_medium(self):
     assert_that(self.bottles(6, "100000"), equal_to(
         (True, 11, 9)
     ))
 def test_should_find_middle(self):
     assert_that(self.bottles(6, "101010"), equal_to(
         (True, 9, 5)
     ))
 def test_should_find_higher(self):
     assert_that(self.bottles(6, "1" * 6), equal_to(
         (True, 6, 0)
     ))
 def test_should_find_lower(self):
     assert_that(self.bottles(6, "0" * 6), equal_to(
         (True, 10, 10)
     ))
Example #36
0
    def test_successful_add_record_to_database(self):
        # Arrange, act, assert
        user_to_create = {"name": "Bob", "email": "*****@*****.**"}
        db_result = self.store.create(user_to_create)

        assert_that(db_result, equal_to(None), 'assertion error')
Example #37
0
def step_impl(context):
    global GLOBAL_TIMESTAMP
    while not GLOBAL_TIMESTAMP:
        time.sleep(1)
    assert_that(context.msg.header.timestamp, equal_to(GLOBAL_TIMESTAMP))
Example #38
0
def test_adc_irq():
    mcu = 'atmega2560'
    feedmv = 2400  # 2.4 volts

    # The code do one ADC and "sends" the captured value back as 16bit number using the A and B ports
    code = '''
    #include <avr/io.h>

    int main(){
        DDRB =  0xFF;   //A output
        DDRA =  0xFF;   //B output

        //Init ADC
        ADMUX = (1 << MUX1)| (1 << REFS0);// Select MUTEX to ADC2, and VCC reference
        ADCSRB = 0;
        //Set 64 Prescaler division = (125khz @ 8MHZ clock) and enable.
        ADCSRA = (1 << ADEN) |(1 << ADPS2) | (1 << ADPS1) | (0 << ADPS0);
        ADCSRA|= (1 << ADSC); //Start conversion. Single Conversion mode.
        while (ADCSRA & (1 << ADSC)); //Wait for the conv. to finish

        //Use all the bits of the port A and B to "send" the converted value back to the test.
        PORTB = ADCL;
        PORTA = ADCH;

        while(1);
    }
    '''
    avr = _create_avr(mcu, 4000000, code)

    # Called once AVR starts the ADC.
    def adcCallback(irq, newVal):
        # Feed the analog value (in milivolts) to the ADC2.
        irq_t = avr.irq.getadc(utils.ADC_IRQ_ADC2)
        avr_raise_irq(irq_t, feedmv)

    # Wrap further to Mock object to enable recording the number of calls.
    adcCallbackMock = Mock(side_effect=adcCallback)
    avr.irq.adc_register_notify(adcCallbackMock)

    # The result value "sent" back from simulated code. Need to wrap the variable into an array
    # to workaround the "referenced before assignment" errors.
    result = [0]

    # Called each time A or B port is changed
    def portCallback(irq, newVal):
        if irq.name[0] == 'A':
            newVal = newVal << 8
        result[0] += newVal

    portCallbackMock = Mock(side_effect=portCallback)

    for port in ('A', 'B'):
        p = avr.irq.ioport_register_notify(portCallbackMock,
                                           (port, utils.IOPORT_IRQ_PIN_ALL))
        p.get_irq(
        ).name = port  # Rename the IO IRQs to ease the Word recomposition in the callback
        # Force callback even on unchanged port values. Just to always have the same number of callback calls.
        p.get_irq().flags &= ~IRQ_FLAG_FILTERED

    avr.step(10000)

    assert_that(adcCallbackMock.call_count, equal_to(1),
                "Number of ADC trigger_out callback invocations.")

    # The port A and B callback gets triggeret at startup first when they are set to output. Two 0 values are sent.
    # And later when the result value is being send back. Hence 4x.
    assert_that(portCallbackMock.call_count, equal_to(4),
                "Number of IO IRQ callback invocations.")
    expectedAdc = avr.vcc * 1000 * result[
        0] / 1024  # 10 bit ADC. VCC used as vref.
    assert_that(expectedAdc, close_to(feedmv, 10), "ADC result")

    avr.terminate()
Example #39
0
 def test_column_rate_minus_2(self):
     stock = self.get_stock_20day()
     open_r = stock['open_-2_r']
     assert_that(isnan(open_r.ix[20110105]), equal_to(True))
     assert_that(open_r.ix[20110106], close_to(2.49, 0.01))
Example #40
0
    def test_from_dict(self):
        cmd = UnregisterUserStatus.from_dict(self.msg)

        assert_that(cmd.user_ids,
                    contains(('xivo_uuid', 42), ('other_uuid', 12)))
        assert_that(cmd.commandid, equal_to(self.commandid))
Example #41
0
 def test_column_delta(self):
     stock = self.get_stock_20day()
     open_d = stock['open_-1_d']
     assert_that(isnan(open_d.ix[20110104]), equal_to(True))
     assert_that(open_d.ix[20110120], close_to(0.07, 0.0001))
Example #42
0
 def test_column_rate_plus2(self):
     stock = self.get_stock_20day()
     open_r = stock['open_2_r']
     assert_that(open_r.ix[20110118], close_to(-1.566, 0.001))
     assert_that(isnan(open_r.ix[20110119]), equal_to(True))
     assert_that(isnan(open_r.ix[20110120]), equal_to(True))
Example #43
0
 def test_delta(self):
     stock = self.get_stock()
     assert_that(len(stock['volume_delta']), greater_than(1))
     assert_that(stock.ix[20141219]['volume_delta'], equal_to(-63383600))
Example #44
0
 def test_column_delta_p2(self):
     stock = self.get_stock_20day()
     open_d = stock['open_2_d']
     assert_that(isnan(open_d.ix[20110119]), equal_to(True))
     assert_that(open_d.ix[20110118], close_to(-0.2, 0.001))
Example #45
0
 def test_to_float(self):
     number = Sdf.to_float('12.3')
     assert_that(number, equal_to(12.3))
Example #46
0
 def test_column_le_count(self):
     stock = self.get_stock_20day()
     c = 'close_13.01_le_5_c'
     stock.get(c)
     assert_that(stock.ix[20110117][c], equal_to(1))
     assert_that(stock.ix[20110119][c], equal_to(3))
Example #47
0
 def test_parse_column_name_stacked_xu(self):
     c, r, t = Sdf.parse_column_name('cr-ma2_xu_cr-ma1_20_c')
     assert_that(c, equal_to('cr-ma2_xu_cr-ma1'))
     assert_that(r, equal_to('20'))
     assert_that(t, equal_to('c'))
Example #48
0
 def test_rsv_nan_value(self):
     s = Sdf.retype(pd.read_csv(get_file('asml.as.csv')))
     df = Sdf.retype(s)
     assert_that(df['rsv_9'][0], equal_to(0.0))
Example #49
0
 def test_parse_column_name_max(self):
     c, r, t = Sdf.parse_column_name('close_-3,-1,+2_max')
     assert_that(c, equal_to('close'))
     assert_that(r, equal_to('-3,-1,+2'))
     assert_that(t, equal_to('max'))
Example #50
0
 def test_parse_column_name_rsv(self):
     c, r, t = Sdf.parse_column_name('rsv_9')
     assert_that(c, equal_to('rsv'))
     assert_that(r, equal_to('9'))
Example #51
0
 def test_parse_column_name_2(self):
     c, r, t = Sdf.parse_column_name('open_+2~4_d')
     assert_that(c, equal_to('open'))
     assert_that(r, equal_to('+2~4'))
     assert_that(t, equal_to('d'))
Example #52
0
 def test_parse_column_name_float(self):
     c, r, t = Sdf.parse_column_name('close_12.32_le')
     assert_that(c, equal_to('close'))
     assert_that(r, equal_to('12.32'))
     assert_that(t, equal_to('le'))
Example #53
0
 def test_bollinger_empty(self):
     stock = self.get_stock().within(18800101, 18900101)
     s = stock['boll_ub']
     assert_that(len(s), equal_to(0))
Example #54
0
 def test_parse_column_name_stacked(self):
     c, r, t = Sdf.parse_column_name('open_-1_d_-1~-3_p')
     assert_that(c, equal_to('open_-1_d'))
     assert_that(r, equal_to('-1~-3'))
     assert_that(t, equal_to('p'))
Example #55
0
 def test_column_cross_down(self):
     stock = self.get_stock_30day()
     cross = stock['kdjk_3_xd_kdjd_3']
     assert_that(sum(cross), equal_to(1))
     assert_that(cross.ix[20110114], equal_to(True))
Example #56
0
 def test_parse_column_name_1(self):
     c, r, t = Sdf.parse_column_name('amount_-5~-1_p')
     assert_that(c, equal_to('amount'))
     assert_that(r, equal_to('-5~-1'))
     assert_that(t, equal_to('p'))
Example #57
0
 def test_column_shift_positive(self):
     stock = self.get_stock_20day()
     close_s = stock['close_2_s']
     assert_that(close_s.ix[20110118], equal_to(12.48))
     assert_that(isnan(close_s.ix[20110119]), equal_to(True))
     assert_that(isnan(close_s.ix[20110120]), equal_to(True))
Example #58
0
 def test_column_ema(self):
     stock = self.get_stock_20day()
     ema_5 = stock['close_5_ema']
     assert_that(isnan(ema_5.ix[20110107]), equal_to(False))
     assert_that(ema_5.ix[20110110], close_to(12.9668, 0.01))
Example #59
0
 def test_column_min(self):
     stock = self.get_stock_20day()
     volume_max = stock['volume_-3~1_min']
     assert_that(volume_max.ix[20110106], equal_to(83140300))
     assert_that(volume_max.ix[20110120], equal_to(50888500))
     assert_that(volume_max.ix[20110112], equal_to(72035800))
Example #60
0
 def test_column_shift_negative(self):
     stock = self.get_stock_20day()
     close_s = stock['close_-1_s']
     assert_that(isnan(close_s.ix[20110104]), equal_to(True))
     assert_that(close_s.ix[20110105:20110106], contains(12.61, 12.71))