Exemple #1
0
def test_no_incompatible_ospf_sessions():
    """Confirm no-incompatible-ospf-sessions assert passes and fails as expected when specifying a session."""
    bf = Session(load_questions=False)
    with patch.object(bf.q, 'ospfSessionCompatibility',
                      create=True) as ospfSessionCompatibility:
        # Test success
        ospfSessionCompatibility.return_value = MockQuestion()
        assert_no_incompatible_ospf_sessions(nodes='nodes',
                                             remote_nodes='remote_nodes',
                                             session=bf)
        ospfSessionCompatibility.assert_called_with(nodes='nodes',
                                                    remote_nodes='remote_nodes',
                                                    statuses=UNESTABLISHED_OSPF_SESSION_STATUS_SPEC)
        # Test failure
        mock_df = DataFrame.from_records([{'Session': 'found', 'More': 'data'}])
        ospfSessionCompatibility.return_value = MockQuestion(
            MockTableAnswer(mock_df))
        with pytest.raises(BatfishAssertException) as excinfo:
            assert_no_incompatible_ospf_sessions(nodes='nodes',
                                                 remote_nodes='remote_nodes',
                                                 session=bf)
        # Ensure found answer is printed
        assert mock_df.to_string() in str(excinfo.value)
        ospfSessionCompatibility.assert_called_with(nodes='nodes',
                                                    remote_nodes='remote_nodes',
                                                    statuses=UNESTABLISHED_OSPF_SESSION_STATUS_SPEC)
Exemple #2
0
def test_execute_request_params():
    session = Session(load_questions=False)

    # Unmodified work item
    work_item = WorkItem(session)
    witem = __execute_and_return_request_params(work_item, session)
    assert "TESTARG" not in witem

    session.additional_args["TESTARG"] = "addl"

    # Work item with additional args
    work_item = WorkItem(session)
    witem = __execute_and_return_request_params(work_item, session)
    assert witem.get("TESTARG") == "addl"

    # Work item with additional args and extra args
    work_item = WorkItem(session)
    witem = __execute_and_return_request_params(
        work_item, session, extra_args={"TESTARG": "extra"})
    assert witem.get("TESTARG") == "extra"

    # Confirm additional args not messed up
    work_item = WorkItem(session)
    witem = __execute_and_return_request_params(work_item, session)
    assert witem.get("TESTARG") == "addl"
Exemple #3
0
def test_filter_permits_from_session():
    """Confirm filter-permits assert passes and fails as expected when called from a session."""
    headers = HeaderConstraints(srcIps='1.1.1.1')
    bf = Session(load_questions=False)
    with patch.object(bf.q, 'searchFilters',
                      create=True) as mock_search_filters:
        # Test success
        mock_search_filters.return_value = MockQuestion()
        bf.asserts.assert_filter_permits('filter', headers)
        mock_search_filters.assert_called_with(filters='filter',
                                               headers=headers,
                                               action='deny')
        # Test failure; also test that startLocation is passed through
        mock_df = DataFrame.from_records([{'Flow': 'found', 'More': 'data'}])
        mock_search_filters.return_value = MockQuestion(
            MockTableAnswer(mock_df))
        with pytest.raises(BatfishAssertException) as excinfo:
            bf.asserts.assert_filter_permits('filter', headers,
                                             startLocation='Ethernet1')
        # Ensure found answer is printed
        assert mock_df.to_string() in str(excinfo.value)
        mock_search_filters.assert_called_with(filters='filter',
                                               headers=headers,
                                               startLocation='Ethernet1',
                                               action='deny')
Exemple #4
0
def test_flows_succeed_from_session():
    """Confirm flows-succeed assert passes and fails as expected when called from a session."""
    startLocation = "node1"
    headers = HeaderConstraints(srcIps='1.1.1.1')
    bf = Session(load_questions=False)
    with patch.object(bf.q, 'reachability', create=True) as reachability:
        # Test success
        reachability.return_value = MockQuestion()
        bf.asserts.assert_flows_succeed(startLocation, headers)
        reachability.assert_called_with(
            pathConstraints=PathConstraints(startLocation=startLocation),
            headers=headers,
            actions='failure')
        # Test failure
        mock_df = DataFrame.from_records([{'Flow': 'found', 'More': 'data'}])
        reachability.return_value = MockQuestion(
            MockTableAnswer(mock_df))
        with pytest.raises(BatfishAssertException) as excinfo:
            bf.asserts.assert_flows_succeed(startLocation, headers)
        # Ensure found answer is printed
        assert mock_df.to_string() in str(excinfo.value)
        reachability.assert_called_with(
            pathConstraints=PathConstraints(startLocation=startLocation),
            headers=headers,
            actions='failure')
Exemple #5
0
def test_no_incompatible_bgp_sessions():
    """Confirm no-incompatible-bgp-sessions assert passes and fails as expected when specifying a session."""
    bf = Session(load_questions=False)
    with patch.object(bf.q, "bgpSessionCompatibility",
                      create=True) as bgpSessionCompatibility:
        # Test success
        bgpSessionCompatibility.return_value = MockQuestion()
        assert_no_incompatible_bgp_sessions(nodes="nodes",
                                            remote_nodes="remote_nodes",
                                            status=".*",
                                            session=bf)
        bgpSessionCompatibility.assert_called_with(nodes="nodes",
                                                   remote_nodes="remote_nodes",
                                                   status=".*")
        # Test failure
        mock_df = DataFrame.from_records([{
            "Session": "found",
            "More": "data"
        }])
        bgpSessionCompatibility.return_value = MockQuestion(
            MockTableAnswer(mock_df))
        with pytest.raises(BatfishAssertException) as excinfo:
            assert_no_incompatible_bgp_sessions(nodes="nodes",
                                                remote_nodes="remote_nodes",
                                                status=".*",
                                                session=bf)
        # Ensure found answer is printed
        assert mock_df.to_string() in str(excinfo.value)
        bgpSessionCompatibility.assert_called_with(nodes="nodes",
                                                   remote_nodes="remote_nodes",
                                                   status=".*")
Exemple #6
0
def test_print_workstatus_fresh_task(caplog):
    session = Session(load_questions=False)
    session.stale_timeout = 5
    nowFunction = lambda tzinfo: datetime.datetime(
        2017, 12, 20, 0, 0, 0, 0, tzinfo=tzinfo
    )
    workStatus = "TEST"
    taskDetails = json.dumps(
        {
            "obtained": "2017-12-20 00:00:00 UTC",
            "batches": [
                {
                    "completed": 0,
                    "description": "Fooing the bar",
                    "size": 0,
                    "startDate": "2017-12-20 00:00:00 UTC",
                }
            ],
        }
    )
    _print_work_status_helper(session, workStatus, taskDetails, nowFunction)
    assert "status: TEST" in caplog.text
    assert (
        ".... {obtained} Fooing the bar".format(
            obtained=_print_timestamp(
                _parse_timestamp(json.loads(taskDetails)["obtained"])
            )
        )
        in caplog.text
    )
Exemple #7
0
def test_no_incompatible_ospf_sessions_from_session():
    """Confirm no-incompatible-ospf-sessions assert passes and fails as expected when called from a session."""
    bf = Session(load_questions=False)
    with patch.object(bf.q, "ospfSessionCompatibility",
                      create=True) as ospfSessionCompatibility:
        # Test success
        ospfSessionCompatibility.return_value = MockQuestion()
        bf.asserts.assert_no_incompatible_ospf_sessions(
            nodes="nodes", remote_nodes="remote_nodes")
        ospfSessionCompatibility.assert_called_with(
            nodes="nodes",
            remote_nodes="remote_nodes",
            statuses=UNESTABLISHED_OSPF_SESSION_STATUS_SPEC,
        )
        # Test failure
        mock_df = DataFrame.from_records([{
            "Session": "found",
            "More": "data"
        }])
        ospfSessionCompatibility.return_value = MockQuestion(
            MockTableAnswer(mock_df))
        with pytest.raises(BatfishAssertException) as excinfo:
            bf.asserts.assert_no_incompatible_ospf_sessions(
                nodes="nodes", remote_nodes="remote_nodes")
        # Ensure found answer is printed
        assert mock_df.to_string() in str(excinfo.value)
        ospfSessionCompatibility.assert_called_with(
            nodes="nodes",
            remote_nodes="remote_nodes",
            statuses=UNESTABLISHED_OSPF_SESSION_STATUS_SPEC,
        )
Exemple #8
0
def test_filter_denies():
    """Confirm filter-denies assert passes and fails as expected when specifying a session."""
    headers = HeaderConstraints(srcIps="1.1.1.1")
    bf = Session(load_questions=False)
    with patch.object(bf.q, "searchFilters",
                      create=True) as mock_search_filters:
        # Test success
        mock_search_filters.return_value = MockQuestion()
        assert_filter_denies("filter", headers, session=bf)
        mock_search_filters.assert_called_with(filters="filter",
                                               headers=headers,
                                               action="permit")
        # Test failure; also test that startLocation is passed through
        mock_df = DataFrame.from_records([{"Flow": "found", "More": "data"}])
        mock_search_filters.return_value = MockQuestion(
            MockTableAnswer(mock_df))
        with pytest.raises(BatfishAssertException) as excinfo:
            assert_filter_denies("filter",
                                 headers,
                                 startLocation="Ethernet1",
                                 session=bf)
        # Ensure found answer is printed
        assert mock_df.to_string() in str(excinfo.value)
        mock_search_filters.assert_called_with(
            filters="filter",
            headers=headers,
            startLocation="Ethernet1",
            action="permit",
        )
Exemple #9
0
def test_no_unestablished_bgp_sessions():
    """Confirm no-uncompatible-bgp-sessions assert passes and fails as expected when specifying a session."""
    bf = Session(load_questions=False)
    with patch.object(bf.q, 'bgpSessionStatus',
                      create=True) as bgpSessionStatus:
        # Test success
        bgpSessionStatus.return_value = MockQuestion()
        assert_no_unestablished_bgp_sessions(nodes='nodes',
                                             remote_nodes='remote_nodes',
                                             session=bf)
        bgpSessionStatus.assert_called_with(nodes='nodes',
                                            remote_nodes='remote_nodes',
                                            status="NOT_ESTABLISHED")
        # Test failure
        mock_df = DataFrame.from_records([{
            'Session': 'found',
            'More': 'data'
        }])
        bgpSessionStatus.return_value = MockQuestion(MockTableAnswer(mock_df))
        with pytest.raises(BatfishAssertException) as excinfo:
            assert_no_unestablished_bgp_sessions(nodes='nodes',
                                                 remote_nodes='remote_nodes',
                                                 session=bf)
        # Ensure found answer is printed
        assert mock_df.to_string() in str(excinfo.value)
        bgpSessionStatus.assert_called_with(nodes='nodes',
                                            remote_nodes='remote_nodes',
                                            status="NOT_ESTABLISHED")
def test_execute_request_params(logger):
    session = Session(logger)

    # Unmodified work item
    work_item = WorkItem(session)
    witem = __execute_and_return_request_params(work_item, session)
    assert 'TESTARG' not in witem

    session.additionalArgs['TESTARG'] = 'addl'

    # Work item with additional args
    work_item = WorkItem(session)
    witem = __execute_and_return_request_params(work_item, session)
    assert witem.get('TESTARG') == 'addl'

    # Work item with additional args and extra args
    work_item = WorkItem(session)
    witem = __execute_and_return_request_params(
        work_item, session, extra_args={'TESTARG': 'extra'})
    assert witem.get('TESTARG') == 'extra'

    # Confirm additional args not messed up
    work_item = WorkItem(session)
    witem = __execute_and_return_request_params(work_item, session)
    assert witem.get('TESTARG') == 'addl'
Exemple #11
0
def test_get_facts_questions():
    """Test that get facts calls the right questions, passing through the right args."""
    bf = Session(load_questions=False)
    nodes = 'foo'
    with patch.object(bf.q,
                      'nodeProperties',
                      create=True) as mock_node, \
            patch.object(bf.q,
                         'interfaceProperties',
                         create=True) as mock_iface, \
            patch.object(bf.q,
                         'bgpPeerConfiguration',
                         create=True) as mock_peers, \
            patch.object(bf.q,
                         'bgpProcessConfiguration',
                         create=True) as mock_proc:
        mock_node.return_value = MockQuestion(MockTableAnswer())
        mock_iface.return_value = MockQuestion(MockTableAnswer())
        mock_proc.return_value = MockQuestion(MockTableAnswer())
        mock_peers.return_value = MockQuestion(MockTableAnswer())
        get_facts(bf, nodes)

        mock_node.assert_called_with(nodes=nodes)
        mock_iface.assert_called_with(nodes=nodes)
        mock_proc.assert_called_with(nodes=nodes)
        mock_peers.assert_called_with(nodes=nodes)
Exemple #12
0
def test_get_facts_questions():
    """Test that get facts calls the right questions, passing through the right args."""
    bf = Session(load_questions=False)
    nodes = "foo"
    with patch.object(
            bf.q, "nodeProperties", create=True) as mock_node, patch.object(
                bf.q, "interfaceProperties",
                create=True) as mock_iface, patch.object(
                    bf.q, "bgpPeerConfiguration",
                    create=True) as mock_peers, patch.object(
                        bf.q, "bgpProcessConfiguration",
                        create=True) as mock_proc, patch.object(
                            bf.q, "ospfProcessConfiguration",
                            create=True) as mock_ospf_proc, patch.object(
                                bf.q, "ospfAreaConfiguration",
                                create=True) as mock_ospf_area, patch.object(
                                    bf.q,
                                    "ospfInterfaceConfiguration",
                                    create=True) as mock_ospf_iface:
        mock_node.return_value = MockQuestion(MockTableAnswer)
        mock_iface.return_value = MockQuestion(MockTableAnswer)
        mock_proc.return_value = MockQuestion(MockTableAnswer)
        mock_peers.return_value = MockQuestion(MockTableAnswer)
        mock_ospf_proc.return_value = MockQuestion(MockTableAnswer)
        mock_ospf_area.return_value = MockQuestion(MockTableAnswer)
        mock_ospf_iface.return_value = MockQuestion(MockTableAnswer)
        get_facts(bf, nodes)

        mock_node.assert_called_with(nodes=nodes)
        mock_iface.assert_called_with(nodes=nodes)
        mock_proc.assert_called_with(nodes=nodes)
        mock_peers.assert_called_with(nodes=nodes)
        mock_ospf_proc.assert_called_with(nodes=nodes)
        mock_ospf_area.assert_called_with(nodes=nodes)
        mock_ospf_iface.assert_called_with(nodes=nodes)
Exemple #13
0
def test_no_unestablished_bgp_sessions_from_session():
    """Confirm no-uncompatible-bgp-sessions assert passes and fails as expected when called from a session."""
    bf = Session(load_questions=False)
    with patch.object(bf.q, "bgpSessionStatus",
                      create=True) as bgpSessionStatus:
        # Test success
        bgpSessionStatus.return_value = MockQuestion()
        bf.asserts.assert_no_unestablished_bgp_sessions(
            nodes="nodes", remote_nodes="remote_nodes")
        bgpSessionStatus.assert_called_with(nodes="nodes",
                                            remote_nodes="remote_nodes",
                                            status="NOT_ESTABLISHED")
        # Test failure
        mock_df = DataFrame.from_records([{
            "Session": "found",
            "More": "data"
        }])
        bgpSessionStatus.return_value = MockQuestion(MockTableAnswer(mock_df))
        with pytest.raises(BatfishAssertException) as excinfo:
            bf.asserts.assert_no_unestablished_bgp_sessions(
                nodes="nodes", remote_nodes="remote_nodes")
        # Ensure found answer is printed
        assert mock_df.to_string() in str(excinfo.value)
        bgpSessionStatus.assert_called_with(nodes="nodes",
                                            remote_nodes="remote_nodes",
                                            status="NOT_ESTABLISHED")
Exemple #14
0
def test_print_workstatus_old_task_subtasks(caplog):
    session = Session(load_questions=False)
    session.stale_timeout = 5
    nowFunction = lambda tzinfo: datetime.datetime(
        2017, 12, 20, 0, 0, 0, 0, tzinfo=tzinfo
    )
    workStatus = "TEST"
    taskDetails = json.dumps(
        {
            "obtained": "2016-11-22 10:43:21 UTC",
            "batches": [
                {
                    "completed": 1,
                    "description": "Fooing the bar",
                    "size": 2,
                    "startDate": "2016-11-22 10:43:22 UTC",
                }
            ],
        }
    )
    _print_work_status_helper(session, workStatus, taskDetails, nowFunction)
    assert "status: TEST" in caplog.text
    assert (
        ".... {obtained} Fooing the bar 1 / 2. (1y27d13:16:39 elapsed)".format(
            obtained=_print_timestamp(
                _parse_timestamp(json.loads(taskDetails)["obtained"])
            )
        )
        in caplog.text
    )
Exemple #15
0
def test_flows_succeed():
    """Confirm flows-succeed assert passes and fails as expected when specifying a session."""
    startLocation = "node1"
    headers = HeaderConstraints(srcIps="1.1.1.1")
    bf = Session(load_questions=False)
    with patch.object(bf.q, "reachability", create=True) as reachability:
        # Test success
        reachability.return_value = MockQuestion()
        assert_flows_succeed(startLocation, headers, session=bf)
        reachability.assert_called_with(
            pathConstraints=PathConstraints(startLocation=startLocation),
            headers=headers,
            actions="failure",
        )
        # Test failure
        mock_df = DataFrame.from_records([{"Flow": "found", "More": "data"}])
        reachability.return_value = MockQuestion(MockTableAnswer(mock_df))
        with pytest.raises(BatfishAssertException) as excinfo:
            assert_flows_succeed(startLocation, headers, session=bf)
        # Ensure found answer is printed
        assert mock_df.to_string() in str(excinfo.value)
        reachability.assert_called_with(
            pathConstraints=PathConstraints(startLocation=startLocation),
            headers=headers,
            actions="failure",
        )
Exemple #16
0
def test_no_incompatible_bgp_sessions_from_session():
    """Confirm no-incompatible-bgp-sessions assert passes and fails as expected when called from a session."""
    bf = Session(load_questions=False)
    with patch.object(bf.q, 'bgpSessionCompatibility',
                      create=True) as bgpSessionCompatibility:
        # Test success
        bgpSessionCompatibility.return_value = MockQuestion()
        bf.asserts.assert_no_incompatible_bgp_sessions(nodes='nodes',
                                                       remote_nodes='remote_nodes',
                                                       status='.*')
        bgpSessionCompatibility.assert_called_with(nodes='nodes',
                                                   remote_nodes='remote_nodes',
                                                   status='.*')
        # Test failure
        mock_df = DataFrame.from_records([{'Session': 'found', 'More': 'data'}])
        bgpSessionCompatibility.return_value = MockQuestion(
            MockTableAnswer(mock_df))
        with pytest.raises(BatfishAssertException) as excinfo:
            bf.asserts.assert_no_incompatible_bgp_sessions(nodes='nodes',
                                                           remote_nodes='remote_nodes',
                                                           status='.*')
        # Ensure found answer is printed
        assert mock_df.to_string() in str(excinfo.value)
        bgpSessionCompatibility.assert_called_with(nodes='nodes',
                                                   remote_nodes='remote_nodes',
                                                   status='.*')
Exemple #17
0
def test_get_facts_questions_specific_snapshot():
    """Test that get facts calls the right questions, passing through the right args when a snapshot is specified."""
    bf = Session(load_questions=False)
    nodes = "foo"
    with patch.object(
            bf.q, "nodeProperties", create=True) as mock_node, patch.object(
                bf.q, "interfaceProperties",
                create=True) as mock_iface, patch.object(
                    bf.q, "bgpPeerConfiguration",
                    create=True) as mock_peers, patch.object(
                        bf.q, "bgpProcessConfiguration",
                        create=True) as mock_proc, patch.object(
                            bf.q, "ospfProcessConfiguration",
                            create=True) as mock_ospf_proc, patch.object(
                                bf.q, "ospfAreaConfiguration",
                                create=True) as mock_ospf_area, patch.object(
                                    bf.q,
                                    "ospfInterfaceConfiguration",
                                    create=True) as mock_ospf_iface:
        # Setup mock answers for each underlying question
        mock_node_a = Mock(return_value=MockTableAnswer())
        mock_iface_a = Mock(return_value=MockTableAnswer())
        mock_proc_a = Mock(return_value=MockTableAnswer())
        mock_peers_a = Mock(return_value=MockTableAnswer())
        mock_ospf_proc_a = Mock(return_value=MockTableAnswer())
        mock_ospf_area_a = Mock(return_value=MockTableAnswer())
        mock_ospf_iface_a = Mock(return_value=MockTableAnswer())

        # Setup mock questions for all underlying questions
        mock_node.return_value = MockQuestion(mock_node_a)
        mock_iface.return_value = MockQuestion(mock_iface_a)
        mock_proc.return_value = MockQuestion(mock_proc_a)
        mock_peers.return_value = MockQuestion(mock_peers_a)
        mock_ospf_proc.return_value = MockQuestion(mock_ospf_proc_a)
        mock_ospf_area.return_value = MockQuestion(mock_ospf_area_a)
        mock_ospf_iface.return_value = MockQuestion(mock_ospf_iface_a)

        get_facts(bf, nodes, snapshot="snapshot")

        # Make sure questions were all called with expected params
        mock_node.assert_called_with(nodes=nodes)
        mock_iface.assert_called_with(nodes=nodes)
        mock_proc.assert_called_with(nodes=nodes)
        mock_peers.assert_called_with(nodes=nodes)
        mock_ospf_proc.assert_called_with(nodes=nodes)
        mock_ospf_area.assert_called_with(nodes=nodes)
        mock_ospf_iface.assert_called_with(nodes=nodes)

        # Make sure answer functions were all called with expected params
        mock_node_a.assert_called_with(snapshot="snapshot")
        mock_iface_a.assert_called_with(snapshot="snapshot")
        mock_proc_a.assert_called_with(snapshot="snapshot")
        mock_peers_a.assert_called_with(snapshot="snapshot")
        mock_ospf_proc_a.assert_called_with(snapshot="snapshot")
        mock_ospf_area_a.assert_called_with(snapshot="snapshot")
        mock_ospf_iface_a.assert_called_with(snapshot="snapshot")
Exemple #18
0
def test_run_assertion():
    """Confirm running passing assertion results in a passing message."""
    bf = Session(load_questions=False)
    assertion = {
        'name': 'assert_name',
        'type': 'assert_no_undefined_references',
    }
    with patch.object(bf.q, 'undefinedReferences', create=True) as mock_undef:
        mock_undef.return_value = MockQuestion(MockTableAnswer())
        assert run_assertion(bf, assertion) == ASSERT_PASS_MESSAGE
Exemple #19
0
def session():
    s = Session()
    # Snapshot which can be referenced by name
    other_name = s.init_snapshot(join(_this_dir, 'snapshots',
                                      'fact_snapshot2'))
    # Current snapshot
    name = s.init_snapshot(join(_this_dir, 'snapshots', 'fact_snapshot'))
    yield s
    s.delete_snapshot(name)
    s.delete_snapshot(other_name)
Exemple #20
0
 def __init__(self, snapshot_dir, host="localhost"):
     if not os.path.exists(snapshot_dir):
         raise ValueError(
             "Snapshot directory '{}' does not exist".format(snapshot_dir))
     self._bf = Session(host=host)
     self._bf.set_network("manrs-test")
     self._bf.init_snapshot(snapshot_dir, name="manrs-test", overwrite=True)
     self.node_properties = self._bf.q.nodeProperties().answer()
     self.interface_properties = self._bf.q.interfaceProperties().answer()
     self.bgp_peer_properties = self._bf.q.bgpPeerConfiguration().answer()
Exemple #21
0
def test_upload_diagnostics_metadata():
    """Confirm metadata file is generated with correct content."""
    metadata = {"test_key1": "test_value", "test_key2": 1234}
    out_dir = upload_diagnostics(
        Session(load_questions=False), metadata, dry_run=True, questions=[]
    )

    with open(os.path.join(out_dir, METADATA_FILENAME)) as f:
        contents = json.loads(f.read())

    assert contents == metadata
Exemple #22
0
def session():
    s = Session()
    # Snapshot which can be referenced by name
    other_name = s.init_snapshot(
        join(_this_dir, "snapshots", "fact_snapshot2"), _PREVIOUS_SNAPSHOT)
    # Current snapshot
    name = s.init_snapshot(join(_this_dir, "snapshots", "fact_snapshot"),
                           _CURRENT_SNAPSHOT)
    yield s
    s.delete_snapshot(name)
    s.delete_snapshot(other_name)
Exemple #23
0
def test_no_forwarding_loops():
    """Confirm no-forwarding-loops assert passes and fails as expected when specifying a session."""
    bf = Session(load_questions=False)
    with patch.object(bf.q, 'detectLoops', create=True) as detectLoops:
        # Test success
        detectLoops.return_value = MockQuestion()
        assert_no_forwarding_loops(session=bf)
        # Test failure
        mock_df = DataFrame.from_records([{'Loop': 'found', 'More': 'data'}])
        detectLoops.return_value = MockQuestion(MockTableAnswer(mock_df))
        with pytest.raises(BatfishAssertException) as excinfo:
            assert_no_forwarding_loops(session=bf)
        # Ensure found answer is printed
        assert mock_df.to_string() in str(excinfo.value)
Exemple #24
0
def test_no_forwarding_loops_from_session():
    """Confirm no-forwarding-loops assert passes and fails as expected when called from a session."""
    bf = Session(load_questions=False)
    with patch.object(bf.q, "detectLoops", create=True) as detectLoops:
        # Test success
        detectLoops.return_value = MockQuestion()
        bf.asserts.assert_no_forwarding_loops()
        # Test failure
        mock_df = DataFrame.from_records([{"Loop": "found", "More": "data"}])
        detectLoops.return_value = MockQuestion(MockTableAnswer(mock_df))
        with pytest.raises(BatfishAssertException) as excinfo:
            bf.asserts.assert_no_forwarding_loops()
        # Ensure found answer is printed
        assert mock_df.to_string() in str(excinfo.value)
Exemple #25
0
def test_run_assertion_fail():
    """Confirm running failing assertion results in a message indicating failure."""
    bf = Session(load_questions=False)
    assertion = {
        'name': 'assert_name',
        'type': 'assert_no_undefined_references',
    }
    with patch.object(bf.q, 'undefinedReferences', create=True) as mock_undef:
        mock_undef.return_value = MockQuestion(
            MockTableAnswer(DataFrame.from_records([{
                'Undef': 'something'
            }])))
        result = run_assertion(bf, assertion)
    assert ASSERT_PASS_MESSAGE not in result
    assert 'Found undefined reference(s), when none were expected' in result
Exemple #26
0
def test_no_undefined_references_from_session():
    """Confirm no-undefined-references assert passes and fails as expected when called from a session."""
    bf = Session(load_questions=False)
    with patch.object(bf.q, 'undefinedReferences',
                      create=True) as undefinedReferences:
        # Test success
        undefinedReferences.return_value = MockQuestion()
        bf.asserts.assert_no_undefined_references()
        # Test failure
        mock_df = DataFrame.from_records(
            [{'UndefRef': 'found', 'More': 'data'}])
        undefinedReferences.return_value = MockQuestion(
            MockTableAnswer(mock_df))
        with pytest.raises(BatfishAssertException) as excinfo:
            bf.asserts.assert_no_undefined_references()
        # Ensure found answer is printed
        assert mock_df.to_string() in str(excinfo.value)
Exemple #27
0
def test_filter_has_no_unreachable_lines_from_session():
    """Confirm filter-has-no-unreachable-lines assert passes and fails as expected when called from a session."""
    filters = "filter1"
    bf = Session(load_questions=False)
    with patch.object(bf.q, 'filterLineReachability',
                      create=True) as filterLineReachability:
        # Test success
        filterLineReachability.return_value = MockQuestion()
        bf.asserts.assert_filter_has_no_unreachable_lines(filters=filters)
        # Test failure
        mock_df = DataFrame.from_records(
            [{'UnreachableLine': 'found', 'More': 'data'}])
        filterLineReachability.return_value = MockQuestion(
            MockTableAnswer(mock_df))
        with pytest.raises(BatfishAssertException) as excinfo:
            bf.asserts.assert_filter_has_no_unreachable_lines(filters=filters)
        # Ensure found answer is printed
        assert mock_df.to_string() in str(excinfo.value)
Exemple #28
0
def test_no_undefined_references():
    """Confirm no-undefined-references assert passes and fails as expected when specifying a session."""
    bf = Session(load_questions=False)
    with patch.object(bf.q, "undefinedReferences",
                      create=True) as undefinedReferences:
        # Test success
        undefinedReferences.return_value = MockQuestion()
        assert_no_undefined_references(session=bf)
        # Test failure
        mock_df = DataFrame.from_records([{
            "UndefRef": "found",
            "More": "data"
        }])
        undefinedReferences.return_value = MockQuestion(
            MockTableAnswer(mock_df))
        with pytest.raises(BatfishAssertException) as excinfo:
            assert_no_undefined_references(session=bf)
        # Ensure found answer is printed
        assert mock_df.to_string() in str(excinfo.value)
Exemple #29
0
def test_filter_has_no_unreachable_lines():
    """Confirm filter-has-no-unreachable-lines assert passes and fails as expected when specifying a session."""
    filters = "filter1"
    bf = Session(load_questions=False)
    with patch.object(bf.q, "filterLineReachability",
                      create=True) as filterLineReachability:
        # Test success
        filterLineReachability.return_value = MockQuestion()
        assert_filter_has_no_unreachable_lines(filters=filters, session=bf)
        # Test failure
        mock_df = DataFrame.from_records([{
            "UnreachableLine": "found",
            "More": "data"
        }])
        filterLineReachability.return_value = MockQuestion(
            MockTableAnswer(mock_df))
        with pytest.raises(BatfishAssertException) as excinfo:
            assert_filter_has_no_unreachable_lines(filters=filters, session=bf)
        # Ensure found answer is printed
        assert mock_df.to_string() in str(excinfo.value)
Exemple #30
0
def test_get_question_object():
    """Confirm _get_question_object identifies the correct question object based on the specified session and the questions it contains."""
    # Session contains the question we're searching for
    bf = Session(load_questions=False)
    with patch.object(bf.q, 'qName', create=True):
        assert bf.q == _get_question_object(bf, 'qName')

    # Session does not contain the question we're searching for, but bfq does
    with patch.object(bfq, 'qName', create=True):
        assert bfq == _get_question_object(bf, 'qName')

    # No Session specified, but bfq contains the question we're searching for
    with patch.object(bfq, 'qName', create=True):
        assert bfq == _get_question_object(None, 'qName')

    # Cannot find the question we're searching for
    with patch.object(bf.q, 'otherName', create=True):
        with patch.object(bfq, 'otherOtherName', create=True):
            with pytest.raises(BatfishException) as err:
                _get_question_object(bf, 'qName')
            assert 'qName question was not found' in str(err.value)