Esempio n. 1
0
    def test_handle_api_call(self,
                             mock_is_valid_resource,
                             mock_resolve_action,
                             mock_build_response,
                             mock_build_request,
                             mock_build_request_data):
        mock_is_valid_resource.return_value = True
        mock_resolve_action.return_value = expected_action = MagicMock()
        expected_action.return_value = expected_response = MagicMock()
        mock_build_request.return_value = expected_request = MagicMock()
        mock_build_response.return_value = expected_http_response = MagicMock()
        mock_build_request_data.return_value = expected_request_data = {}
        mock_http_request = MagicMock()
        mock_http_request.read.return_value = request_body = MagicMock()
        mock_api = MagicMock()
        url = 'test_endpoint'

        http_response = django_http_handler.handle_api_call(
            mock_http_request, url, mock_api)

        mock_is_valid_resource.assert_called_once_with('test_endpoint',
                                                       mock_api)
        mock_resolve_action.assert_called_once_with(mock_http_request,
                                                    'test_endpoint',
                                                    mock_api)
        mock_build_request.assert_called_once_with(
            http_request=mock_http_request,
            url=url, api=mock_api, request_data=expected_request_data,
            request_body=request_body)
        expected_action.assert_called_once_with(expected_request)
        assert_that(http_response, equal_to(expected_http_response))
        mock_build_response.assert_called_once_with(mock_http_request,
                                                    expected_response)
def step(context, total_years, selection):
    if selection == "First":
        actual_text = context.rate_checker.get_secondary_interest_rate(0, total_years)
    if selection == "Second":
        actual_text = context.rate_checker.get_secondary_interest_rate(1, total_years)

    assert_that(actual_text, equal_to(total_years))
Esempio n. 3
0
    def test_set_live_reload_status(self):
        ctimain = CtiMain(live_reload_conf=0)
        self.add_me(ctimain)

        dao.set_live_reload_status({'enabled': True})

        assert_that(ctimain.live_reload_conf, equal_to(1))
Esempio n. 4
0
def get_current_leader(lb_pools, timeout = 60, wait_time=5):
    agents = service.get_all_containers('midolman')
    current_leader = None
    num_leaders = 0
    haproxies = []
    while timeout > 0:
        for agent in agents:
            # Check that we have an haproxy running for each pool to be
            # considered a full leader
            haproxies = []
            for lb_pool in lb_pools:
                if agent.hm_resources_exist(lb_pool.get_id()):
                    haproxies.append(lb_pool.get_id())
                else:
                    break

            if len(haproxies) == len(lb_pools):
                current_leader = agent
                num_leaders += 1

        assert_that(num_leaders <= 1,
                    True,
                    'L4LB: More than one agent running haproxy instances')
        if num_leaders == 0:
            LOG.debug('L4LB: No haproxy leaders found! Retrying...')
            time.sleep(wait_time)
            timeout -= wait_time
        else:
            LOG.debug('L4LB: current leader is %s' % current_leader.get_hostname())
            return current_leader

    raise RuntimeError('Not all haproxy instances found! '
                       'Only pools %s have an haproxy instance.' % haproxies)
def step(context, state_name):
    current_Selection = context.rate_checker.get_location()
    # If the location tracker is not available then "Alabama" is set by default
    try:
        assert_that(current_Selection, equal_to('Alabama'))
    except:
        assert_that(current_Selection, equal_to(state_name))
Esempio n. 6
0
def step(context, page_name):
    if (page_name == 'Owning a Home'):
        context.base.go(HOME)
    elif (page_name == 'Loan Comparison'):
        context.base.go(LC)
    elif (page_name == 'Loan Options'):
        context.base.go(LO)
    elif (page_name == 'Rate Checker'):
        context.base.go(RC)
        # Wait for the chart to load
        context.base.sleep(2)
        assert_that(context.rate_checker.is_chart_loaded(), equal_to("Chart is loaded"))
    elif (page_name == 'Conventional Loan'):
        context.base.go(CONV)
    elif (page_name == 'FHA Loan'):
        context.base.go(FHA)
    elif (page_name == 'Special Loan Programs'):
        context.base.go(SPECIAL)
    elif (page_name == 'Know the Process'):
        context.base.go(KP)
    elif (page_name == 'Prepare to Shop'):
        context.base.go(PP)
    elif (page_name == 'Explore Loan Options'):
        context.base.go(PE)
    elif (page_name == 'Compare Loan Options'):
        context.base.go(PC)
    elif (page_name == 'Get Ready to Close'):
        context.base.go(PF)
    else:
        raise Exception(page_name + ' is NOT a valid page')
Esempio n. 7
0
def test_connection_tracking_with_drop_by_dl():
    '''
    Title: Tests dl-based connection tracking.

    Scenario:
    When: A VM inside a FW sends UDP packets to a VM outside.
    And: The outside receives the UDP packets.
    Then: A connection-tracking-based peep hole is established.
    And: The outside now can send UDP packets to the inside. 
    ''' 
    outside = BM.get_iface_for_port('bridge-000-001', 2)
    inside = BM.get_iface_for_port('bridge-000-001', 3)

    # Set a filtering rule based on mac addresses
    set_bridge_port_filters('bridge-000-001', 3, 'connection_tracking_dl_in',
                            'connection_tracking_dl_out')

    # Send forward packets to set up a connection-tracking based peep hole in
    # the filter.
    port_num = get_random_port_num()
    f1 = inside.send_udp('aa:bb:cc:00:01:01', '172.16.1.1', 41,
                         src_port=port_num, dst_port=port_num)
    assert_that(outside, receives('dst host 172.16.1.1 and udp', within_sec(5)),
                'The outside host receives forward packets from the inside.')
    wait_on_futures([f1])

    # Verify the peep hole.
    f1 = outside.send_udp('aa:bb:cc:00:01:02', '172.16.1.2', 41,
                          src_port=port_num, dst_port=port_num)
    assert_that(inside, receives('dst host 172.16.1.2 and udp', within_sec(5)),
                'The outside host can now send packets to the inside via a '
                'peep hole.')
    wait_on_futures([f1])
Esempio n. 8
0
def test_dnat():
    """
    Title: Tests DNAT on ping messages.

    Scenario 1:
    When: a VM sends ICMP echo request with ping command to an unassigned IP
          address.
    Then: the router performs DNAT on the message according to the rule chain
          set to the router,
    And: the receiver VM should receive the ICMP echo packet,
    And: the ping command succeeds
    """
    sender = BM.get_iface_for_port('bridge-000-001', 2)
    receiver = BM.get_iface_for_port('bridge-000-002', 2)

    # Reset in-/out-bound filters.
    unset_filters('router-000-001')
    feed_receiver_mac(receiver)

    f1 = sender.ping_ipv4_addr('100.100.100.100', suppress_failure=True)
    assert_that(receiver, should_NOT_receive('dst host 172.16.2.1 and icmp',
                                             within_sec(5)))
    wait_on_futures([f1])

    # Set DNAT rule chains to the router
    set_filters('router-000-001', 'pre_filter_001', 'post_filter_001')

    f1 = sender.ping_ipv4_addr('100.100.100.100')
    f2 = async_assert_that(receiver, receives('dst host 172.16.2.1 and icmp',
                                   within_sec(5)))
    f3 = async_assert_that(sender, receives('src host 100.100.100.100 and icmp',
                                 within_sec(5)))
    wait_on_futures([f1, f2, f3])
Esempio n. 9
0
def test_connection_tracking_by_network_addres():
    '''
    Title: Tests NW address based connection tracking.

    Scenario:
    When: A VM, supposedly inside a FW, sends UDP packets to another host,
          supposedly outside the FS, on the same bridge.
    And: The host outside the FW receives the UDP packets.
    Then: A connection-tracking-based peep hole is established.
    And: The outside host now can send UDP packets to the inside host. 
    '''
    outside = BM.get_iface_for_port('bridge-000-001', 2)
    inside = BM.get_iface_for_port('bridge-000-001', 3)

    # Set a filtering rule based on ip address.
    set_bridge_port_filters('bridge-000-001', 3, 'connection_tracking_nw_in',
                            'connection_tracking_nw_out')

    # Send forward packets to set up a connection-tracking based peep hole in
    # the filter.
    port_num = get_random_port_num()
    f1 = inside.send_udp('aa:bb:cc:00:01:01', '172.16.1.1', 41,
                         src_port=port_num, dst_port=port_num)
    assert_that(outside, receives('dst host 172.16.1.1 and udp', within_sec(5)),
                'Outside host receives forward packets from inside.')
    wait_on_futures([f1])

    # Verify the peep hole.
    f1 = outside.send_udp('aa:bb:cc:00:01:02', '172.16.1.2', 41,
                         src_port=port_num, dst_port=port_num)
    assert_that(inside, receives('dst host 172.16.1.2 and udp', within_sec(5)),
                'Outside host can send packets to inside via a peep hole.')
    wait_on_futures([f1])
Esempio n. 10
0
def test_filtering_by_dl():
    '''
    Title: Tests dl-based packet filtering.

    Scenario:
    When: A VM sends UDP packets to another host on the same bridge.
    Then: The UDP packets reach the receiver without filtering rule chains.
    Then: A filtering rule chain based on mac address is set on the bridge.
    And: UDP packets from the same host do NOT reach the same destination host.
    '''
    outside = BM.get_iface_for_port('bridge-000-001', 2)
    inside = BM.get_iface_for_port('bridge-000-001', 3)

    # Reset an in-bound filter. 
    unset_bridge_port_filters('bridge-000-001', 3)

    port_num = get_random_port_num()
    f1 = outside.send_udp('aa:bb:cc:00:01:02', '172.16.1.2', 41,
                          src_port=port_num, dst_port=port_num)
    assert_that(inside, receives('dst host 172.16.1.2 and udp', within_sec(5)),
                'No filtering: inside receives UDP packets from outside.')
    wait_on_futures([f1])

    # Set a filtering rule based on mac addresses
    set_bridge_port_filters('bridge-000-001', 3, 'connection_tracking_dl_in',
                            'connection_tracking_dl_out')

    f1 = outside.send_udp('aa:bb:cc:00:01:02', '172.16.1.2', 41,
                          src_port=port_num, dst_port=port_num)
    assert_that(inside, should_NOT_receive('dst host 172.16.1.2 and udp',
                                           within_sec(5)),
                'Packets are filtered based on mac address.')
    wait_on_futures([f1])
Esempio n. 11
0
    def test_authentication_for_a_valid_user(self):
        user = MagicMock()
        request = Request(user=user, request_params=None)

        returned_request = default_authentication.authenticate(request)

        assert_that(returned_request, equal_to(request))
Esempio n. 12
0
def test_filtering_by_network_address():
    '''
    Title: Tests packets filtering based on network address

    Scenario:
    When: A VM sends UDP packets to another host on the same bridge.
    Then: The UDP packets reaches the receiver. 
    Then: Filtering rule chains based on network address (IP address) are set on
          the bridge port that the receiver host is connected to.
    And: The UDP packets from the same sender do NOT reach the receiver.
    '''
    sender = BM.get_iface_for_port('bridge-000-001', 2)
    receiver = BM.get_iface_for_port('bridge-000-001', 3)

    # Reset in/out-bound filters. 
    unset_bridge_port_filters('bridge-000-001', 3)

    port_num = get_random_port_num()
    f1 = sender.send_udp('aa:bb:cc:00:01:02', '172.16.1.2', 41,
                         src_port=port_num, dst_port=port_num)
    assert_that(receiver, receives('dst host 172.16.1.2 and udp', within_sec(5)),
                'No filtering: receiver receives UDP packets from sender.')
    wait_on_futures([f1])

    # Set a filtering rule based on network address.
    set_bridge_port_filters('bridge-000-001', 3, 'connection_tracking_nw_in',
                            'connection_tracking_nw_out')

    f1 = sender.send_udp('aa:bb:cc:00:01:02', '172.16.1.2', 41,
                         src_port=port_num, dst_port=port_num)
    assert_that(receiver, should_NOT_receive('dst host 172.16.1.2 and udp',
                                             within_sec(5)),
                'Packets are filtered based on IP address.')
    wait_on_futures([f1])
Esempio n. 13
0
    def test_authentication_when_no_user(self):
        request = Request(user=None, request_params=None)

        response = default_authentication.authenticate(request)

        assert_that(response.is_success, equal_to(False))
        assert_that(response.reason, equal_to(error_types.AuthenticationFailed))
Esempio n. 14
0
def step(context, page_name):
    if page_name == "Owning a Home":
        context.base.go(HOME)
    elif page_name == "Loan Comparison":
        context.base.go(LC)
    elif page_name == "Loan Options":
        context.base.go(LO)
    elif page_name == "Rate Checker":
        context.base.go(RC)
        # Wait for the chart to load
        context.base.sleep(2)
        assert_that(context.rate_checker.is_chart_loaded(), equal_to("Chart is loaded"))
    elif page_name == "Conventional Loan":
        context.base.go(CONV)
    elif page_name == "FHA Loan":
        context.base.go(FHA)
    elif page_name == "Special Loan Programs":
        context.base.go(SPECIAL)
    elif page_name == "Know the Process":
        context.base.go(KP)
    elif page_name == "Prepare to Shop":
        context.base.go(PP)
    elif page_name == "Explore Loan Options":
        context.base.go(PE)
    elif page_name == "Compare Loan Options":
        context.base.go(PC)
    elif page_name == "Get Ready to Close":
        context.base.go(PF)
    elif page_name == "Closing Disclosure":
        context.base.go(CD)
    elif page_name == "Loan Estimate":
        context.base.go(LE)
    else:
        raise Exception(page_name + " is NOT a valid page")
Esempio n. 15
0
def test_snat():
    """
    Title: Tests SNAT on ping messages.

    Scenario:
    When: a VM sends ICMP echo request with ping command to a different subnet,
    Then: the router performs SNAT on the message according to the rule chain
          set to the router,
    And: the receiver VM should receive the ICMP echo packet, with src address
         NATted,
    And: the ping command succeeds.
    """
    sender = BM.get_iface_for_port('bridge-000-001', 2)
    receiver = BM.get_iface_for_port('bridge-000-002', 2)

    # Reset in-/out-bound filters.
    unset_filters('router-000-001')
    feed_receiver_mac(receiver)

    f1 = sender.ping4(receiver)
    # No SNAT configured. Should not receive SNATed messages.
    assert_that(receiver, should_NOT_receive('src host 172.16.1.100 and icmp',
                                             within_sec(5)))
    wait_on_futures([f1])

    # Set SNAT rule chains to the router
    set_filters('router-000-001', 'pre_filter_002', 'post_filter_002')

    f1 = sender.ping4(receiver)
    # The receiver should receive SNATed messages.
    f2 = async_assert_that(receiver, receives('src host 172.16.1.100 and icmp',
                                   within_sec(5)))
    f3 = async_assert_that(sender, receives('dst host 172.16.1.1 and icmp',
                                 within_sec(5)))
    wait_on_futures([f1, f2, f3])
Esempio n. 16
0
    def test_validate_returns_error_if_max_length_exceeds(self):
        string_field = StringField(max_length=1, required=True)

        result = string_field.validate(None, '1212')

        assert_that(result.is_success, equal_to(False))
        assert_that(result.reason, equal_to('Maxlength of 1 exceeded'))
Esempio n. 17
0
    def test_validate_returns_error_for_invalid_type(self):
        url_field = UrlField(required=True)

        result = url_field.validate(None, 1212)

        assert_that(result.is_success, equal_to(False))
        assert_that(result.reason, equal_to('Expected type string'))
Esempio n. 18
0
    def test_validate_returns_error_if_required_and_value_is_default(self):
        url_field = UrlField(required=True)

        result = url_field.validate(None, DEFAULT_FIELD_VALUE)

        assert_that(result.is_success, equal_to(False))
        assert_that(result.reason, equal_to('This field is required'))
Esempio n. 19
0
    def test_put_products(self):
        if self.__catalog_service is None or self.__read_only:
            return

        self.__put_products()
        products = self.__catalog_service.get_products()
        assert_that(products, equal_to(self.__products))
def step(context, state_name):
    # Wait for the chart to load
    assert_that(context.rate_checker.is_chart_loaded(), equal_to("Chart is loaded"))

    context.rate_checker.set_location(state_name)
    # Wait for the chart to load
    assert_that(context.rate_checker.is_chart_loaded(), equal_to("Chart is loaded"))
Esempio n. 21
0
    def test_remove_its_members_from_the_bond(self):
        self.try_to.add_interface_to_bond(self.test_port, 42)

        self.client.remove_bond(42)
        
        interface = self.client.get_interface(self.test_port)
        assert_that(interface.bond_master, is_(None))
Esempio n. 22
0
    def test_with_equals_filter(self, mock_view):
        mock_view.return_value = {'name': 'foo'}
        request = request_factory.get_request(user=object(), request_params={'foo': 'bar'})
        response = DummyResource().read(request=request)

        assert_that(response.is_success, equal_to(True))
        assert_that(response.data, equal_to({'name': 'foo'}))
        mock_view.assert_called_once_with(request, **({'foo': 'bar'}))
Esempio n. 23
0
    def test_get(self, profile_dao_get):
        profile = CtiProfile()
        profile_dao_get.return_value = profile

        result = services.get(1)

        assert_that(result, same_instance(profile))
        profile_dao_get.assert_called_with(1)
Esempio n. 24
0
def step(context, param_name):
    expected_reponse = "Required parameter '" + param_name + "' is missing"
    context.json_data = json.loads(context.response.text)

    context.logger.debug("JSON detail is: %s" % context.json_data['detail'])
    context.logger.debug("JSON text is: %s" % context.response.text)

    assert_that(context.json_data['detail'], equal_to(expected_reponse))
Esempio n. 25
0
    def test_get_live_reload_status(self, is_live_reload_enabled):
        is_live_reload_enabled.return_value = False
        expected_result = {'enabled': False}

        result = services.get_live_reload_status()

        assert_that(result, equal_to(expected_result))
        is_live_reload_enabled.assert_called_once_with()
Esempio n. 26
0
    def test_find_all(self, profile_dao_find_all):
        profile1 = CtiProfile()
        profile2 = CtiProfile()
        profile_dao_find_all.return_value = [profile1, profile2]

        [res1, res2] = services.find_all()

        assert_that(res1, same_instance(profile1))
        assert_that(res2, same_instance(profile2))
def step(context, range_operation):
    # get the range text from below the slider handle
    range_text = context.rate_checker.get_credit_score_range()
    currentRange = int(range_text[:3])

    if (range_operation == "increase"):
        assert_that(currentRange, greater_than(DEFAULT_CREDIT_SCORE))
    elif (range_operation == "decrease"):
        assert_that(currentRange, less_than(DEFAULT_CREDIT_SCORE))
 def runTest(self):
     iprot = MagentoXmlrpcProtocol(self.PRODUCTS_XMLRPC)
     products = []
     for _ in xrange(iprot.readListBegin()[1]):
         product = MagentoProduct.read(iprot)
         assert product is not None
         products.append(product)
     iprot.readListEnd()
     assert_that(products, has_length(1))
Esempio n. 29
0
    def test_get_mail_templates(self):
        templates = self.__mail_service.get_mail_templates()
        assert_that(templates, has_length(greater_than(0)))

        templates = \
            self.__mail_service.get_mail_templates(
                types=frozenset((MailTemplateType(TemplateType.BASE),))
            )
        assert_that(templates, has_length(greater_than(0)))
def step(context, state_name):
    # Get the location state displayed on page
    actual_text = context.rate_checker.get_chart_location()
    # If the location tracker is not available then "Alabama" is set by default
    try:
        assert_that(actual_text, equal_to("Alabama"))
    # Verify that displayed location matches the expected state
    except AssertionError:
        assert_that(actual_text, equal_to(state_name))
Esempio n. 31
0
 def test_obj_to_dict_with_object_in_dict(self):
     # given
     e1 = Entry('1234', name='Alice')
     e2 = Entry('456')
     # when
     result = objToDict({'a': e1, 'b': e2})
     # then
     assert_that(
         result,
         is_({
             'a': {
                 'id': '1234',
                 'name': 'Alice'
             },
             'b': {
                 'id': '456'
             }
         }))
Esempio n. 32
0
 def test_patch_to_subresource_should_fail(self):
     # given
     entry = Entry('1234', name='Charlie', phone='5678')
     self.app.post_json(url='/phonebook/', params=objToDict(entry))
     # when
     response = self.app.patch_json(url='/phonebook/1234/asdf',
                                    params={
                                        'name': 'David',
                                        'phone': None,
                                        'mobile': 5555
                                    },
                                    expect_errors=True)
     # then
     assert_that(response.status_int, is_(404))
     assert_that(response.json, equal_to({
         'status': 404,
         'detail': HTTP_404
     }))
Esempio n. 33
0
    def test_get_product_by_sku(self):
        if self.__catalog_service is None:
            return

        if not self.__read_only:
            self.__put_products()

        product_skus = self.__catalog_service.get_product_skus()
        assert_that(product_skus, has_length(greater_than(0)))
        for product_sku in product_skus:
            product = self.__catalog_service.get_product_by_sku(product_sku)
            assert_that(product, instance_of(Product))

        try:
            self.__catalog_service.get_product_by_sku('nonexitantsku')
            self.fail()
        except NoSuchProductException:
            pass
Esempio n. 34
0
    def test_should_get_tags_for_given_documents_topics_and_tokens(self):
        documents_tokens_map = {
            "sha1": [
                "content", "network", "router", "wifi", "cable", "ethernet",
                "socket", "authentication", "content", "router", "wifi",
                "cable", "ethernet", "socket", "authentication"
            ],
            "sha2": ["java", "golang", "python", "clojure", "socket"],
            "sha3": ["authentication", "golang", "socket", "clojure"],
            "sha4": [
                "network", "cable", "ethernet", "monitor", "reliability",
                "cable", "ethernet", "content", "network", "router", "wifi",
                "cable", "ethernet", "socket", "authentication"
            ],
            "sha5": ["python", "python", "python", "java"]
        }
        documents_topics_map = {
            "sha1": [("0", 0.80), ("1", 0.1)],
            "sha2": [("2", 0.90), ("1", 0.1)],
            "sha3": [("2", 0.5), ("1", 0.5)],
            "sha4": [("0", 0.1), ("1", 0.9)],
            "sha5": [("2", 0.92)]
        }
        expected_documents_tags_hamcrest_assert = has_entries(
            "sha1", contains_inanyorder(
                "router", "authentication", "content")), has_entries(
                    "sha2", contains_inanyorder(
                        "java", "clojure", "python")), has_entries(
                            "sha3",
                            contains_inanyorder("clojure")), has_entries(
                                "sha4",
                                contains_inanyorder("ethernet", "socket",
                                                    "network")), has_entries(
                                                        "sha5",
                                                        contains_inanyorder(
                                                            "python", "java"))

        document_tag_generator = TagGenerator(self.topics_tokens_map)
        actual_documents_tags_map = document_tag_generator.generate_documents_tag_map(
            documents_tokens_map=documents_tokens_map,
            documents_topics_map=documents_topics_map,
            top_n=3)
        assert_that(actual_documents_tags_map,
                    expected_documents_tags_hamcrest_assert)
Esempio n. 35
0
 def test_patch_should_fail_when_id_in_url_and_body_mismatch(self):
     # given
     entry = Entry('1234', name='Charlie', phone='5678')
     self.app.post_json(url='/phonebook/', params=objToDict(entry))
     # when
     response = self.app.patch_json(url='/phonebook/1234',
                                    params={
                                        'id': '456',
                                        'name': 'David'
                                    },
                                    expect_errors=True)
     # then
     assert_that(response.status_int, is_(400))
     assert_that(
         response.json,
         equal_to({
             'status': 400,
             'detail': 'Entry ID in URL and body mismatch'
         }))
    def test_raises_bad_request_if_required_data_is_missing(self):
        data = {}
        request = request_factory.get_request(
            data=data,
            context_params={'crud_action': CrudActions.CREATE_DETAIL})

        response = self.validation.validate_request_data(request)

        assert_that(response.is_success, equal_to(False))
        assert_that(response.reason, equal_to(error_types.InvalidData))
        assert_that(len(response.data), equal_to(2))
        assert_that(response.data, has_items('name', 'is_active'))
Esempio n. 37
0
 def test_init_with_extra_attrs(self):
     entry = Entry(2,
                   attrBool=True,
                   attrStr='attr',
                   attrDict={
                       'a': 1,
                       'b': 2
                   })
     assert_that(entry.id, is_(2))
     assert_that(entry.attrBool, is_(True))
     assert_that(entry.attrStr, is_('attr'))
     assert_that(entry.attrDict, equal_to({'a': 1, 'b': 2}))
Esempio n. 38
0
def test_filtering_by_network_address():
    '''
    Title: Tests packets filtering based on network address

    Scenario:
    When: A VM sends UDP packets to another host on the same bridge.
    Then: The UDP packets reaches the receiver. 
    Then: Filtering rule chains based on network address (IP address) are set on
          the bridge port that the receiver host is connected to.
    And: The UDP packets from the same sender do NOT reach the receiver.
    '''
    sender = BM.get_iface_for_port('bridge-000-001', 2)
    receiver = BM.get_iface_for_port('bridge-000-001', 3)

    # Reset in/out-bound filters.
    unset_bridge_port_filters('bridge-000-001', 3)

    port_num = get_random_port_num()
    f1 = sender.send_udp('aa:bb:cc:00:01:02',
                         '172.16.1.2',
                         41,
                         src_port=port_num,
                         dst_port=port_num)
    assert_that(receiver, receives('dst host 172.16.1.2 and udp',
                                   within_sec(5)),
                'No filtering: receiver receives UDP packets from sender.')
    wait_on_futures([f1])

    # Set a filtering rule based on network address.
    set_bridge_port_filters('bridge-000-001', 3, 'connection_tracking_nw_in',
                            'connection_tracking_nw_out')

    f1 = sender.send_udp('aa:bb:cc:00:01:02',
                         '172.16.1.2',
                         41,
                         src_port=port_num,
                         dst_port=port_num)
    assert_that(
        receiver,
        should_NOT_receive('dst host 172.16.1.2 and udp', within_sec(5)),
        'Packets are filtered based on IP address.')
    wait_on_futures([f1])
Esempio n. 39
0
    def test_are_destinations_equal_in_flow(self):
        assert_that(
            IsEqualToFlowComparisonLogic.are_destinations_equal_in_flow(
                ["objectName1", "objectName2"],
                {
                    "destinations": [{
                        "name": "objectName1"
                    }, {
                        "name": "objectName2"
                    }]
                },
            ), is_(equal_to(True)))

        assert_that(
            IsEqualToFlowComparisonLogic.are_destinations_equal_in_flow(
                ["objectName1"],
                {"destinations": [{
                    "name": "UnknownObjectName"
                }]},
            ), is_(equal_to(False)))
Esempio n. 40
0
def step(context, page_name):
    if (page_name == 'Owning a Home'):
        context.base.go(HOME)
    elif (page_name == 'Loan Comparison'):
        context.base.go(LC)
    elif (page_name == 'Loan Options'):
        context.base.go(LO)
    elif (page_name == 'Rate Checker'):
        context.base.go(RC)
        # Wait for the chart to load
        context.base.sleep(1)
        assert_that(context.rate_checker.is_chart_loaded(), equal_to(True))
    elif (page_name == 'Conventional Loan'):
        context.base.go(CONV)
    elif (page_name == 'FHA Loan'):
        context.base.go(FHA)
    elif (page_name == 'Special Loan Programs'):
        context.base.go(SPECIAL)
    else:
        raise Exception(page_name + ' is NOT a valid page')
Esempio n. 41
0
def test_connection_tracking_with_drop_by_dl():
    '''
    Title: Tests dl-based connection tracking.

    Scenario:
    When: A VM inside a FW sends UDP packets to a VM outside.
    And: The outside receives the UDP packets.
    Then: A connection-tracking-based peep hole is established.
    And: The outside now can send UDP packets to the inside. 
    '''
    outside = BM.get_iface_for_port('bridge-000-001', 2)
    inside = BM.get_iface_for_port('bridge-000-001', 3)

    # Set a filtering rule based on mac addresses
    set_bridge_port_filters('bridge-000-001', 3, 'connection_tracking_dl_in',
                            'connection_tracking_dl_out')

    # Send forward packets to set up a connection-tracking based peep hole in
    # the filter.
    port_num = get_random_port_num()
    f1 = inside.send_udp('aa:bb:cc:00:01:01',
                         '172.16.1.1',
                         41,
                         src_port=port_num,
                         dst_port=port_num)
    assert_that(outside, receives('dst host 172.16.1.1 and udp',
                                  within_sec(5)),
                'The outside host receives forward packets from the inside.')
    wait_on_futures([f1])

    # Verify the peep hole.
    f1 = outside.send_udp('aa:bb:cc:00:01:02',
                          '172.16.1.2',
                          41,
                          src_port=port_num,
                          dst_port=port_num)
    assert_that(
        inside, receives('dst host 172.16.1.2 and udp', within_sec(5)),
        'The outside host can now send packets to the inside via a '
        'peep hole.')
    wait_on_futures([f1])
Esempio n. 42
0
    def test_read_detail_pipeline_has_all_steps_in_the_right_order(
            self, compose_pipeline):
        entity_actions = MagicMock()
        entity_actions.read_detail = read_detail = MagicMock()
        authentication = MagicMock()
        authentication.authenticate = MagicMock()
        authorization = MagicMock()
        authorization \
            .authorize_read_detail = authorize_read_detail = MagicMock()
        cleaner = MagicMock()
        cleaner.clean_data_for_read_detail = \
            clean_data_for_read_detail = MagicMock()
        serializer = MagicMock()
        serializer.serialize_detail = serialize_detail = MagicMock()
        response_converter = MagicMock()
        response_converter.convert_serialized_data_to_response = \
            convert_serialized_data_to_response = MagicMock()
        post_action_hooks = MagicMock()
        post_action_hooks.read_detail_hook = read_detail_hook = MagicMock()

        compose_pipeline.return_value = expected_pipeline = MagicMock()
        configuration = {
            'entity_actions': entity_actions,
            'authentication': authentication,
            'authorization': authorization,
            'serializer': serializer,
            'data_cleaner': cleaner,
            'response_converter': response_converter,
            'post_action_hooks': post_action_hooks
        }

        pipeline = crud_pipeline_factory.read_detail_pipeline(configuration)

        assert_that(pipeline, equal_to(expected_pipeline))
        compose_pipeline.assert_called_once_with(
            name=CrudActions.READ_DETAIL,
            pipeline=[
                authentication.authenticate, clean_data_for_read_detail,
                read_detail, authorize_read_detail, serialize_detail,
                read_detail_hook, convert_serialized_data_to_response
            ])
Esempio n. 43
0
    def test_are_network_services_equal_in_flow(self):
        # TODO: Make sure that we have no issues with case sensitiveness of TCP/80 vs tcp/80 for any of the protocols
        assert_that(
            IsEqualToFlowComparisonLogic.are_network_services_equal_in_flow(
                ["service1", "service2"],
                {"services": [
                    {
                        "name": "service2"
                    },
                    {
                        "name": "service1"
                    },
                ]}), is_(equal_to(True)))

        assert_that(
            IsEqualToFlowComparisonLogic.are_network_services_equal_in_flow(
                ["service2"],
                {"services": [{
                    "name": "service1"
                }]},
            ), is_(equal_to(False)))
def test_order_suffix(suffix: str) -> None:
    prefix = "X"
    number = "1"
    index = NUMBERS_AND_SUFFIXES.index(suffix)
    larger = NUMBERS_AND_SUFFIXES[index + 1 :]
    smaller = NUMBERS_AND_SUFFIXES[:index]
    assert_that(
        MuseumNumber(prefix, number, suffix),
        all_of(
            *(
                *(
                    less_than(MuseumNumber(prefix, number, another))
                    for another in larger
                ),
                *(
                    greater_than(MuseumNumber(prefix, number, another))
                    for another in smaller
                ),
            )
        ),
    )
Esempio n. 45
0
def test_connection_tracking_by_network_addres():
    '''
    Title: Tests NW address based connection tracking.

    Scenario:
    When: A VM, supposedly inside a FW, sends UDP packets to another host,
          supposedly outside the FS, on the same bridge.
    And: The host outside the FW receives the UDP packets.
    Then: A connection-tracking-based peep hole is established.
    And: The outside host now can send UDP packets to the inside host. 
    '''
    outside = BM.get_iface_for_port('bridge-000-001', 2)
    inside = BM.get_iface_for_port('bridge-000-001', 3)

    # Set a filtering rule based on ip address.
    set_bridge_port_filters('bridge-000-001', 3, 'connection_tracking_nw_in',
                            'connection_tracking_nw_out')

    # Send forward packets to set up a connection-tracking based peep hole in
    # the filter.
    port_num = get_random_port_num()
    f1 = inside.send_udp('aa:bb:cc:00:01:01',
                         '172.16.1.1',
                         41,
                         src_port=port_num,
                         dst_port=port_num)
    assert_that(outside, receives('dst host 172.16.1.1 and udp',
                                  within_sec(5)),
                'Outside host receives forward packets from inside.')
    wait_on_futures([f1])

    # Verify the peep hole.
    f1 = outside.send_udp('aa:bb:cc:00:01:02',
                          '172.16.1.2',
                          41,
                          src_port=port_num,
                          dst_port=port_num)
    assert_that(inside, receives('dst host 172.16.1.2 and udp', within_sec(5)),
                'Outside host can send packets to inside via a peep hole.')
    wait_on_futures([f1])
Esempio n. 46
0
def test_filtering_by_dl():
    '''
    Title: Tests dl-based packet filtering.

    Scenario:
    When: A VM sends UDP packets to another host on the same bridge.
    Then: The UDP packets reach the receiver without filtering rule chains.
    Then: A filtering rule chain based on mac address is set on the bridge.
    And: UDP packets from the same host do NOT reach the same destination host.
    '''
    outside = BM.get_iface_for_port('bridge-000-001', 2)
    inside = BM.get_iface_for_port('bridge-000-001', 3)

    # Reset an in-bound filter.
    unset_bridge_port_filters('bridge-000-001', 3)

    port_num = get_random_port_num()
    f1 = outside.send_udp('aa:bb:cc:00:01:02',
                          '172.16.1.2',
                          41,
                          src_port=port_num,
                          dst_port=port_num)
    assert_that(inside, receives('dst host 172.16.1.2 and udp', within_sec(5)),
                'No filtering: inside receives UDP packets from outside.')
    wait_on_futures([f1])

    # Set a filtering rule based on mac addresses
    set_bridge_port_filters('bridge-000-001', 3, 'connection_tracking_dl_in',
                            'connection_tracking_dl_out')

    f1 = outside.send_udp('aa:bb:cc:00:01:02',
                          '172.16.1.2',
                          41,
                          src_port=port_num,
                          dst_port=port_num)
    assert_that(
        inside, should_NOT_receive('dst host 172.16.1.2 and udp',
                                   within_sec(5)),
        'Packets are filtered based on mac address.')
    wait_on_futures([f1])
 def test_raises_bad_request_if_field_greater_than_max_length(self):
     data = {
         'name': 'John Smith',
         'is_active': True,
         'country': 'United States'
     }
     request = request_factory.get_request(
         data=data,
         context_params={'crud_action': CrudActions.UPDATE_DETAIL})
     response = self.validation.validate_request_data(request)
     assert_that(response.is_success, equal_to(False))
     assert_that(response.reason, equal_to(error_types.InvalidData))
     assert_that(len(response.data), equal_to(2))
     assert_that(response.data, has_items('name', 'country'))
Esempio n. 48
0
def step(context, page_name):
    if (page_name == 'Owning a Home'):
        context.base.go(HOME)
    elif (page_name == 'Loan Comparison'):
        context.base.go(LC)
    elif (page_name == 'Loan Options'):
        context.base.go(LO)
    elif (page_name == 'Rate Checker'):
        context.base.go(ER)
        # Wait for the chart to load
        context.base.sleep(2)
        assert_that(context.rate_checker.is_chart_loaded(), equal_to("Chart is loaded"))
    elif (page_name == 'Conventional Loan'):
        context.base.go(CONV)
    elif (page_name == 'FHA Loan'):
        context.base.go(FHA)
    elif (page_name == 'Special Loan Programs'):
        context.base.go(SPECIAL)
    elif (page_name == 'Know the Process'):
        context.base.go(KP)
    elif (page_name == 'Prepare to Shop'):
        context.base.go(PP)
    elif (page_name == 'Explore Loan Options'):
        context.base.go(PE)
    elif (page_name == 'Compare Loan Options'):
        context.base.go(PC)
    elif (page_name == 'Get Ready to Close'):
        context.base.go(PF)
    elif (page_name == 'Sources'):
        context.base.go(PS)
    elif (page_name == 'Closing Disclosure'):
        context.base.go(CD)
    elif (page_name == 'Loan Estimate'):
        context.base.go(LE)
    elif (page_name == 'Mortgage Closing'):
        context.base.go(MC)
    elif (page_name == 'Mortgage Estimate'):
        context.base.go(ME)
    else:
        raise Exception(page_name + ' is NOT a valid page')
def test_order_prefix(prefix: str) -> None:
    number = "B"
    suffix = "C"
    index = PREFIXES.index(prefix)
    larger = PREFIXES[index + 1 :]
    smaller = PREFIXES[:index]
    assert_that(
        MuseumNumber(prefix, number, suffix),
        all_of(
            *(
                *(
                    less_than(MuseumNumber(another, number, suffix))
                    for another in larger
                ),
                *(
                    greater_than(MuseumNumber(another, number, suffix))
                    for another in smaller
                ),
                equal_to(MuseumNumber(prefix, number, suffix)),
            )
        ),
    )
Esempio n. 50
0
def test_floating_ip():
    """
    Title: Tests a floating IP.

    Scenario 1:
    When: a VM sends an ICMP echo request to a floating IP address
          (100.100.100.100).
    Then: the router performs DNAT on the message according to the rule chain
          set to the router,
    And: the receiver VM should receive the ICMP echo packet,
    And: the receiver sends back an ICMP reply with its original IP address
         as a source address.
    And: the router applies SNAT to the reply packet.
    And: the sender receives the reply with src address NATed to the floating IP
         address.
    """
    sender = BM.get_iface_for_port('bridge-000-001', 2)
    receiver = BM.get_iface_for_port('bridge-000-002', 2)

    # Reset in-/out-bound filters.
    unset_filters('router-000-001')
    feed_receiver_mac(receiver)

    f1 = sender.ping_ipv4_addr('100.100.100.100', suppress_failure=True)
    assert_that(
        receiver,
        should_NOT_receive('dst host 172.16.2.1 and icmp', within_sec(5)))
    wait_on_futures([f1])

    # Configure floating IP address with the router
    set_filters('router-000-001', 'pre_filter_floating_ip',
                'post_filter_floating_ip')

    f1 = sender.ping_ipv4_addr('100.100.100.100')
    f2 = async_assert_that(
        receiver, receives('dst host 172.16.2.1 and icmp', within_sec(5)))
    f3 = async_assert_that(
        sender, receives('src host 100.100.100.100 and icmp', within_sec(5)))
    wait_on_futures([f1, f2, f3])
Esempio n. 51
0
def test_all_paired_dataset_providers_should_honor_excludes(
        dataset_provider_cls_name, patched_excluded):
    provider_cls = from_class_name(dataset_provider_cls_name)
    raw_data_provider = FakeRawDataProvider(curated=True)
    dataset_spec = DatasetSpec(raw_data_provider,
                               DatasetType.TEST,
                               with_excludes=False,
                               encoding=False)
    provider = provider_cls(raw_data_provider)

    dataset = provider.supply_dataset(dataset_spec, batch_size=1).take(100)
    encountered_labels = set()
    for batch in dataset:
        left_label = batch[0][
            consts.LEFT_FEATURE_IMAGE].numpy().flatten()[0] + 0.5
        right_label = batch[0][
            consts.RIGHT_FEATURE_IMAGE].numpy().flatten()[0] + 0.5
        encountered_labels.update((left_label, right_label))
    assert_that((np.rint(list(encountered_labels)) * 10),
                only_contains(not_(is_in(list(patched_excluded.numpy())))))
    assert_that((np.rint(list(encountered_labels)) * 10),
                only_contains((is_in([0, 1, 4]))))
Esempio n. 52
0
def test_should_include_reduced_size_in_path(expected_size,
                                             should_image_size_be_reduced):
    images_dataset: DictsDataset
    paths_dataset: DictsDataset
    images_dataset, paths_dataset = gen.dicts_dataset(save_on_disc=True)

    dataset_desc = gen.dataset_desc(
        storage_method=DatasetStorageMethod.ON_DISC,
        image_dimensions=ImageDimensions(expected_size))
    raw_dataset_fragment = testing_helpers.dicts_dataset_to_raw_dataset_fragment(
        images_dataset)
    dataset_spec = gen.dataset_spec(description=dataset_desc,
                                    raw_dataset_fragment=raw_dataset_fragment,
                                    paired=False)
    tfrecord_full_path = preparing_data.save_to_tfrecord(
        paths_dataset.features, paths_dataset.labels, 'data', dataset_spec)

    parts = tfrecord_full_path.parts
    if should_image_size_be_reduced:
        assert ("size_" + str(expected_size[0])) in parts
    else:
        assert_that(parts, not_(contains("size_" + str(expected_size[0]))))
Esempio n. 53
0
    def test_are_destinations_included_in_flow(self):
        assert_that(
            IsIncludedInFlowComparisonLogic.are_destinations_included_in_flow(
                {
                    "DEST-IP": {"objectID1", "objectID2"},
                    "DEST-IP2": {"objectID2", "objectID3"}
                },
                {"destinations": [{
                    "objectID": "objectID2"
                }]},
            ), is_(equal_to(True)))

        assert_that(
            IsIncludedInFlowComparisonLogic.are_destinations_included_in_flow(
                {"DEST-IP": {"UnknownObject"}},
                {
                    "destinations": [{
                        "objectID": "objectID1"
                    }, {
                        "objectID": "objectID2"
                    }]
                },
            ), is_(equal_to(False)))
Esempio n. 54
0
    def test_are_sources_included_in_flow(self):
        assert_that(
            IsIncludedInFlowComparisonLogic.are_sources_included_in_flow(
                {
                    "SOURCE-IP": {"objectID1", "objectID2"},
                    "SOURCE-IP2": {"objectID2", "objectID3"}
                },
                {"sources": [{
                    "objectID": "objectID2"
                }]},
            ), is_(equal_to(True)))

        assert_that(
            IsIncludedInFlowComparisonLogic.are_sources_included_in_flow(
                {"SOURCE-IP": {"UnknownObject"}},
                {
                    "sources": [{
                        "objectID": "objectID1"
                    }, {
                        "objectID": "objectID2"
                    }]
                },
            ), is_(equal_to(False)))
Esempio n. 55
0
 def test_first_fetch(self):
     result = requests.get(f'{self.endpoint}/api/events',
                           params={'fetch_offset': ''})
     assert_that(result.status_code, equal_to(200))
     assert_that(len(result.json()['events']), equal_to(25))
     token: str = result.json()['fetch_offset']
     assert_that(
         base64.decodebytes(token.encode('utf-8')).decode('utf-8'),
         is_not(equal_to('DONE')))
Esempio n. 56
0
    def test_should_validate(self):
        field = SchemaField(self.test_schema_cls)
        request = request_factory.get_request(
            context_params={'crud_action': CrudActions.UPDATE_DETAIL})
        result = field.validate(request, {'name': 1})

        assert_that(result, instance_of(ValidationResult))
        assert_that(result.is_success, equal_to(False))
        assert_that(result.reason, has_entry('name', 'Expected type string'))
Esempio n. 57
0
 def test_none_result(self):
     result = requests.get(f'{self.endpoint}/api/search',
                           params={'term': 'klaasjanelzingapython37'})
     assert_that(result.status_code, equal_to(200))
     assert_that(len(result.json()['events']), equal_to(0))
     token: str = result.json()['fetch_offset']
     assert_that(
         base64.decodebytes(token.encode('utf-8')).decode('utf-8'),
         equal_to('DONE'))
Esempio n. 58
0
 def test_param_search(self, search_key, type, expected_price):
     """
     1. 打开雪球应用
     2. 点击 搜索框
     3. 输入 搜索词 'alibaba' or 'xiaomi'
     4. 点击 第一个搜索结果
     5. 判断股票价格
     :return:
     """
     self.driver.find_element_by_id(
         'com.xueqiu.android:id/home_search').click()
     self.driver.find_element(
         MobileBy.ID,
         "com.xueqiu.android:id/search_input_text").send_keys(search_key)
     # self.driver.find_element_by_xpath('//*[@resource-id="com.xueqiu.android:id/name" and @text="阿里巴巴"]').click()
     self.driver.find_element_by_xpath(
         '//*[@resource-id="com.xueqiu.android:id/name"]').click()
     price = self.driver.find_element_by_xpath(
         f'//*[@text="{type}"]/../../..//*[@resource-id="com.xueqiu.android:id/current_price"]'
     ).text
     self.driver.find_element_by_id(
         'com.xueqiu.android:id/action_close').click()
     price = float(price)
     assert_that(price, close_to(expected_price, expected_price * 0.2))
Esempio n. 59
0
def test_issue(encoding):
    """
    with encoding=UTF-8:
        File "/Users/jens/se/behave_main.unicode/tests/issues/test_issue0453.py", line 31, in problematic_step_impl
            raise Exception(u"по русски")
        Exception: \u043f\u043e \u0440\u0443\u0441\u0441\u043a\u0438

    with encoding=unicode_escape:
        File "/Users/jens/se/behave_main.unicode/tests/issues/test_issue0453.py", line 31, in problematic_step_impl
            raise Exception(u"по русски")
        Exception: по русски
    """
    context = None
    text2 = ""
    expected_text = u"по русски"
    try:
        problematic_step_impl(context)
    except Exception:
        text2 = traceback.format_exc()

    text3 = text(text2, encoding)
    print(u"EXCEPTION-TEXT: %s" % text3)
    assert_that(text3, contains_string(u'raise Exception(u"по русски"'))
    assert_that(text3, contains_string(u"Exception: по русски"))
Esempio n. 60
0
def test_snat():
    """
    Title: Tests SNAT on ping messages.

    Scenario:
    When: a VM sends ICMP echo request with ping command to a different subnet,
    Then: the router performs SNAT on the message according to the rule chain
          set to the router,
    And: the receiver VM should receive the ICMP echo packet, with src address
         NATted,
    And: the ping command succeeds.
    """
    sender = BM.get_iface_for_port('bridge-000-001', 2)
    receiver = BM.get_iface_for_port('bridge-000-002', 2)

    # Reset in-/out-bound filters.
    unset_filters('router-000-001')
    feed_receiver_mac(receiver)

    f1 = sender.ping4(receiver)
    # No SNAT configured. Should not receive SNATed messages.
    assert_that(
        receiver,
        should_NOT_receive('src host 172.16.1.100 and icmp', within_sec(5)))
    wait_on_futures([f1])

    # Set SNAT rule chains to the router
    set_filters('router-000-001', 'pre_filter_002', 'post_filter_002')

    f1 = sender.ping4(receiver)
    # The receiver should receive SNATed messages.
    f2 = async_assert_that(
        receiver, receives('src host 172.16.1.100 and icmp', within_sec(5)))
    f3 = async_assert_that(
        sender, receives('dst host 172.16.1.1 and icmp', within_sec(5)))
    wait_on_futures([f1, f2, f3])