def main(sc=None):
    """ Main function """
    try:
        if sc is None:
            sc = steelconnection.SConnect(SCM_REALM, SCM_USER, SCM_PW)
    except NameError:
        sc = steelconnection.SConnect()
    orgs = get_items(sc, 'orgs')
    sites = get_items(sc, 'sites')
    nodes = get_items(sc, 'nodes')
    uplinks_status = getstatus_items(sc, 'uplinks')
    nodes_status = getstatus_items(sc, 'nodes')
    org_details = get_org_details(orgs)
    node_details = get_node_details(sc, sites, nodes, org_details, uplinks_status, nodes_status)
    active_tunnels = get_items(sc, 'sshtunnel')
    nodes_list = list_nodes(node_details, active_tunnels)
    while True:
        selected_site = get_input("Type number to select site, or anything else to quit: ", len(nodes_list))
        uplink_list = select_node_detail(nodes_list[selected_site])
        # adding len+1 as the first index is the manually defined SCM SSH tunnel
        selected_ssh_option = get_input("Selection: ", len(uplink_list)+1)
        break
    if selected_ssh_option == 1:
        start_tunnel(sc, nodes_list[selected_site])
    else:
        start_ssh_direct(sc, uplink_list[selected_ssh_option])
Example #2
0
def test_received_not_ok_and_no_json():
    """Test SConnect.received when response.text is not json formatted."""
    responses.add(get_nonesuch)
    sc = steelconnection.SConnect('some.realm', connection_attempts=0)
    with pytest.raises(RuntimeError):
        sc.get('nonesuch')
    assert sc.received == 'Status: 404 - Not Found\nError: None'
Example #3
0
def test_scon_make_url():
    """Test SConnect.url method."""
    sc = steelconnection.SConnect(
        'NO.REALM', api_version='999', connection_attempts=0
    )
    url = sc.make_url('FAKE', 'PATH')
    assert url == 'https://NO.REALM/api/FAKE/999/PATH'
Example #4
0
def test_wait_for_ready_resource_gone():
    """Test _wait_for_ready returns None when image not available."""
    responses.add(get_image_status_ResourceGone)
    sc = steelconnection.SConnect('some.realm', connection_attempts=0)
    result = steelconnection.image_download._wait_for_ready(
        sc, 'node-12345', steelconnection.image_download._no_op)
    assert result is None
Example #5
0
def test_create_site(monkeypatch):
    if sys.version_info.major < 3:
        monkeypatch.setattr('__builtin__.raw_input', lambda x: username)
    else:
        monkeypatch.setattr('builtins.input', lambda x: username)
    monkeypatch.setattr('getpass.getpass', lambda x: password)
    import create_site
    create_site.scm_name = realm
    create_site.org_name = org_name
    create_site.new_site = {
        'name': 'pytest',
        'longname': 'pytest',
        'city': 'pytest',
        'country': 'US',
        'timezone': 'America/New_York',
    }
    sc = steelconnection.SConnect(realm, username, password)
    org = sc.lookup.org(org_name)
    site = sc.lookup.site(create_site.new_site['name'], org['id'])
    if site:
        sc.delete('site/' + site['id'])
    create_site.main()
    site = sc.lookup.site(create_site.new_site['name'], org['id'])
    assert site['id']
    for key in create_site.new_site:
        assert site[key] == create_site.new_site[key]
    sc.delete('site/' + site['id'])
    site = sc.lookup.site(create_site.new_site['name'], org['id'])
    assert site is None
Example #6
0
def test_scon_delete():
    """Test SConnect.delete method."""
    responses.add(delete_org)
    sc = steelconnection.SConnect("some.realm", connection_attempts=0)
    assert sc.delete("org/org-12345") == {}
    assert sc.response.ok
    assert "/api/scm.config/" in sc.response.url
Example #7
0
def test_scon_getstatus():
    """Test SConnect.getstatus method."""
    responses.add(getstatus_node)
    sc = steelconnection.SConnect('some.realm', connection_attempts=0)
    assert sc.getstatus('/node/node-12345') == db['nodes']['items'][0]
    assert sc.response.ok
    assert '/api/scm.reporting/' in sc.response.url
Example #8
0
def test_lookup_find_one_successful():
    responses.add(get_orgs)
    sc = steelconnection.SConnect("some.realm", connection_attempts=0)
    item = db["orgs"]["items"][0]
    value = item["name"]
    result = sc.lookup.find_one(domain="orgs", search={"name": value})
    assert result == item
def test_scon_str():
    """Test __str__ returns expected string."""
    responses.add(
        responses.GET,
        "https://some.realm/api/common/1.0/info",
        json={
            "sw_version": "1.23.4",
            "sw_build": "56",
            "scm_id": "ABC"
        },
        status=200,
    )
    realm = "some.realm"
    scm_version = "1.23.4_56"
    api_version = "1.0"
    pkg_version = steelconnection.__version__
    expected = "\n".join((
        "SteelConnection:",
        ">> realm: '{}'",
        ">> scm version: '{}'",
        ">> api version: '{}'",
        ">> package version: '{}'",
        ">> GET: https://some.realm/api/common/1.0/info",
        ">> Data Sent: None",
        ">> Status: 200 - OK",
        ">> Error: None",
    ))
    expected = expected.format(realm, scm_version, api_version, pkg_version)
    sc = steelconnection.SConnect(realm, "u", "p", api_version=api_version)
    assert str(sc) == expected
Example #10
0
def test_lookup_org():
    responses.add(get_orgs)
    sc = steelconnection.SConnect("some.realm", connection_attempts=0)
    item = db["orgs"]["items"][0]
    key = item["name"]
    result = sc.lookup.org(key)
    assert result == item
Example #11
0
def test_lookup_org():
    responses.add(get_orgs)
    sc = steelconnection.SConnect('some.realm', connection_attempts=0)
    item = db['orgs']['items'][0]
    key = item['name']
    result = sc.lookup.org(key)
    assert result == item
Example #12
0
def test_lookup_node():
    responses.add(get_nodes)
    sc = steelconnection.SConnect("some.realm", connection_attempts=0)
    item = db["nodes"]["items"][0]
    key = item["serial"]
    result = sc.lookup.node(key)
    assert result == item
Example #13
0
def test_create_object():
    sc = steelconnection.SConnect(REALM, REALM_ADMIN, PASSWORD)
    orgs = sc.get("orgs")
    assert orgs
    assert isinstance(orgs, list)
    assert isinstance(sc, steelconnection.SConnect)
    assert orgs[0]["id"]
Example #14
0
def test_create_site(monkeypatch):
    if sys.version_info.major < 3:
        monkeypatch.setattr("__builtin__.raw_input", lambda x: username)
    else:
        monkeypatch.setattr("builtins.input", lambda x: username)
    monkeypatch.setattr("getpass.getpass", lambda x: password)
    import create_site

    create_site.scm_name = realm
    create_site.org_name = org_name
    create_site.new_site = {
        "name": "pytest",
        "longname": "pytest",
        "city": "pytest",
        "country": "US",
        "timezone": "America/New_York",
    }
    sc = steelconnection.SConnect(realm, username, password)
    org = sc.lookup.org(org_name)
    site = sc.lookup.site(create_site.new_site["name"], org["id"])
    if site:
        sc.delete("site/" + site["id"])
    create_site.main()
    site = sc.lookup.site(create_site.new_site["name"], org["id"])
    assert site["id"]
    for key in create_site.new_site:
        assert site[key] == create_site.new_site[key]
    sc.delete("site/" + site["id"])
    site = sc.lookup.site(create_site.new_site["name"], org["id"])
    assert site is None
Example #15
0
def test_received_not_ok_and_non_dict_json():
    """Test SConnect.received when response.text is not json dict."""
    responses.add(get_nonesuch_non_dict)
    sc = steelconnection.SConnect("some.realm", connection_attempts=0)
    with pytest.raises(RuntimeError):
        sc.get("nonesuch")
    assert sc.received == "Status: 404 - Not Found\nError: None"
Example #16
0
def test_scon_getstatus():
    """Test SConnect.getstatus method."""
    responses.add(getstatus_node)
    sc = steelconnection.SConnect("some.realm", connection_attempts=0)
    assert sc.getstatus("/node/node-12345") == db["nodes"]["items"][0]
    assert sc.response.ok
    assert "/api/scm.reporting/" in sc.response.url
Example #17
0
def test_lookup_lookup_success():
    responses.add(get_orgs)
    sc = steelconnection.SConnect('some.realm', connection_attempts=0)
    item = db['orgs']['items'][0]
    key = item['name']
    result = sc.lookup._lookup(domain='orgs', value=key, key='name')
    assert result == item
Example #18
0
def test_scon_make_url():
    """Test SConnect.url method."""
    sc = steelconnection.SConnect("NO.REALM",
                                  api_version="999",
                                  connection_attempts=0)
    url = sc.make_url("FAKE", "PATH")
    assert url == "https://NO.REALM/api/FAKE/999/PATH"
Example #19
0
def test_scon_get_result_with_items():
    """_get_results should return a list when 'items' is in response."""
    responses.add(get_nodes)
    sc = steelconnection.SConnect("some.realm", connection_attempts=0)
    sc.get("nodes")
    assert isinstance(sc._get_result(sc.response), list)
    assert sc._get_result(sc.response) == db["nodes"]["items"]
Example #20
0
def test_lookup_node():
    responses.add(get_nodes)
    sc = steelconnection.SConnect('some.realm', connection_attempts=0)
    item = db['nodes']['items'][0]
    key = item['serial']
    result = sc.lookup.node(key)
    assert result == item
Example #21
0
def test_scon_get_result_no_items():
    """_get_results should return a dict when 'items' is not in response."""
    responses.add(get_node)
    sc = steelconnection.SConnect("some.realm", connection_attempts=0)
    sc.get("node/node-12345")
    assert isinstance(sc._get_result(sc.response), dict)
    assert sc._get_result(sc.response) == db["nodes"]["items"][0]
Example #22
0
def test_scon_put():
    """Test SConnect.put method."""
    responses.add(put_node)
    sc = steelconnection.SConnect('some.realm', connection_attempts=0)
    data = db['nodes']['items'][0]
    assert sc.put('node/node-12345', data=data) == data
    assert sc.response.ok
    assert '/api/scm.config/' in sc.response.url
Example #23
0
def test_scon_put():
    """Test SConnect.put method."""
    responses.add(put_node)
    sc = steelconnection.SConnect("some.realm", connection_attempts=0)
    data = db["nodes"]["items"][0]
    assert sc.put("node/node-12345", data=data) == data
    assert sc.response.ok
    assert "/api/scm.config/" in sc.response.url
Example #24
0
def test_lookup_wan():
    responses.add(get_orgs)
    responses.add(get_wans_from_org)
    sc = steelconnection.SConnect("some.realm", connection_attempts=0)
    item = db["wans"]["items"][0]
    key = item["name"]
    org_id = item["org"]
    result = sc.lookup.wan(key, orgid=org_id)
    assert result == item
Example #25
0
def test_scon_get_result_octet_stream():
    """Test SConnect._get_result method."""
    responses.add(get_image)
    sc = steelconnection.SConnect('some.realm', connection_attempts=0)
    sc.get('image')
    assert sc._get_result(sc.response) == {'status': ' '.join((
        "Binary data returned.",
        "Use '.savefile(filename)' method or access using '.response.content'."
    ))}
Example #26
0
def test_scon_get_result_not_ok():
    """Test SConnect.__get_result method."""
    responses.add(get_nonesuch)
    sc = steelconnection.SConnect("some.realm", connection_attempts=0)
    try:
        sc.get("nonesuch")
    except RuntimeError:
        pass
    assert sc._get_result(sc.response) is None
Example #27
0
def test_lookup_site():
    responses.add(get_orgs)
    responses.add(get_sites_from_org)
    sc = steelconnection.SConnect('some.realm', connection_attempts=0)
    item = db['sites']['items'][0]
    key = item['name']
    org_id = item['org']
    result = sc.lookup.site(key, orgid=org_id)
    assert result == item
Example #28
0
def test_raise_exception_without_exceptions():
    """_raise_exception should raise the correct exceptions based on status."""
    sc = steelconnection.SConnect("sc", connection_attempts=0, on_error=False)
    sc.response = fake_requests.Fake_Response("", 502, {})
    try:
        result = sc._raise_exception(sc.response)
    except BaseException:
        assert False
    else:
        assert result is None
Example #29
0
def test_exit_when_raise_exception_with_exit_on_error(capsys):
    sc = steelconnection.SConnect("sc", connection_attempts=0, on_error="exit")
    sc.response = fake_requests.Fake_Response("", 502, {})
    with pytest.raises(SystemExit) as pytest_wrapped_e:
        sc._raise_exception(sc.response)
    captured = capsys.readouterr()
    assert captured.err == (
        "Status: 502 - Failed\nError: None\nFAKE: \nData Sent: '{}'\n")
    assert pytest_wrapped_e.type == SystemExit
    assert pytest_wrapped_e.value.code == 1
Example #30
0
def test_clear_location_fields():
    sc = steelconnection.SConnect(realm, username, password)
    org = sc.lookup.org(org_name)
    assert org["id"]
    nodes = sc.get("org/" + org["id"] + "/nodes")
    assert nodes
    for node in nodes:
        node["location"] = None
        response = sc.put("node/" + node["id"], data=node)
        assert response["location"] is None