示例#1
0
def test_httpbin():
    client = EnterpriseSearch("https://httpbin.org:443")
    resp = client.perform_request("GET", "/anything")
    assert resp.meta.status == 200
    assert re.match(
        r"^ent=8[.0-9]+p?,py=[.0-9]+p?,t=[.0-9]+p?,ur=[.0-9]+p?$",
        resp.body["headers"]["X-Elastic-Client-Meta"],
    )
    assert resp.body["headers"]["User-Agent"].startswith(
        "enterprise-search-python/")
def test_http_auth_per_request_override():
    client = EnterpriseSearch(http_auth="bad-token", node_class=DummyNode)
    with warnings.catch_warnings(record=True) as w:
        client.get_version(http_auth=("user", "password"))

    assert len(w) == 1 and str(w[0].message) == (
        "Passing transport options in the API method is deprecated. "
        "Use 'EnterpriseSearch.options()' instead.")

    calls = client.transport.node_pool.get().calls
    assert len(calls) == 1
    assert calls[-1][1]["headers"][
        "Authorization"] == "Basic dXNlcjpwYXNzd29yZA=="
示例#3
0
def test_sub_client_auth():
    client = EnterpriseSearch(node_class=DummyNode, meta_header=False)

    # Using options on individual clients
    client.options(bearer_auth="enterprise-search").perform_request(
        "GET", "/enterprise-search")
    client.app_search.options(bearer_auth="app-search").perform_request(
        "GET", "/app-search")
    client.workplace_search.options(
        bearer_auth="workplace-search").perform_request(
            "GET", "/workplace-search")

    # Authenticating doesn't modify other clients
    client.options(bearer_auth="not-app-search").app_search.perform_request(
        "GET", "/not-app-search")
    client.options(
        bearer_auth="not-workplace-search").workplace_search.perform_request(
            "GET", "/not-workplace-search")

    # The Authorziation header gets hidden
    calls = client.transport.node_pool.get().calls
    headers = [(target, kwargs["headers"].get("Authorization", None))
               for ((_, target), kwargs) in calls]

    assert headers == [
        ("/enterprise-search", "Bearer enterprise-search"),
        ("/app-search", "Bearer app-search"),
        ("/workplace-search", "Bearer workplace-search"),
        ("/not-app-search", None),
        ("/not-workplace-search", None),
    ]
def test_request_timeout(request_timeout):
    client = EnterpriseSearch(connection_class=DummyConnection, meta_header=False)
    client.get_version(request_timeout=request_timeout)

    calls = client.transport.get_connection().calls
    assert calls == [
        (
            ("GET", "/api/ent/v1/internal/version", None),
            {
                "headers": {"user-agent": client._user_agent_header},
                "ignore_status": (),
                "request_timeout": request_timeout,
            },
        )
    ]
def test_request_timeout(request_timeout):
    client = EnterpriseSearch(node_class=DummyNode, meta_header=False)
    client.get_version(request_timeout=request_timeout)

    calls = client.transport.node_pool.get().calls
    assert calls == [(
        ("GET", "/api/ent/v1/internal/version"),
        {
            "body": None,
            "headers": {
                "accept": "application/json"
            },
            "request_timeout": request_timeout,
        },
    )]
示例#6
0
def test_sub_clients():
    client = EnterpriseSearch()
    assert isinstance(client.app_search, AppSearch)
    assert isinstance(client.workplace_search, WorkplaceSearch)

    # Requests Session is shared for pooling
    assert client.transport is client.app_search.transport
    assert client.transport is client.workplace_search.transport
示例#7
0
def test_get_stats_include(ent_search: EnterpriseSearch, include):
    with pytest.raises(ValueError) as e:
        ent_search.get_stats(include="queues")
    assert str(e.value) == "'include' must be of type list or tuple"

    resp = ent_search.get_stats()
    assert resp.meta.status == 200
    assert set(resp.body.keys()) == {
        "app",
        "cluster_uuid",
        "connectors",
        "crawler",
        "http",
        "product_usage",
        "queues",
    }

    resp = ent_search.get_stats(include=include)
    assert resp.meta.status == 200
    assert set(resp.body.keys()) == {"app", "queues"}
def test_sub_clients():
    client = EnterpriseSearch()
    assert isinstance(client.app_search, AppSearch)
    assert isinstance(client.workplace_search, WorkplaceSearch)

    # Requests Session is shared for pooling
    assert client.transport is client.app_search.transport
    assert client.transport is client.workplace_search.transport

    # Authenticating doesn't modify other clients
    client.http_auth = ("user", "pass")
    client.app_search.http_auth = "token-app-search"
    client.workplace_search.http_auth = "token-workplace-search"

    assert client.http_auth == ("user", "pass")
    assert client.app_search.http_auth == "token-app-search"
    assert client.workplace_search.http_auth == "token-workplace-search"

    assert client._authorization_header == "Basic dXNlcjpwYXNz"
    assert client.app_search._authorization_header == "Bearer token-app-search"
    assert (client.workplace_search._authorization_header ==
            "Bearer token-workplace-search")
def test_http_auth_disable_with_none():
    client = EnterpriseSearch(bearer_auth="api-token", node_class=DummyNode)
    client.perform_request("GET", "/")

    calls = client.transport.node_pool.get().calls
    assert len(calls) == 1
    assert calls[-1][1]["headers"]["Authorization"] == "Bearer api-token"

    client.options(bearer_auth=None).get_version()
    assert len(calls) == 2
    assert "Authorization" not in calls[-1][1]["headers"]

    client.options(basic_auth=None).get_version()
    assert len(calls) == 3
    assert "Authorization" not in calls[-1][1]["headers"]
示例#10
0
def ent_search():
    host = "localhost"
    for try_host in ("enterprise-search", "localhost", "127.0.0.1"):
        try:
            http = urllib3.PoolManager()
            http.request("GET", "http://%s:3002" % try_host)
            host = try_host
            break
        except Exception:
            continue
    else:
        pytest.skip(
            "No Enterprise Search instance running on 'localhost:3002'")

    # TODO: Add authentication to this client
    with EnterpriseSearch("http://%s:3002" % host) as client:
        yield client
from pathlib import Path

import yaml
from elastic_enterprise_search import EnterpriseSearch

with (Path(__file__).absolute().parent.parent / "config.yml").open() as f:
    CONFIG = yaml.safe_load(f.read())

# Create our client instance.
ent_search = EnterpriseSearch(CONFIG["app_search"]["url"])

# Only executes when run as a script, not as an import.
if __name__ == "__main__":

    # If this code doesn't work, the rest of the examples won't either.
    version = ent_search.get_version()
    number, build_hash, build_date = (
        version["number"],
        version["build_hash"],
        version["build_date"],
    )

    print(f"You're running Enterprise Search v{number}")
    print(f"The build hash is {build_hash!r}")
    print(f"The build was created on {build_date}")
    print("Everything worked! :-)")

# Unpack the AppSearch client from the EnterpriseSearch client
# for use in the rest of the examples.
app_search = ent_search.app_search
示例#12
0
def ent_search(ent_search_url, ent_search_basic_auth):
    with EnterpriseSearch(ent_search_url,
                          basic_auth=ent_search_basic_auth) as client:
        yield client
def enterprise_search():
    yield EnterpriseSearch("http://localhost:3002",
                           http_auth=("elastic", "changeme"))
示例#14
0
def enterprise_search():
    yield EnterpriseSearch(
        "https://my-deployment-c6095a.ent.us-central1.gcp.cloud.es.io:443",
        basic_auth=("elastic", "yqcGpRqU9Mk4FQmsvJKxL9Uo"),
    )