Example #1
0
def _for_form_ip(field):
    # the IP address form fields have no direct indication of which type
    #  of address they want, so direct comparison with the validator
    #  function has to be used instead. Sorry for the potato logic here
    if validate_ipv46_address in field.default_validators:
        return st.ip_addresses(v=4).map(str) | _ipv6_strings
    if validate_ipv4_address in field.default_validators:
        return st.ip_addresses(v=4).map(str)
    if validate_ipv6_address in field.default_validators:
        return _ipv6_strings
    raise ResolutionFailed(f"No IP version validator on field={field!r}")
class TestIpAddressQuery(unittest.TestCase):
    @hypothesis.settings(
        deadline=None, )
    @given(
        node_key=st.uuids(),
        first_seen_timestamp=st.datetimes(),
        last_seen_timestamp=st.datetimes(),
        ip_address=st.ip_addresses(v=4),  # TODO: support ipv6?
    )
    def test__single_ip_addr_node__query_by_node_key(
        self,
        node_key,
        first_seen_timestamp,
        last_seen_timestamp,
        ip_address,
    ):
        # current function's name, but don't need to copy-paste replace
        node_key = node_key_for_test(self, node_key)
        local_client = DgraphClient(DgraphClientStub("localhost:9080"))

        created = get_or_create_ip_address_node(
            local_client=local_client,
            node_key=node_key,
            first_seen_timestamp=as_millis(first_seen_timestamp),
            last_seen_timestamp=as_millis(last_seen_timestamp),
            ip_address=str(ip_address),
        )

        queried_ip_address_node = (IpAddressQuery().with_ip_address(
        ).with_first_seen_timestamp().with_last_seen_timestamp().query_first(
            local_client, contains_node_key=node_key))

        assert_views_equal(expected=created, actual=queried_ip_address_node)
def test_ipaddress_from_network_is_always_in_network(data, network):
    ip = data.draw(ds.ip_addresses(network=network), label="address")
    assert ip in network
    assert ip.version == network.version
Example #4
0
def _for_model_ip(field):
    return {
        "ipv4": st.ip_addresses(v=4).map(str),
        "ipv6": _ipv6_strings,
        "both": st.ip_addresses(v=4).map(str) | _ipv6_strings,
    }[field.protocol.lower()]
Example #5
0
    df.FloatField:
    lambda field: st.floats(*numeric_bounds_from_validators(field),
                            allow_nan=False,
                            allow_infinity=False),
    df.IntegerField:
    integers_for_field(-2147483648, 2147483647),
    df.NullBooleanField:
    st.one_of(st.none(), st.booleans()),
    df.URLField:
    urls(),
    df.UUIDField:
    st.uuids(),
}

_ipv6_strings = st.one_of(
    st.ip_addresses(v=6).map(str),
    st.ip_addresses(v=6).map(lambda addr: addr.exploded),
)


def register_for(field_type):
    def inner(func):
        _global_field_lookup[field_type] = func
        return func

    return inner


@register_for(dm.DateTimeField)
@register_for(df.DateTimeField)
def _for_datetime(field):
Example #6
0
from hypothesis import given
from hypothesis import strategies as st

from giap.consumer import Method, Operation
from giap.core import GIAP


@given(
    st.one_of(st.integers(min_value=1), st.text()),
    st.text(),
    st.dictionaries(st.text(), st.text()),
    st.one_of(st.none(),
              st.ip_addresses().map(str)),
    st.text(),
)
def test_track(mock_consumer, id_, name, properties, ip_address, token):
    giap = GIAP(token, "")

    giap.track(id_, name, properties, ip_address)

    args = mock_consumer.send.call_args_list[-1][0]
    assert args[0] == "/events"
    assert args[2] == token

    data = args[1]["events"][0]
    assert data["$distinct_id"] == str(id_)
    assert data["$name"] == name
    assert isinstance(data["$time"], int)
    assert "$lib" in data
    assert "$lib_version" in data
Example #7
0
                                 targets=[],
                                 labels={
                                     label_name: "value",
                                 })
    assert (len(target_config.labels) == 3
            and {"job", "env", label_name} == target_config.labels.keys())


@given(UNICODE_VALUES, UNICODE_VALUES)
def test_default_labels_added_when_no_labels_in_constructor(app, env):
    """Make sure the constructor includes the default job and env labels"""
    target_config = TargetConfig(application=app, environment=env)
    assert target_config.labels == {"job": app, "env": env}


@given(st.ip_addresses(v=4), ALLOWED_PORTS)
def test_ip_address_hosts_are_allowed(ip_address, port):
    """Make sure IP addresses can be used for hostnames"""
    targets = [f"{ip_address!s}:{port}"]
    target_config = TargetConfig(
        application="app",
        environment="env",
        targets=targets,
    )
    assert target_config.targets == targets


@given(UNICODE_VALUES, UNICODE_VALUES)
def test_json_property_gets_created_properly(app, env):
    """Make sure the JSON version of the object looks correct"""
    target_config = TargetConfig(application=app, environment=env)
Example #8
0
    pydantic.PaymentCardNumber,
    st.from_regex('|'.join(card_patterns), fullmatch=True).map(add_luhn_digit),  # type: ignore[arg-type]
)

# UUIDs
st.register_type_strategy(pydantic.UUID1, st.uuids(version=1))
st.register_type_strategy(pydantic.UUID3, st.uuids(version=3))
st.register_type_strategy(pydantic.UUID4, st.uuids(version=4))
st.register_type_strategy(pydantic.UUID5, st.uuids(version=5))

# Secrets
st.register_type_strategy(pydantic.SecretBytes, st.binary().map(pydantic.SecretBytes))
st.register_type_strategy(pydantic.SecretStr, st.text().map(pydantic.SecretStr))

# IP addresses, networks, and interfaces
st.register_type_strategy(pydantic.IPvAnyAddress, st.ip_addresses())  # type: ignore[arg-type]
st.register_type_strategy(
    pydantic.IPvAnyInterface,
    st.from_type(ipaddress.IPv4Interface) | st.from_type(ipaddress.IPv6Interface),  # type: ignore[arg-type]
)
st.register_type_strategy(
    pydantic.IPvAnyNetwork,
    st.from_type(ipaddress.IPv4Network) | st.from_type(ipaddress.IPv6Network),  # type: ignore[arg-type]
)

# We hook into the con***() functions and the ConstrainedNumberMeta metaclass,
# so here we only have to register subclasses for other constrained types which
# don't go via those mechanisms.  Then there are the registration hooks below.
st.register_type_strategy(pydantic.StrictBool, st.booleans())
st.register_type_strategy(pydantic.StrictStr, st.text())
Example #9
0
class Testdata1(unittest.TestCase):
    @settings(max_examples=100)
    @given(a=st.ip_addresses(), b=st.tuples())
    def test_case(self, a, b):
        # print("a->", a)
        print("b->", b)
Example #10
0
# UUIDs
st.register_type_strategy(pydantic.UUID1, st.uuids(version=1))
st.register_type_strategy(pydantic.UUID3, st.uuids(version=3))
st.register_type_strategy(pydantic.UUID4, st.uuids(version=4))
st.register_type_strategy(pydantic.UUID5, st.uuids(version=5))

# Secrets
st.register_type_strategy(pydantic.SecretBytes,
                          st.binary().map(pydantic.SecretBytes))
st.register_type_strategy(pydantic.SecretStr,
                          st.text().map(pydantic.SecretStr))

# IP addresses, networks, and interfaces
st.register_type_strategy(pydantic.IPvAnyAddress,
                          st.ip_addresses())  # type: ignore[arg-type]
st.register_type_strategy(
    pydantic.IPvAnyInterface,
    st.from_type(ipaddress.IPv4Interface)
    | st.from_type(ipaddress.IPv6Interface),  # type: ignore[arg-type]
)
st.register_type_strategy(
    pydantic.IPvAnyNetwork,
    st.from_type(ipaddress.IPv4Network)
    | st.from_type(ipaddress.IPv6Network),  # type: ignore[arg-type]
)

# We hook into the con***() functions and the ConstrainedNumberMeta metaclass,
# so here we only have to register subclasses for other constrained types which
# don't go via those mechanisms.  Then there are the registration hooks below.
st.register_type_strategy(pydantic.StrictBool, st.booleans())
)

# UUIDs
st.register_type_strategy(pydantic.UUID1, st.uuids(version=1))
st.register_type_strategy(pydantic.UUID3, st.uuids(version=3))
st.register_type_strategy(pydantic.UUID4, st.uuids(version=4))
st.register_type_strategy(pydantic.UUID5, st.uuids(version=5))

# Secrets
st.register_type_strategy(pydantic.SecretBytes,
                          st.binary().map(pydantic.SecretBytes))
st.register_type_strategy(pydantic.SecretStr,
                          st.text().map(pydantic.SecretStr))

# IP addresses, networks, and interfaces
st.register_type_strategy(pydantic.IPvAnyAddress, st.ip_addresses())
st.register_type_strategy(
    pydantic.IPvAnyInterface,
    st.from_type(ipaddress.IPv4Interface)
    | st.from_type(ipaddress.IPv6Interface),  # type: ignore[arg-type]
)
st.register_type_strategy(
    pydantic.IPvAnyNetwork,
    st.from_type(ipaddress.IPv4Network)
    | st.from_type(ipaddress.IPv6Network),  # type: ignore[arg-type]
)

# We hook into the con***() functions and the ConstrainedNumberMeta metaclass,
# so here we only have to register subclasses for other constrained types which
# don't go via those mechanisms.  Then there are the registration hooks below.
st.register_type_strategy(pydantic.StrictBool, st.booleans())
Example #12
0
from hypothesis import given, settings
from hypothesis import strategies as st

from pathlib import Path
import ipdata

# local testing
pwd = Path(__file__).parent.resolve()
load_dotenv(f"{pwd}/.env")

# Github CI runs
IPDATA_API_KEY = os.environ.get("IPDATA_API_KEY")
ipdata.api_key = IPDATA_API_KEY


@given(st.ip_addresses(network="8.8.8.0/24"))
@settings(deadline=None, max_examples=100)
@pytest.mark.api
def test_lookup_v4(ip):
    ip = str(ip)
    data = ipdata.lookup(ip)
    assert data.ip == ip


@given(st.ip_addresses(network="2620:11a:a000::/40"))
@settings(deadline=None, max_examples=100)
@pytest.mark.api
def test_lookup_v6(ip):
    ip = str(ip)
    data = ipdata.lookup(ip)
Example #13
0
        with pytest.raises(RuntimeError):
            await multiplex_listener.bind(ip, port)


async def test_unbind_twice():
    start_server_mock, server_mock, remote_conn_mock = get_start_sever_mock()
    ip, port = ("127.0.0.1", 7777)
    with patch("asyncio.start_server", start_server_mock):
        multiplex_listener = await bind_multiplex_listener(ip, port)
        await multiplex_listener.unbind()
        with pytest.raises(RuntimeError):
            await multiplex_listener.unbind()


@given(
    remote_address=tuples(ip_addresses(), integers(min_value=0,
                                                   max_value=65535)),
    stream_names=lists(text(min_size=1), unique=True),
)
async def test_handle_streams(remote_address, stream_names):
    remote_ip, remote_port = remote_address
    handled_events = {name: asyncio.Event() for name in stream_names}

    async def handler(stream_name: StreamName, stream: Stream):
        assert stream.name == stream_name
        assert stream.ip == remote_ip
        assert stream.port == remote_port
        handled_events[stream_name].set()

    start_server_mock, server_mock, remote_conn_mock = get_start_sever_mock()
    with patch("asyncio.start_server", start_server_mock):
Example #14
0
@given(integers(1000, 300000000000))
def test_all_are_ips(n):
    ips = list(get_ip(str(n)))
    for ip in ips:
        assert is_ip(ip)


@given(integers(1000, 300000000000))
def test_concatenate_answers(n):
    s = str(n)
    ips = list(get_ip(str(n)))
    for ip in ips:
        assert no_dots(ip) == s


@given(ip_addresses(v=4))
def test_answer_contains_ip(ip):
    s = str(ip)
    ips = list(get_ip(no_dots(s)))
    assert s in ips


def test_example():
    ips = set(get_ip('11211'))
    assert ips == set([
        '1.1.2.11',
        '1.1.21.1',
        '1.12.1.1',
        '11.2.1.1',
    ])
Example #15
0
    """
    GIVEN
        An authentication provider is defined
    WHEN
        Whether authentication is required is requested  
    THEN
        Whether authentication is required is returned
    """

    mock_authentication_provider.required.return_value = auth_required
    assert auth.auth_required() == auth_required


@settings(suppress_health_check=[HealthCheck.function_scoped_fixture])
@given(addr=st.ip_addresses(),
       user=st.text(alphabet=st.characters(whitelist_categories=('Lu',
                                                                 'Ll',
                                                                 'Nd',
                                                                 'P'))))
def test_verify_valid_token(addr, user, server_with_auth_prov):

    """
    Uses `generate_token` to create token, as the essential behaviour to test
    is that a generated token can correctly verified 

    GIVEN
        A server with a secret token key
        AND a server with a token lifetime
        AND a request from a IP address
        AND a token generated using the IP
def test_ipaddress_from_network_is_always_correct_version(data, version):
    ip = data.draw(ds.ip_addresses(v=version), label="address")
    assert ip.version == version
        - MAC Address as input
    When:
        - Running the script
    Then:
        - Ensure the MAC address is caught as invalid IPv6 and returns array with empty string
    """
    mocker.patch.object(demisto,
                        'args',
                        return_value={'input': '00:16:45:00:46:91'})
    mocker.patch.object(demisto, 'results')
    main()
    demisto.results.assert_called_with([''])


@pytest.mark.skip(reason="Flaky test, issue #41552")
@settings(suppress_health_check=[HealthCheck.function_scoped_fixture])
@given(strategies.ip_addresses(v=6))
def test_valid_ip_address(mocker, ipv6):
    """
    Given:
        - IPv6 address
    When:
        - Running the script
    Then:
        - Ensure the IPv6 address is returned in an array
    """
    mocker.patch.object(demisto, 'args', return_value={'input': str(ipv6)})
    mocker.patch.object(demisto, 'results')
    main()
    demisto.results.assert_called_with([str(ipv6)])
Example #18
0
        assume(False)
    return result


REGEX_PATTERNS = regex_patterns()

STRING_FORMATS = {
    **{name: rfc3339(name)
       for name in RFC3339_FORMATS},
    "date": rfc3339("full-date"),
    "time": rfc3339("full-time"),
    "email": st.emails(),
    "idn-email": st.emails(),
    "hostname": prov.domains(),
    "idn-hostname": prov.domains(),
    "ipv4": st.ip_addresses(v=4).map(str),
    "ipv6": st.ip_addresses(v=6).map(str),
    **{
        name: prov.domains().map("https://{}".format)
        for name in [
            "uri", "uri-reference", "iri", "iri-reference", "uri-template"
        ]
    },
    "json-pointer": st.just(""),
    "relative-json-pointer": st.just(""),
    "regex": REGEX_PATTERNS,
}


def string_schema(schema: dict) -> st.SearchStrategy[str]:
    """Handle schemata for strings."""
Example #19
0
# Third party modules
import hypothesis.strategies as s
import mpu.string  # Martins Python Utilities
from hypothesis import given


@given(s.emails())
def test_is_email(email):
    assert mpu.string.is_email(email), f"is_email({email}) returned False"


@given(s.ip_addresses(v=4))
def test_is_ipv4(ip):
    assert mpu.string.is_ipv4(str(ip)), f"is_ipv4({ip}) returned False"
    if isinstance(value, str):
        try:
            JSONPointer(value)
        except JSONPointerError as e:
            raise ValueError(str(e))


def evaluate(format_attr, instval, assert_=True):
    FormatKeyword(schema := JSONSchema(True),
                  format_attr).evaluate(JSON(instval), scope := Scope(schema))
    assert scope.annotations["format"].value == format_attr
    assert scope._assert is assert_
    return scope.valid


@given(hs.ip_addresses(v=4))
def test_ipv4_valid(instval):
    result = evaluate("ipv4", str(instval))
    assert result is True


@given(hs.text())
def test_ipv4_invalid(instval):
    result = evaluate("ipv4", instval)
    try:
        ipaddress.IPv4Address(instval)
        assert result is True
    except ipaddress.AddressValueError:
        assert result is False