instance_id
stringlengths
12
53
patch
stringlengths
264
37.7k
repo
stringlengths
8
49
base_commit
stringlengths
40
40
hints_text
stringclasses
114 values
test_patch
stringlengths
224
315k
problem_statement
stringlengths
40
10.4k
version
stringclasses
1 value
FAIL_TO_PASS
sequencelengths
1
4.94k
PASS_TO_PASS
sequencelengths
0
6.23k
created_at
stringlengths
25
25
__index_level_0__
int64
4.13k
6.41k
nolar__kopf-770
diff --git a/docs/authentication.rst b/docs/authentication.rst index d7ae95a..e17889d 100644 --- a/docs/authentication.rst +++ b/docs/authentication.rst @@ -14,6 +14,12 @@ authentication methods and piggybacks the existing Kubernetes clients. Custom authentication ===================== +In most setups, the normal authentication from one of the API client libraries +is enough --- it works out of the box if those clients are installed +(see :ref:`auth-piggybacking` below). Custom authentication is only needed +if the normal authentication methods do not work for some reason, such as if +you have a specific and unusual cluster setup (e.g. your own auth tokens). + To implement a custom authentication method, one or a few login-handlers can be added. The login handlers should either return nothing (``None``) or an instance of `kopf.ConnectionInfo`:: diff --git a/kopf/_cogs/clients/auth.py b/kopf/_cogs/clients/auth.py index 632984d..4b4af34 100644 --- a/kopf/_cogs/clients/auth.py +++ b/kopf/_cogs/clients/auth.py @@ -44,7 +44,12 @@ def reauthenticated_request(fn: _F) -> _F: return await fn(*args, **kwargs, context=context) except errors.APIUnauthorizedError as e: await vault.invalidate(key, exc=e) - raise credentials.LoginError("Ran out of connection credentials.") + + # Normally, either `vault.extended()` or `vault.invalidate()` raise the login errors. + # The for-cycle can only end if the yielded credentials are not invalidated before trying + # the next ones -- but this case exits by `return` or by other (non-401) errors. + raise RuntimeError("Reached an impossible state: the end of the authentication cycle.") + return cast(_F, wrapper) @@ -76,7 +81,12 @@ def reauthenticated_stream(fn: _F) -> _F: return except errors.APIUnauthorizedError as e: await vault.invalidate(key, exc=e) - raise credentials.LoginError("Ran out of connection credentials.") + + # Normally, either `vault.extended()` or `vault.invalidate()` raise the login errors. + # The for-cycle can only end if the yielded credentials are not invalidated before trying + # the next ones -- but this case exits by `return` or by other (non-401) errors. + raise RuntimeError("Reached an impossible state: the end of the authentication cycle.") + return cast(_F, wrapper) diff --git a/kopf/_cogs/structs/credentials.py b/kopf/_cogs/structs/credentials.py index e9bca12..3d9cae6 100644 --- a/kopf/_cogs/structs/credentials.py +++ b/kopf/_cogs/structs/credentials.py @@ -205,7 +205,9 @@ class Vault(AsyncIterable[Tuple[VaultKey, ConnectionInfo]]): it can lead to improper items returned. """ if not self._current: - raise LoginError("No valid credentials are available.") + raise LoginError("Ran out of valid credentials. Consider installing " + "an API client library or adding a login handler. See more: " + "https://kopf.readthedocs.io/en/stable/authentication/") prioritised: Dict[int, List[Tuple[VaultKey, VaultItem]]] prioritised = collections.defaultdict(list) for key, item in self._current.items(): @@ -252,11 +254,14 @@ class Vault(AsyncIterable[Tuple[VaultKey, ConnectionInfo]]): # If the re-auth has failed, re-raise the original exception in the current stack. # If the original exception is unknown, raise normally on the next iteration's yield. + # The error here is optional -- for better stack traces of the original exception `exc`. # Keep in mind, this routine is called in parallel from many tasks for the same keys. async with self._lock: if not self._current: if exc is not None: - raise exc + raise LoginError("Ran out of valid credentials. Consider installing " + "an API client library or adding a login handler. See more: " + "https://kopf.readthedocs.io/en/stable/authentication/") from exc async def populate( self, diff --git a/kopf/_core/intents/piggybacking.py b/kopf/_core/intents/piggybacking.py index e05714d..df57ba1 100644 --- a/kopf/_core/intents/piggybacking.py +++ b/kopf/_core/intents/piggybacking.py @@ -46,6 +46,7 @@ def login_via_client( **kwargs: Any, ) -> Optional[credentials.ConnectionInfo]: + # Keep imports in the function, as module imports are mocked in some tests. try: import kubernetes.config except ImportError: @@ -59,7 +60,8 @@ def login_via_client( kubernetes.config.load_kube_config() # developer's config files logger.debug("Client is configured via kubeconfig file.") except kubernetes.config.ConfigException as e2: - raise credentials.LoginError(f"Cannot authenticate client neither in-cluster, nor via kubeconfig.") + raise credentials.LoginError("Cannot authenticate the client library " + "neither in-cluster, nor via kubeconfig.") # We do not even try to understand how it works and why. Just load it, and extract the results. # For kubernetes client >= 12.0.0 use the new 'get_default_copy' method @@ -100,6 +102,7 @@ def login_via_pykube( **kwargs: Any, ) -> Optional[credentials.ConnectionInfo]: + # Keep imports in the function, as module imports are mocked in some tests. try: import pykube except ImportError: @@ -115,8 +118,8 @@ def login_via_pykube( config = pykube.KubeConfig.from_file() logger.debug("Pykube is configured via kubeconfig file.") except (pykube.PyKubeError, FileNotFoundError): - raise credentials.LoginError(f"Cannot authenticate pykube " - f"neither in-cluster, nor via kubeconfig.") + raise credentials.LoginError("Cannot authenticate pykube " + "neither in-cluster, nor via kubeconfig.") # We don't know how this token will be retrieved, we just get it afterwards. provider_token = None
nolar/kopf
c2216191e11c8476e418e3d578b0cc7bb035b82d
diff --git a/tests/authentication/test_vault.py b/tests/authentication/test_vault.py index 50cc939..d39ef7c 100644 --- a/tests/authentication/test_vault.py +++ b/tests/authentication/test_vault.py @@ -55,7 +55,8 @@ async def test_invalidation_reraises_if_nothing_is_left_with_exception(mocker): with pytest.raises(Exception) as e: await vault.invalidate(key1, exc=exc) - assert e.value is exc + assert isinstance(e.value, LoginError) + assert e.value.__cause__ is exc assert vault._ready.wait_for.await_args_list == [((True,),)] diff --git a/tests/k8s/test_creating.py b/tests/k8s/test_creating.py index 7d45fd5..c2958dc 100644 --- a/tests/k8s/test_creating.py +++ b/tests/k8s/test_creating.py @@ -40,7 +40,8 @@ async def test_full_body_with_identifiers( assert data == {'x': 'y', 'metadata': {'name': 'name1', 'namespace': namespace}} [email protected]('status', [400, 401, 403, 404, 409, 500, 666]) +# Note: 401 is wrapped into a LoginError and is tested elsewhere. [email protected]('status', [400, 403, 404, 409, 500, 666]) async def test_raises_api_errors( resp_mocker, aresponses, hostname, status, resource, namespace, cluster_resource, namespaced_resource): diff --git a/tests/k8s/test_errors.py b/tests/k8s/test_errors.py index 54465f3..411d4a0 100644 --- a/tests/k8s/test_errors.py +++ b/tests/k8s/test_errors.py @@ -3,7 +3,7 @@ import pytest from kopf._cogs.clients.auth import APIContext, reauthenticated_request from kopf._cogs.clients.errors import APIConflictError, APIError, APIForbiddenError, \ - APINotFoundError, APIUnauthorizedError, check_response + APINotFoundError, check_response @reauthenticated_request @@ -47,9 +47,9 @@ async def test_no_error_on_success( await get_it(f"http://{hostname}/") +# Note: 401 is wrapped into a LoginError and is tested elsewhere. @pytest.mark.parametrize('status, exctype', [ (400, APIError), - (401, APIUnauthorizedError), (403, APIForbiddenError), (404, APINotFoundError), (409, APIConflictError), diff --git a/tests/k8s/test_list_objs.py b/tests/k8s/test_list_objs.py index 57822a6..cfa9e84 100644 --- a/tests/k8s/test_list_objs.py +++ b/tests/k8s/test_list_objs.py @@ -3,6 +3,7 @@ import pytest from kopf._cogs.clients.errors import APIError from kopf._cogs.clients.fetching import list_objs_rv +from kopf._cogs.structs.credentials import LoginError async def test_listing_works( @@ -23,8 +24,9 @@ async def test_listing_works( assert list_mock.call_count == 1 [email protected]('status', [400, 401, 403, 500, 666]) -async def test_raises_api_error( +# Note: 401 is wrapped into a LoginError and is tested elsewhere. [email protected]('status', [400, 403, 500, 666]) +async def test_raises_direct_api_errors( resp_mocker, aresponses, hostname, status, resource, namespace, cluster_resource, namespaced_resource): diff --git a/tests/k8s/test_patching.py b/tests/k8s/test_patching.py index 0f758da..0702df9 100644 --- a/tests/k8s/test_patching.py +++ b/tests/k8s/test_patching.py @@ -177,7 +177,8 @@ async def test_ignores_absent_objects( assert result is None [email protected]('status', [400, 401, 403, 500, 666]) +# Note: 401 is wrapped into a LoginError and is tested elsewhere. [email protected]('status', [400, 403, 500, 666]) async def test_raises_api_errors( resp_mocker, aresponses, hostname, status, resource, namespace, cluster_resource, namespaced_resource):
Authentication during startup ## Problem I'm trying to create/update CRDs using the `@kopf.on.startup()` event. However, it seems to me that the authentication even has not yet fired, which means that there is no valid connection to the Kubernetes api. I can get around this by running `config.load_kube_config()` and/or `config.load_incluster_config()` but it seems a bit dirty (this is what the kopf authentication stuff is mode for, after all). ## Proposal Add a new event, `@kopf.on.post_auth_startup()` that executes after the authentication stuff is initialized. ## Checklist - [x] Many users can benefit from this feature, it is not a one-time case - [x] The proposal is related to the K8s operator framework, not to the K8s client libraries
0.0
[ "tests/authentication/test_vault.py::test_invalidation_reraises_if_nothing_is_left_with_exception", "tests/k8s/test_creating.py::test_raises_api_errors[namespaced-409]", "tests/k8s/test_errors.py::test_exception_with_payload[cluster]", "tests/k8s/test_errors.py::test_error_with_payload[namespaced-409-APIConflictError]", "tests/k8s/test_errors.py::test_error_with_nonjson_payload[namespaced-666]", "tests/k8s/test_list_objs.py::test_listing_works[cluster]", "tests/k8s/test_patching.py::test_without_subresources[cluster]", "tests/k8s/test_patching.py::test_status_as_body_field_with_combined_payload[cluster]", "tests/k8s/test_patching.py::test_raises_api_errors[cluster-666]" ]
[ "tests/authentication/test_vault.py::test_evals_as_false_when_empty", "tests/authentication/test_vault.py::test_evals_as_true_when_filled", "tests/authentication/test_vault.py::test_yielding_after_creation", "tests/authentication/test_vault.py::test_yielding_after_population", "tests/authentication/test_vault.py::test_invalidation_continues_if_nothing_is_left_without_exception", "tests/authentication/test_vault.py::test_invalidation_continues_if_something_is_left", "tests/authentication/test_vault.py::test_yielding_after_invalidation", "tests/authentication/test_vault.py::test_duplicates_are_remembered", "tests/authentication/test_vault.py::test_caches_from_factory", "tests/authentication/test_vault.py::test_caches_with_same_purpose", "tests/authentication/test_vault.py::test_caches_with_different_purposes", "tests/k8s/test_creating.py::test_simple_body_with_arguments[namespaced]", "tests/k8s/test_creating.py::test_simple_body_with_arguments[cluster]", "tests/k8s/test_creating.py::test_full_body_with_identifiers[namespaced]", "tests/k8s/test_creating.py::test_full_body_with_identifiers[cluster]", "tests/k8s/test_creating.py::test_raises_api_errors[namespaced-400]", "tests/k8s/test_creating.py::test_raises_api_errors[namespaced-403]", "tests/k8s/test_creating.py::test_raises_api_errors[namespaced-404]", "tests/k8s/test_creating.py::test_raises_api_errors[namespaced-500]", "tests/k8s/test_creating.py::test_raises_api_errors[cluster-400]", "tests/k8s/test_creating.py::test_raises_api_errors[cluster-403]", "tests/k8s/test_creating.py::test_raises_api_errors[cluster-404]", "tests/k8s/test_creating.py::test_raises_api_errors[cluster-409]", "tests/k8s/test_creating.py::test_raises_api_errors[cluster-500]", "tests/k8s/test_creating.py::test_raises_api_errors[cluster-666]", "tests/k8s/test_errors.py::test_aiohttp_is_not_leaked_outside[namespaced]", "tests/k8s/test_errors.py::test_aiohttp_is_not_leaked_outside[cluster]", "tests/k8s/test_errors.py::test_exception_without_payload[namespaced]", "tests/k8s/test_errors.py::test_exception_without_payload[cluster]", "tests/k8s/test_errors.py::test_exception_with_payload[namespaced]", "tests/k8s/test_errors.py::test_no_error_on_success[namespaced-200]", "tests/k8s/test_errors.py::test_no_error_on_success[namespaced-202]", "tests/k8s/test_errors.py::test_no_error_on_success[namespaced-304]", "tests/k8s/test_errors.py::test_no_error_on_success[cluster-200]", "tests/k8s/test_errors.py::test_no_error_on_success[cluster-202]", "tests/k8s/test_errors.py::test_no_error_on_success[cluster-300]", "tests/k8s/test_errors.py::test_no_error_on_success[cluster-304]", "tests/k8s/test_errors.py::test_error_with_payload[namespaced-400-APIError]", "tests/k8s/test_errors.py::test_error_with_payload[namespaced-403-APIForbiddenError]", "tests/k8s/test_errors.py::test_error_with_payload[namespaced-404-APINotFoundError]", "tests/k8s/test_errors.py::test_error_with_payload[namespaced-500-APIError]", "tests/k8s/test_errors.py::test_error_with_payload[cluster-400-APIError]", "tests/k8s/test_errors.py::test_error_with_payload[cluster-403-APIForbiddenError]", "tests/k8s/test_errors.py::test_error_with_payload[cluster-404-APINotFoundError]", "tests/k8s/test_errors.py::test_error_with_payload[cluster-409-APIConflictError]", "tests/k8s/test_errors.py::test_error_with_payload[cluster-500-APIError]", "tests/k8s/test_errors.py::test_error_with_payload[cluster-666-APIError]", "tests/k8s/test_errors.py::test_error_with_nonjson_payload[namespaced-400]", "tests/k8s/test_errors.py::test_error_with_nonjson_payload[namespaced-500]", "tests/k8s/test_errors.py::test_error_with_nonjson_payload[cluster-400]", "tests/k8s/test_errors.py::test_error_with_nonjson_payload[cluster-666]", "tests/k8s/test_errors.py::test_error_with_parseable_nonk8s_payload[namespaced-400]", "tests/k8s/test_errors.py::test_error_with_parseable_nonk8s_payload[namespaced-500]", "tests/k8s/test_errors.py::test_error_with_parseable_nonk8s_payload[namespaced-666]", "tests/k8s/test_errors.py::test_error_with_parseable_nonk8s_payload[cluster-400]", "tests/k8s/test_errors.py::test_error_with_parseable_nonk8s_payload[cluster-500]", "tests/k8s/test_errors.py::test_error_with_parseable_nonk8s_payload[cluster-666]", "tests/k8s/test_list_objs.py::test_listing_works[namespaced]", "tests/k8s/test_list_objs.py::test_raises_direct_api_errors[namespaced-400]", "tests/k8s/test_list_objs.py::test_raises_direct_api_errors[namespaced-500]", "tests/k8s/test_list_objs.py::test_raises_direct_api_errors[namespaced-666]", "tests/k8s/test_list_objs.py::test_raises_direct_api_errors[cluster-400]", "tests/k8s/test_list_objs.py::test_raises_direct_api_errors[cluster-403]", "tests/k8s/test_list_objs.py::test_raises_direct_api_errors[cluster-500]", "tests/k8s/test_list_objs.py::test_raises_direct_api_errors[cluster-666]", "tests/k8s/test_patching.py::test_without_subresources[namespaced]", "tests/k8s/test_patching.py::test_status_as_subresource_with_combined_payload[namespaced]", "tests/k8s/test_patching.py::test_status_as_subresource_with_object_fields_only[namespaced]", "tests/k8s/test_patching.py::test_status_as_subresource_with_object_fields_only[cluster]", "tests/k8s/test_patching.py::test_status_as_subresource_with_status_fields_only[namespaced]", "tests/k8s/test_patching.py::test_status_as_subresource_with_status_fields_only[cluster]", "tests/k8s/test_patching.py::test_status_as_body_field_with_combined_payload[namespaced]", "tests/k8s/test_patching.py::test_ignores_absent_objects[namespaced-404]", "tests/k8s/test_patching.py::test_raises_api_errors[namespaced-403]", "tests/k8s/test_patching.py::test_raises_api_errors[namespaced-500]", "tests/k8s/test_patching.py::test_raises_api_errors[namespaced-666]", "tests/k8s/test_patching.py::test_raises_api_errors[cluster-400]", "tests/k8s/test_patching.py::test_raises_api_errors[cluster-403]", "tests/k8s/test_patching.py::test_raises_api_errors[cluster-500]" ]
2021-05-13 15:57:53+00:00
4,231
nornir-automation__nornir-235
diff --git a/nornir/core/__init__.py b/nornir/core/__init__.py index 8df1d34..08a112f 100644 --- a/nornir/core/__init__.py +++ b/nornir/core/__init__.py @@ -1,12 +1,12 @@ import logging import logging.config from multiprocessing.dummy import Pool -from typing import Type from nornir.core.configuration import Config -from nornir.core.connections import ConnectionPlugin from nornir.core.task import AggregatedResult, Task -from nornir.plugins import connections +from nornir.plugins.connections import register_default_connection_plugins + +register_default_connection_plugins() class Data(object): @@ -16,12 +16,10 @@ class Data(object): Attributes: failed_hosts (list): Hosts that have failed to run a task properly - available_connections (dict): Dictionary holding available connection plugins """ def __init__(self): self.failed_hosts = set() - self.available_connections = connections.available_connections def recover_host(self, host): """Remove ``host`` from list of failed hosts.""" @@ -47,8 +45,6 @@ class Nornir(object): dry_run(``bool``): Whether if we are testing the changes or not config (:obj:`nornir.core.configuration.Config`): Configuration object config_file (``str``): Path to Yaml configuration file - available_connections (``dict``): dict of connection types that will be made available. - Defaults to :obj:`nornir.plugins.tasks.connections.available_connections` Attributes: inventory (:obj:`nornir.core.inventory.Inventory`): Inventory to work with @@ -58,14 +54,7 @@ class Nornir(object): """ def __init__( - self, - inventory, - dry_run, - config=None, - config_file=None, - available_connections=None, - logger=None, - data=None, + self, inventory, dry_run, config=None, config_file=None, logger=None, data=None ): self.logger = logger or logging.getLogger("nornir") @@ -81,9 +70,6 @@ class Nornir(object): self.configure_logging() - if available_connections is not None: - self.data.available_connections = available_connections - def __enter__(self): return self @@ -238,10 +224,6 @@ class Nornir(object): """ Return a dictionary representing the object. """ return {"data": self.data.to_dict(), "inventory": self.inventory.to_dict()} - def get_connection_type(self, connection: str) -> Type[ConnectionPlugin]: - """Returns the class for the given connection type.""" - return self.data.available_connections[connection] - def close_connections(self, on_good=True, on_failed=False): def close_connections_task(task): task.host.close_connections() diff --git a/nornir/core/connections.py b/nornir/core/connections.py index fe50090..5e26397 100644 --- a/nornir/core/connections.py +++ b/nornir/core/connections.py @@ -1,8 +1,12 @@ from abc import ABC, abstractmethod -from typing import Any, Dict, NoReturn, Optional +from typing import Any, Dict, NoReturn, Optional, Type from nornir.core.configuration import Config +from nornir.core.exceptions import ( + ConnectionPluginAlreadyRegistered, + ConnectionPluginNotRegistered, +) class ConnectionPlugin(ABC): @@ -53,4 +57,63 @@ class UnestablishedConnection(object): class Connections(Dict[str, ConnectionPlugin]): - pass + available: Dict[str, Type[ConnectionPlugin]] = {} + + @classmethod + def register(cls, name: str, plugin: Type[ConnectionPlugin]) -> None: + """Registers a connection plugin with a specified name + + Args: + name: name of the connection plugin to register + plugin: defined connection plugin class + + Raises: + :obj:`nornir.core.exceptions.ConnectionPluginAlreadyRegistered` if + another plugin with the specified name was already registered + """ + existing_plugin = cls.available.get(name) + if existing_plugin is None: + cls.available[name] = plugin + elif existing_plugin != plugin: + raise ConnectionPluginAlreadyRegistered( + f"Connection plugin {plugin.__name__} can't be registered as " + f"{name!r} because plugin {existing_plugin.__name__} " + f"was already registered under this name" + ) + + @classmethod + def deregister(cls, name: str) -> None: + """Deregisters a registered connection plugin by its name + + Args: + name: name of the connection plugin to deregister + + Raises: + :obj:`nornir.core.exceptions.ConnectionPluginNotRegistered` + """ + if name not in cls.available: + raise ConnectionPluginNotRegistered( + f"Connection {name!r} is not registered" + ) + cls.available.pop(name) + + @classmethod + def deregister_all(cls) -> None: + """Deregisters all registered connection plugins""" + cls.available = {} + + @classmethod + def get_plugin(cls, name: str) -> Type[ConnectionPlugin]: + """Fetches the connection plugin by name if already registered + + Args: + name: name of the connection plugin + + Raises: + :obj:`nornir.core.exceptions.ConnectionPluginNotRegistered` + """ + if name not in cls.available: + raise ConnectionPluginNotRegistered( + f"Connection {name!r} is not registered" + ) + return cls.available[name] diff --git a/nornir/core/exceptions.py b/nornir/core/exceptions.py index cbceb40..e1683be 100644 --- a/nornir/core/exceptions.py +++ b/nornir/core/exceptions.py @@ -14,6 +14,14 @@ class ConnectionNotOpen(ConnectionException): pass +class ConnectionPluginAlreadyRegistered(ConnectionException): + pass + + +class ConnectionPluginNotRegistered(ConnectionException): + pass + + class CommandError(Exception): """ Raised when there is a command error. diff --git a/nornir/core/inventory.py b/nornir/core/inventory.py index 4330e86..3e2d8c5 100644 --- a/nornir/core/inventory.py +++ b/nornir/core/inventory.py @@ -329,7 +329,7 @@ class Host(object): if connection in self.connections: raise ConnectionAlreadyOpen(connection) - self.connections[connection] = self.nornir.get_connection_type(connection)() + self.connections[connection] = self.connections.get_plugin(connection)() if default_to_host_attributes: conn_params = self.get_connection_parameters(connection) self.connections[connection].open( diff --git a/nornir/plugins/connections/__init__.py b/nornir/plugins/connections/__init__.py index 5fc891f..fb14988 100644 --- a/nornir/plugins/connections/__init__.py +++ b/nornir/plugins/connections/__init__.py @@ -1,16 +1,10 @@ -from typing import Dict, TYPE_CHECKING, Type - - from .napalm import Napalm from .netmiko import Netmiko from .paramiko import Paramiko - -if TYPE_CHECKING: - from nornir.core.connections import ConnectionPlugin # noqa +from nornir.core.connections import Connections -available_connections: Dict[str, Type["ConnectionPlugin"]] = { - "napalm": Napalm, - "netmiko": Netmiko, - "paramiko": Paramiko, -} +def register_default_connection_plugins() -> None: + Connections.register("napalm", Napalm) + Connections.register("netmiko", Netmiko) + Connections.register("paramiko", Paramiko)
nornir-automation/nornir
2554177329c55a15f5ed6167dfa219ebbb8b9e2e
diff --git a/tests/core/test_connections.py b/tests/core/test_connections.py index b400c14..54c277d 100644 --- a/tests/core/test_connections.py +++ b/tests/core/test_connections.py @@ -1,8 +1,16 @@ from typing import Any, Dict, Optional +import pytest + from nornir.core.configuration import Config -from nornir.core.connections import ConnectionPlugin -from nornir.core.exceptions import ConnectionAlreadyOpen, ConnectionNotOpen +from nornir.core.connections import ConnectionPlugin, Connections +from nornir.core.exceptions import ( + ConnectionAlreadyOpen, + ConnectionNotOpen, + ConnectionPluginNotRegistered, + ConnectionPluginAlreadyRegistered, +) +from nornir.plugins.connections import register_default_connection_plugins class DummyConnectionPlugin(ConnectionPlugin): @@ -30,6 +38,10 @@ class DummyConnectionPlugin(ConnectionPlugin): self.connection = False +class AnotherDummyConnectionPlugin(DummyConnectionPlugin): + pass + + def open_and_close_connection(task): task.host.open_connection("dummy") assert "dummy" in task.host.connections @@ -68,29 +80,31 @@ def validate_params(task, conn, params): class Test(object): + @classmethod + def setup_class(cls): + Connections.deregister_all() + Connections.register("dummy", DummyConnectionPlugin) + Connections.register("dummy_no_overrides", DummyConnectionPlugin) + def test_open_and_close_connection(self, nornir): - nornir.data.available_connections["dummy"] = DummyConnectionPlugin nr = nornir.filter(name="dev2.group_1") r = nr.run(task=open_and_close_connection, num_workers=1) assert len(r) == 1 assert not r.failed def test_open_connection_twice(self, nornir): - nornir.data.available_connections["dummy"] = DummyConnectionPlugin nr = nornir.filter(name="dev2.group_1") r = nr.run(task=open_connection_twice, num_workers=1) assert len(r) == 1 assert not r.failed def test_close_not_opened_connection(self, nornir): - nornir.data.available_connections["dummy"] = DummyConnectionPlugin nr = nornir.filter(name="dev2.group_1") r = nr.run(task=close_not_opened_connection, num_workers=1) assert len(r) == 1 assert not r.failed def test_context_manager(self, nornir): - nornir.data.available_connections["dummy"] = DummyConnectionPlugin with nornir.filter(name="dev2.group_1") as nr: nr.run(task=a_task) assert "dummy" in nr.inventory.hosts["dev2.group_1"].connections @@ -98,7 +112,6 @@ class Test(object): nornir.data.reset_failed_hosts() def test_validate_params_simple(self, nornir): - nornir.data.available_connections["dummy_no_overrides"] = DummyConnectionPlugin params = { "hostname": "127.0.0.1", "username": "root", @@ -118,7 +131,6 @@ class Test(object): assert not r.failed def test_validate_params_overrides(self, nornir): - nornir.data.available_connections["dummy"] = DummyConnectionPlugin params = { "hostname": "overriden_hostname", "username": "root", @@ -131,3 +143,51 @@ class Test(object): r = nr.run(task=validate_params, conn="dummy", params=params, num_workers=1) assert len(r) == 1 assert not r.failed + + +class TestConnectionPluginsRegistration(object): + def setup_method(self, method): + Connections.deregister_all() + Connections.register("dummy", DummyConnectionPlugin) + Connections.register("another_dummy", AnotherDummyConnectionPlugin) + + def teardown_method(self, method): + Connections.deregister_all() + register_default_connection_plugins() + + def test_count(self): + assert len(Connections.available) == 2 + + def test_register_new(self): + Connections.register("new_dummy", DummyConnectionPlugin) + assert "new_dummy" in Connections.available + + def test_register_already_registered_same(self): + Connections.register("dummy", DummyConnectionPlugin) + assert Connections.available["dummy"] == DummyConnectionPlugin + + def test_register_already_registered_new(self): + with pytest.raises(ConnectionPluginAlreadyRegistered): + Connections.register("dummy", AnotherDummyConnectionPlugin) + + def test_deregister_existing(self): + Connections.deregister("dummy") + assert len(Connections.available) == 1 + assert "dummy" not in Connections.available + + def test_deregister_nonexistent(self): + with pytest.raises(ConnectionPluginNotRegistered): + Connections.deregister("nonexistent_dummy") + + def test_deregister_all(self): + Connections.deregister_all() + assert Connections.available == {} + + def test_get_plugin(self): + assert Connections.get_plugin("dummy") == DummyConnectionPlugin + assert Connections.get_plugin("another_dummy") == AnotherDummyConnectionPlugin + assert len(Connections.available) == 2 + + def test_nonexistent_plugin(self): + with pytest.raises(ConnectionPluginNotRegistered): + Connections.get_plugin("nonexistent_dummy")
Augment Connections class This class could contain available connections as class attributes and instance attributes would be existing connections. Here is my previous proposal, which should be tested / discussed more: ``` class HostConnections(Dict[str, ConnectionPlugin]): available: Dict[str, Type[ConnectionPlugin]] = {} @classmethod def register(cls, name, value): cls.available[name] = value def open(self, name: str, ...): connection = self.available[name]() connection.open() self[name] = connection def close(self, ...): ... def close_all(self): for connection in self: self.close(connection) def get_or_create(self, ...): ... class Host(object): ... def __init__(self, ...): ... self.connections = HostConnections() def open_connection(self, name: str, ...): self.connections.open(name, ...) ... # can be called from plugin code or user code HostConnections.register('netmiko', Netmiko) HostConnections.register('napalm', Napalm) ```
0.0
[ "tests/core/test_connections.py::Test::test_open_and_close_connection", "tests/core/test_connections.py::Test::test_open_connection_twice", "tests/core/test_connections.py::Test::test_close_not_opened_connection", "tests/core/test_connections.py::Test::test_context_manager", "tests/core/test_connections.py::Test::test_validate_params_simple", "tests/core/test_connections.py::Test::test_validate_params_overrides", "tests/core/test_connections.py::TestConnectionPluginsRegistration::test_count", "tests/core/test_connections.py::TestConnectionPluginsRegistration::test_register_new", "tests/core/test_connections.py::TestConnectionPluginsRegistration::test_register_already_registered_same", "tests/core/test_connections.py::TestConnectionPluginsRegistration::test_register_already_registered_new", "tests/core/test_connections.py::TestConnectionPluginsRegistration::test_deregister_existing", "tests/core/test_connections.py::TestConnectionPluginsRegistration::test_deregister_nonexistent", "tests/core/test_connections.py::TestConnectionPluginsRegistration::test_deregister_all", "tests/core/test_connections.py::TestConnectionPluginsRegistration::test_get_plugin" ]
[]
2018-08-26 19:00:32+00:00
4,232
nosarthur__gita-105
diff --git a/README.md b/README.md index 997b5a6..8644f43 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ The bookkeeping sub-commands are - `gita group add <repo-name(s)> -n <group-name>`: add repo(s) to a new group or existing group - `gita group [ll]`: display existing groups with repos - `gita group ls`: display existing group names - - `gita group rename <group-name> <new-name>: change group name + - `gita group rename <group-name> <new-name>`: change group name - `gita group rm <group-name(s)>`: delete group(s) - `gita info`: display the used and unused information items - `gita ll`: display the status of all repos diff --git a/doc/README_CN.md b/doc/README_CN.md index 0cb9cd0..051bbe8 100644 --- a/doc/README_CN.md +++ b/doc/README_CN.md @@ -54,7 +54,7 @@ - `gita group add <repo-name(s)>`: 把库加入新的或者已经存在的组 - `gita group [ll]`: 显示已有的组和它们的库 - `gita group ls`: 显示已有的组名 - - `gita group rename <group-name> <new-name>: 改组名 + - `gita group rename <group-name> <new-name>`: 改组名 - `gita group rm group(s): 删除组 - `gita info`: 显示已用的和未用的信息项 - `gita ll`: 显示所有库的状态信息 diff --git a/gita/__main__.py b/gita/__main__.py index 5900d27..e00f20d 100644 --- a/gita/__main__.py +++ b/gita/__main__.py @@ -15,6 +15,7 @@ https://github.com/nosarthur/gita/blob/master/.gita-completion.bash ''' import os +import sys import argparse import subprocess import pkg_resources @@ -76,6 +77,14 @@ def f_group(args: argparse.Namespace): print(f"{group}: {' '.join(repos)}") elif cmd == 'ls': print(' '.join(groups)) + elif cmd == 'rename': + new_name = args.new_name + if new_name in groups: + sys.exit(f'{new_name} already exists.') + gname = args.gname + groups[new_name] = groups[gname] + del groups[gname] + utils.write_to_groups_file(groups, 'w') elif cmd == 'rm': for name in args.to_ungroup: del groups[name] @@ -273,6 +282,12 @@ def main(argv=None): metavar='group-name', required=True, help="group name") + pg_rename = group_cmds.add_parser('rename', description='Change group name.') + pg_rename.add_argument('gname', metavar='group-name', + choices=utils.get_groups(), + help="existing group to be renamed") + pg_rename.add_argument('new_name', metavar='new-name', + help="new group name") group_cmds.add_parser('rm', description='Remove group(s).').add_argument('to_ungroup', nargs='+', diff --git a/setup.py b/setup.py index 79821f1..0cdd33f 100644 --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ with open('README.md', encoding='utf-8') as f: setup( name='gita', packages=['gita'], - version='0.11.5', + version='0.11.6', license='MIT', description='Manage multiple git repos with sanity', long_description=long_description,
nosarthur/gita
f6a1d98f81f23ad4789ad1af2d22f3cf829964ba
diff --git a/tests/test_main.py b/tests/test_main.py index 1d05e2f..1b23bee 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -196,6 +196,28 @@ class TestGroupCmd: assert err == '' assert 'xx: a b\nyy: a c d\n' == out + @patch('gita.utils.get_config_fname', return_value=GROUP_FNAME) + @patch('gita.utils.write_to_groups_file') + def testRename(self, mock_write, _): + args = argparse.Namespace() + args.gname = 'xx' + args.new_name = 'zz' + args.group_cmd = 'rename' + utils.get_groups.cache_clear() + __main__.f_group(args) + expected = {'yy': ['a', 'c', 'd'], 'zz': ['a', 'b']} + mock_write.assert_called_once_with(expected, 'w') + + @patch('gita.utils.get_config_fname', return_value=GROUP_FNAME) + def testRenameError(self, *_): + args = argparse.Namespace() + args.gname = 'xx' + args.new_name = 'yy' + args.group_cmd = 'rename' + utils.get_groups.cache_clear() + with pytest.raises(SystemExit, match='yy already exists.'): + __main__.f_group(args) + @pytest.mark.parametrize('input, expected', [ ('xx', {'yy': ['a', 'c', 'd']}), ("xx yy", {}),
Add some additional options for group subcommand Few different ideas, all related to groups: 1. For `group add`, would it be possible to add a `--to <group>` flag, so it is easier to script the tool. Currently it requires the user to stop and enter the group name 1. Would a `group rename` be hard? 1. Would an `ls` alias on `ll` be hard e.g. `gita group ls`. This would mirror the main gita API Thanks for a useful tool!
0.0
[ "tests/test_main.py::TestGroupCmd::testRename", "tests/test_main.py::TestGroupCmd::testRenameError" ]
[ "tests/test_main.py::TestLsLl::testLs", "tests/test_main.py::TestLsLl::testWithPathFiles[/root/data/temp_dir/tmpa0ez3sm0/nosarthur__gita__0.0/tests/mock_path_file-repo1", "tests/test_main.py::TestLsLl::testWithPathFiles[/root/data/temp_dir/tmpa0ez3sm0/nosarthur__gita__0.0/tests/empty_path_file-]", "tests/test_main.py::TestLsLl::testWithPathFiles[/root/data/temp_dir/tmpa0ez3sm0/nosarthur__gita__0.0/tests/clash_path_file-repo1", "tests/test_main.py::test_rm", "tests/test_main.py::test_not_add", "tests/test_main.py::test_fetch", "tests/test_main.py::test_async_fetch", "tests/test_main.py::test_superman[diff", "tests/test_main.py::test_superman[commit", "tests/test_main.py::TestContext::testDisplayNoContext", "tests/test_main.py::TestContext::testDisplayContext", "tests/test_main.py::TestContext::testReset", "tests/test_main.py::TestContext::testSetFirstTime", "tests/test_main.py::TestContext::testSetSecondTime", "tests/test_main.py::TestGroupCmd::testLs", "tests/test_main.py::TestGroupCmd::testLl", "tests/test_main.py::TestGroupCmd::testRm[xx-expected0]", "tests/test_main.py::TestGroupCmd::testRm[xx", "tests/test_main.py::TestGroupCmd::testAdd", "tests/test_main.py::TestGroupCmd::testAddToExisting", "tests/test_main.py::test_rename", "tests/test_main.py::test_info" ]
2020-10-25 00:40:00+00:00
4,233
nosarthur__gita-108
diff --git a/gita/__main__.py b/gita/__main__.py index e00f20d..13a048e 100644 --- a/gita/__main__.py +++ b/gita/__main__.py @@ -57,7 +57,7 @@ def f_ll(args: argparse.Namespace): if args.group: # only display repos in this group group_repos = utils.get_groups()[args.group] repos = {k: repos[k] for k in group_repos if k in repos} - for line in utils.describe(repos): + for line in utils.describe(repos, no_colors=args.no_colors): print(line) @@ -245,6 +245,8 @@ def main(argv=None): nargs='?', choices=utils.get_groups(), help="show repos in the chosen group") + p_ll.add_argument('-n', '--no-colors', action='store_true', + help='Disable coloring on the branch names.') p_ll.set_defaults(func=f_ll) p_context = subparsers.add_parser('context', diff --git a/gita/info.py b/gita/info.py index 18d20fd..2d1d33f 100644 --- a/gita/info.py +++ b/gita/info.py @@ -42,6 +42,7 @@ def get_info_items() -> Tuple[Dict[str, Callable[[str], str]], List[str]]: 'path': get_path, } display_items = ['branch', 'commit_msg'] + # FIXME: remove these code # custom settings root = common.get_config_dir() src_fname = os.path.join(root, 'extra_repo_info.py') @@ -113,13 +114,15 @@ def get_commit_msg(path: str) -> str: return result.stdout.strip() -def get_repo_status(path: str) -> str: +def get_repo_status(path: str, no_colors=False) -> str: head = get_head(path) - dirty, staged, untracked, color = _get_repo_status(path) - return f'{color}{head+" "+dirty+staged+untracked:<10}{Color.end}' + dirty, staged, untracked, color = _get_repo_status(path, no_colors) + if color: + return f'{color}{head+" "+dirty+staged+untracked:<10}{Color.end}' + return f'{head+" "+dirty+staged+untracked:<10}' -def _get_repo_status(path: str) -> Tuple[str]: +def _get_repo_status(path: str, no_colors: bool) -> Tuple[str]: """ Return the status of one repo """ @@ -128,6 +131,9 @@ def _get_repo_status(path: str) -> Tuple[str]: staged = '+' if run_quiet_diff(['--cached']) else '' untracked = '_' if has_untracked() else '' + if no_colors: + return dirty, staged, untracked, '' + diff_returncode = run_quiet_diff(['@{u}', '@{0}']) has_no_remote = diff_returncode == 128 has_no_diff = diff_returncode == 0 diff --git a/gita/utils.py b/gita/utils.py index 900aefa..cc0a354 100644 --- a/gita/utils.py +++ b/gita/utils.py @@ -2,7 +2,7 @@ import os import yaml import asyncio import platform -from functools import lru_cache +from functools import lru_cache, partial from pathlib import Path from typing import List, Dict, Coroutine, Union @@ -197,13 +197,19 @@ def exec_async_tasks(tasks: List[Coroutine]) -> List[Union[None, str]]: return errors -def describe(repos: Dict[str, str]) -> str: +def describe(repos: Dict[str, str], no_colors: bool=False) -> str: """ Return the status of all repos """ if repos: name_width = max(len(n) for n in repos) + 1 funcs = info.get_info_funcs() + + get_repo_status = info.get_repo_status + if get_repo_status in funcs and no_colors: + idx = funcs.index(get_repo_status) + funcs[idx] = partial(get_repo_status, no_colors=True) + for name in sorted(repos): path = repos[name] display_items = ' '.join(f(path) for f in funcs) diff --git a/setup.py b/setup.py index 0cdd33f..cf4ab90 100644 --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ with open('README.md', encoding='utf-8') as f: setup( name='gita', packages=['gita'], - version='0.11.6', + version='0.11.7', license='MIT', description='Manage multiple git repos with sanity', long_description=long_description,
nosarthur/gita
cd179b31458ccad98fdb62c13ba394a4fc7a2cf3
diff --git a/tests/test_main.py b/tests/test_main.py index 1b23bee..1d6c9f6 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -5,7 +5,7 @@ import argparse import shlex from gita import __main__ -from gita import utils +from gita import utils, info from conftest import ( PATH_FNAME, PATH_FNAME_EMPTY, PATH_FNAME_CLASH, GROUP_FNAME, async_mock, TEST_DIR, @@ -35,6 +35,14 @@ class TestLsLl: out, err = capfd.readouterr() assert err == '' assert 'gita' in out + assert info.Color.end in out + + # no color on branch name + __main__.main(['ll', '-n']) + out, err = capfd.readouterr() + assert err == '' + assert 'gita' in out + assert info.Color.end not in out __main__.main(['ls', 'gita']) out, err = capfd.readouterr() diff --git a/tests/test_utils.py b/tests/test_utils.py index dfabcee..607a33b 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -9,12 +9,9 @@ from conftest import ( @pytest.mark.parametrize('test_input, diff_return, expected', [ - ({ - 'abc': '/root/repo/' - }, True, 'abc \x1b[31mrepo *+_ \x1b[0m msg'), - ({ - 'repo': '/root/repo2/' - }, False, 'repo \x1b[32mrepo _ \x1b[0m msg'), + ([{'abc': '/root/repo/'}, False], True, 'abc \x1b[31mrepo *+_ \x1b[0m msg'), + ([{'abc': '/root/repo/'}, True], True, 'abc repo *+_ msg'), + ([{'repo': '/root/repo2/'}, False], False, 'repo \x1b[32mrepo _ \x1b[0m msg'), ]) def test_describe(test_input, diff_return, expected, monkeypatch): monkeypatch.setattr(info, 'get_head', lambda x: 'repo') @@ -23,8 +20,8 @@ def test_describe(test_input, diff_return, expected, monkeypatch): monkeypatch.setattr(info, 'has_untracked', lambda: True) monkeypatch.setattr('os.chdir', lambda x: None) print('expected: ', repr(expected)) - print('got: ', repr(next(utils.describe(test_input)))) - assert expected == next(utils.describe(test_input)) + print('got: ', repr(next(utils.describe(*test_input)))) + assert expected == next(utils.describe(*test_input)) @pytest.mark.parametrize('path_fname, expected', [
A no colour option for when running through either a script or cron. I am using gita to backup some repositories so need to run `gita ll` (just to see what will change) then do `gita pull`. Because this runs through cron, I get some ugly control characters instead of colours. Would it be possible to add a `--no-colours` option? Thank you
0.0
[ "tests/test_utils.py::test_describe[test_input0-True-abc", "tests/test_utils.py::test_describe[test_input1-True-abc", "tests/test_utils.py::test_describe[test_input2-False-repo" ]
[ "tests/test_main.py::TestLsLl::testLs", "tests/test_main.py::TestLsLl::testWithPathFiles[/root/data/temp_dir/tmputd0g9yt/nosarthur__gita__0.0/tests/mock_path_file-repo1", "tests/test_main.py::TestLsLl::testWithPathFiles[/root/data/temp_dir/tmputd0g9yt/nosarthur__gita__0.0/tests/empty_path_file-]", "tests/test_main.py::TestLsLl::testWithPathFiles[/root/data/temp_dir/tmputd0g9yt/nosarthur__gita__0.0/tests/clash_path_file-repo1", "tests/test_main.py::test_rm", "tests/test_main.py::test_not_add", "tests/test_main.py::test_fetch", "tests/test_main.py::test_async_fetch", "tests/test_main.py::test_superman[diff", "tests/test_main.py::test_superman[commit", "tests/test_main.py::TestContext::testDisplayNoContext", "tests/test_main.py::TestContext::testDisplayContext", "tests/test_main.py::TestContext::testReset", "tests/test_main.py::TestContext::testSetFirstTime", "tests/test_main.py::TestContext::testSetSecondTime", "tests/test_main.py::TestGroupCmd::testLs", "tests/test_main.py::TestGroupCmd::testLl", "tests/test_main.py::TestGroupCmd::testRename", "tests/test_main.py::TestGroupCmd::testRenameError", "tests/test_main.py::TestGroupCmd::testRm[xx-expected0]", "tests/test_main.py::TestGroupCmd::testRm[xx", "tests/test_main.py::TestGroupCmd::testAdd", "tests/test_main.py::TestGroupCmd::testAddToExisting", "tests/test_main.py::test_rename", "tests/test_main.py::test_info", "tests/test_utils.py::test_get_repos[/root/data/temp_dir/tmputd0g9yt/nosarthur__gita__0.0/tests/mock_path_file-expected0]", "tests/test_utils.py::test_get_repos[/root/data/temp_dir/tmputd0g9yt/nosarthur__gita__0.0/tests/empty_path_file-expected1]", "tests/test_utils.py::test_get_repos[/root/data/temp_dir/tmputd0g9yt/nosarthur__gita__0.0/tests/clash_path_file-expected2]", "tests/test_utils.py::test_get_context", "tests/test_utils.py::test_get_groups[/root/data/temp_dir/tmputd0g9yt/nosarthur__gita__0.0/tests/mock_group_file-expected0]", "tests/test_utils.py::test_custom_push_cmd", "tests/test_utils.py::test_add_repos[path_input0-/home/some/repo,repo\\n]", "tests/test_utils.py::test_add_repos[path_input1-expected1]", "tests/test_utils.py::test_add_repos[path_input2-/home/some/repo1,repo1\\n]", "tests/test_utils.py::test_rename_repo", "tests/test_utils.py::test_async_output" ]
2020-10-31 05:10:13+00:00
4,234
nosarthur__gita-122
diff --git a/README.md b/README.md index f76c759..1c9b321 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,7 @@ To see the pre-defined sub-commands, run `gita -h` or take a look at [cmds.yml](https://github.com/nosarthur/gita/blob/master/gita/cmds.yml). To add your own sub-commands, see the [customization section](#custom). To run arbitrary `git` command, see the [superman mode section](#superman). +To run arbitrary shell command, see the [shell mode section](#shell). The branch color distinguishes 5 situations between local and remote branches: @@ -157,6 +158,21 @@ For example, - `gita super frontend-repo backend-repo commit -am 'implement a new feature'` executes `git commit -am 'implement a new feature'` for `frontend-repo` and `backend-repo` +## <a name='shell'></a> Shell mode + +The shell mode delegates any shell command. +Usage: + +``` +gita shell [repo-name(s) or group-name(s)] <any-shell-command> +``` + +Here `repo-name(s)` or `group-name(s)` are optional, and their absence means all repos. +For example, + +- `gita shell ll` lists contents for all repos +- `gita shell repo1 mkdir docs` create a new directory `docs` in repo1 + ## <a name='custom'></a> Customization ### user-defined sub-command using yaml file @@ -195,6 +211,12 @@ comaster: help: checkout the master branch ``` +### customize the local/remote relationship coloring displayed by the `gita ll` command + +You can see the default color scheme and the available colors via `gita color`. +To change the color coding, use `gita color set <situation> <color>`. +The configuration is saved in `$XDG_CONFIG_HOME/gita/color.yml`. + ### customize information displayed by the `gita ll` command You can customize the information displayed by `gita ll`. @@ -208,12 +230,6 @@ For example, the default information items setting corresponds to - commit_msg ``` -### customize the local/remote relationship coloring displayed by the `gita ll` command - -You can see the default color scheme and the available colors via `gita color`. -To change the color coding, use `gita color set <situation> <color>`. -The configuration is saved in `$XDG_CONFIG_HOME/gita/color.yml`. - ## Requirements Gita requires Python 3.6 or higher, due to the use of diff --git a/gita/__main__.py b/gita/__main__.py index 43116df..beecab2 100644 --- a/gita/__main__.py +++ b/gita/__main__.py @@ -222,6 +222,42 @@ def f_git_cmd(args: argparse.Namespace): subprocess.run(cmds, cwd=path) +def f_shell(args): + """ + Delegate shell command defined in `args.man`, which may or may not + contain repo names. + """ + names = [] + repos = utils.get_repos() + groups = utils.get_groups() + ctx = utils.get_context() + for i, word in enumerate(args.man): + if word in repos or word in groups: + names.append(word) + else: + break + args.repo = names + # TODO: redundant with f_git_cmd + if not args.repo and ctx: + args.repo = [ctx.stem] + if args.repo: # with user specified repo(s) or group(s) + chosen = {} + for k in args.repo: + if k in repos: + chosen[k] = repos[k] + if k in groups: + for r in groups[k]: + chosen[r] = repos[r] + repos = chosen + cmds = args.man[i:] + for name, path in repos.items(): + # TODO: pull this out as a function + got = subprocess.run(cmds, cwd=path, check=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT) + print(utils.format_output(got.stdout.decode(), name)) + + def f_super(args): """ Delegate git command/alias defined in `args.man`, which may or may not @@ -415,6 +451,21 @@ def main(argv=None): "Another: gita super checkout master ") p_super.set_defaults(func=f_super) + # shell mode + p_shell = subparsers.add_parser( + 'shell', + description='shell mode: delegate any shell command in specified or ' + 'all repo(s).\n' + 'Examples:\n \t gita shell pwd\n' + '\t gita shell repo1 repo2 repo3 touch xx') + p_shell.add_argument( + 'man', + nargs=argparse.REMAINDER, + help="execute arbitrary shell command for specified or all repos " + "Example: gita shell myrepo1 ls" + "Another: gita shell git checkout master ") + p_shell.set_defaults(func=f_shell) + # sub-commands that fit boilerplate cmds = utils.get_cmds_from_files() for name, data in cmds.items(): diff --git a/gita/utils.py b/gita/utils.py index 1d334ad..9572f02 100644 --- a/gita/utils.py +++ b/gita/utils.py @@ -167,7 +167,7 @@ async def run_async(repo_name: str, path: str, cmds: List[str]) -> Union[None, s stdout, stderr = await process.communicate() for pipe in (stdout, stderr): if pipe: - print(format_output(pipe.decode(), f'{repo_name}: ')) + print(format_output(pipe.decode(), repo_name)) # The existence of stderr is not good indicator since git sometimes write # to stderr even if the execution is successful, e.g. git fetch if process.returncode != 0: @@ -178,7 +178,7 @@ def format_output(s: str, prefix: str): """ Prepends every line in given string with the given prefix. """ - return ''.join([f'{prefix}{line}' for line in s.splitlines(keepends=True)]) + return ''.join([f'{prefix}: {line}' for line in s.splitlines(keepends=True)]) def exec_async_tasks(tasks: List[Coroutine]) -> List[Union[None, str]]: diff --git a/setup.py b/setup.py index c6dbe0e..c729963 100644 --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ with open('README.md', encoding='utf-8') as f: setup( name='gita', packages=['gita'], - version='0.12.6', + version='0.12.7', license='MIT', description='Manage multiple git repos with sanity', long_description=long_description,
nosarthur/gita
b88fe6e0a2ae6670d4264837bd61704341646a75
diff --git a/tests/test_main.py b/tests/test_main.py index 2f51acf..ad501f7 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -159,6 +159,20 @@ def test_superman(mock_run, _, input): mock_run.assert_called_once_with(expected_cmds, cwd='path7') [email protected]('input', [ + 'diff --name-only --staged', + "commit -am 'lala kaka'", +]) +@patch('gita.utils.get_repos', return_value={'repo7': 'path7'}) +@patch('subprocess.run') +def test_shell(mock_run, _, input): + mock_run.reset_mock() + args = ['shell', 'repo7'] + shlex.split(input) + __main__.main(args) + expected_cmds = shlex.split(input) + mock_run.assert_called_once_with(expected_cmds, cwd='path7', check=True, stderr=-2, stdout=-1) + + class TestContext: @patch('gita.utils.get_context', return_value=None)
Allow execution of nested `git` commands Hi, thanks again for this excellent tool. The motivation comes from trying to get `gita` to checkout the latest tag for an entire group. The command is `git describe --abbrev=0 --tags` to get the latest tag, and `git checkout <tag>` to checkout the tag. This can be combined in bash with ``` git checkout $(git describe --abbrev=0 --tags) ``` I'm wondering if it's possible to execute this for multiple repos. Both the `cmds.yml` approach and using superman did not work for me. As a related issue, once a tag is checked out, `gita ll` simply shows `HEAD` for the status column. Is there a way to get it to display the checked out tag? I understand it's in detached head status, but `git status` shows `HEAD detached at v2.2.1` for example so there should be a way to fetch and display this information somehow.
0.0
[ "tests/test_main.py::test_shell[diff", "tests/test_main.py::test_shell[commit" ]
[ "tests/test_main.py::TestLsLl::testLs", "tests/test_main.py::TestLsLl::testWithPathFiles[/root/data/temp_dir/tmpm3gyw1cw/nosarthur__gita__0.0/tests/mock_path_file-repo1", "tests/test_main.py::TestLsLl::testWithPathFiles[/root/data/temp_dir/tmpm3gyw1cw/nosarthur__gita__0.0/tests/empty_path_file-]", "tests/test_main.py::TestLsLl::testWithPathFiles[/root/data/temp_dir/tmpm3gyw1cw/nosarthur__gita__0.0/tests/clash_path_file-repo1", "tests/test_main.py::test_freeze", "tests/test_main.py::test_rm", "tests/test_main.py::test_not_add", "tests/test_main.py::test_fetch", "tests/test_main.py::test_async_fetch", "tests/test_main.py::test_superman[diff", "tests/test_main.py::test_superman[commit", "tests/test_main.py::TestContext::testDisplayNoContext", "tests/test_main.py::TestContext::testDisplayContext", "tests/test_main.py::TestContext::testReset", "tests/test_main.py::TestContext::testSetFirstTime", "tests/test_main.py::TestContext::testSetSecondTime", "tests/test_main.py::TestGroupCmd::testLs", "tests/test_main.py::TestGroupCmd::testLl", "tests/test_main.py::TestGroupCmd::testRename", "tests/test_main.py::TestGroupCmd::testRenameError", "tests/test_main.py::TestGroupCmd::testRm[xx-expected0]", "tests/test_main.py::TestGroupCmd::testRm[xx", "tests/test_main.py::TestGroupCmd::testAdd", "tests/test_main.py::TestGroupCmd::testAddToExisting", "tests/test_main.py::TestGroupCmd::testRmRepo", "tests/test_main.py::test_rename", "tests/test_main.py::TestInfo::testLl", "tests/test_main.py::TestInfo::testAdd", "tests/test_main.py::TestInfo::testRm" ]
2021-01-13 05:53:07+00:00
4,235
nosarthur__gita-124
diff --git a/README.md b/README.md index 1c9b321..f07dc6e 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ I also hate to change directories to execute git commands. ![gita screenshot](https://github.com/nosarthur/gita/raw/master/doc/screenshot.png) In the screenshot, the `gita remote nowhub` command translates to `git remote -v` -for the `nowhub` repo, even though we are at the `blog` repo. +for the `nowhub` repo, even though we are in the `blog` repo. To see the pre-defined sub-commands, run `gita -h` or take a look at [cmds.yml](https://github.com/nosarthur/gita/blob/master/gita/cmds.yml). To add your own sub-commands, see the [customization section](#custom). @@ -70,7 +70,7 @@ The bookkeeping sub-commands are - `gita color set <situation> <color>`: Use the specified color for the local-remote situation - `gita freeze`: print information of all repos such as URL, name, and path. - `gita group`: group sub-command - - `gita group add <repo-name(s)> -n <group-name>`: add repo(s) to a new group or existing group + - `gita group add <repo-name(s)> -n <group-name>`: add repo(s) to a new or existing group - `gita group [ll]`: display existing groups with repos - `gita group ls`: display existing group names - `gita group rename <group-name> <new-name>`: change group name @@ -171,11 +171,12 @@ Here `repo-name(s)` or `group-name(s)` are optional, and their absence means all For example, - `gita shell ll` lists contents for all repos -- `gita shell repo1 mkdir docs` create a new directory `docs` in repo1 +- `gita shell repo1 repo2 mkdir docs` create a new directory `docs` in `repo1` and `repo2` +- `gita shell "git describe --abbrev=0 --tags | xargs git checkout"`: check out the latest tag for all repos ## <a name='custom'></a> Customization -### user-defined sub-command using yaml file +### add user-defined sub-command using yaml file Custom delegating sub-commands can be defined in `$XDG_CONFIG_HOME/gita/cmds.yml` (most likely `~/.config/gita/cmds.yml`). @@ -195,12 +196,11 @@ which executes `git diff --stat` for the specified repo(s). If the delegated `git` command is a single word, the `cmd` tag can be omitted. See `push` for an example. -To disable asynchronous execution, set the `disable_async` tag to be `true`. +To disable asynchronous execution, set `disable_async` to be `true`. See `difftool` for an example. -If you want a custom command to behave like `gita fetch`, i.e., to apply the -command to all repos when no repo is specified, -set the `allow_all` option to be `true`. +If you want a custom command to behave like `gita fetch`, i.e., to apply to all +repos when no repo is specified, set `allow_all` to be `true`. For example, the following snippet creates a new command `gita comaster [repo-name(s)]` with optional repo name input. @@ -223,7 +223,7 @@ You can customize the information displayed by `gita ll`. The used and unused information items are shown with `gita info`, and the configuration is saved in `$XDG_CONFIG_HOME/gita/info.yml`. -For example, the default information items setting corresponds to +For example, the default setting corresponds to ```yaml - branch diff --git a/gita/__main__.py b/gita/__main__.py index beecab2..a183c37 100644 --- a/gita/__main__.py +++ b/gita/__main__.py @@ -249,10 +249,10 @@ def f_shell(args): for r in groups[k]: chosen[r] = repos[r] repos = chosen - cmds = args.man[i:] + cmds = ' '.join(args.man[i:]) # join the shell command into a single string for name, path in repos.items(): # TODO: pull this out as a function - got = subprocess.run(cmds, cwd=path, check=True, + got = subprocess.run(cmds, cwd=path, check=True, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) print(utils.format_output(got.stdout.decode(), name)) diff --git a/gita/info.py b/gita/info.py index a8044e9..dc9d167 100644 --- a/gita/info.py +++ b/gita/info.py @@ -106,7 +106,8 @@ def get_path(path): def get_head(path: str) -> str: - result = subprocess.run('git rev-parse --abbrev-ref HEAD'.split(), + result = subprocess.run('git symbolic-ref -q --short HEAD || git describe --tags --exact-match', + shell=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, universal_newlines=True, diff --git a/setup.py b/setup.py index c729963..9f25098 100644 --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ with open('README.md', encoding='utf-8') as f: setup( name='gita', packages=['gita'], - version='0.12.7', + version='0.12.8', license='MIT', description='Manage multiple git repos with sanity', long_description=long_description,
nosarthur/gita
559dedf6b27bc0fea8d1030fde9820adfeb940f2
diff --git a/tests/test_main.py b/tests/test_main.py index ad501f7..7e3feb9 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -167,10 +167,10 @@ def test_superman(mock_run, _, input): @patch('subprocess.run') def test_shell(mock_run, _, input): mock_run.reset_mock() - args = ['shell', 'repo7'] + shlex.split(input) + args = ['shell', 'repo7', input] __main__.main(args) - expected_cmds = shlex.split(input) - mock_run.assert_called_once_with(expected_cmds, cwd='path7', check=True, stderr=-2, stdout=-1) + expected_cmds = input + mock_run.assert_called_once_with(expected_cmds, cwd='path7', check=True, shell=True, stderr=-2, stdout=-1) class TestContext:
Optionally display tags it could be one of the information items spun from #114
0.0
[ "tests/test_main.py::test_shell[diff", "tests/test_main.py::test_shell[commit" ]
[ "tests/test_main.py::TestLsLl::testLs", "tests/test_main.py::TestLsLl::testWithPathFiles[/root/data/temp_dir/tmp6h_zl2xh/nosarthur__gita__0.0/tests/mock_path_file-repo1", "tests/test_main.py::TestLsLl::testWithPathFiles[/root/data/temp_dir/tmp6h_zl2xh/nosarthur__gita__0.0/tests/empty_path_file-]", "tests/test_main.py::TestLsLl::testWithPathFiles[/root/data/temp_dir/tmp6h_zl2xh/nosarthur__gita__0.0/tests/clash_path_file-repo1", "tests/test_main.py::test_freeze", "tests/test_main.py::test_rm", "tests/test_main.py::test_not_add", "tests/test_main.py::test_fetch", "tests/test_main.py::test_async_fetch", "tests/test_main.py::test_superman[diff", "tests/test_main.py::test_superman[commit", "tests/test_main.py::TestContext::testDisplayNoContext", "tests/test_main.py::TestContext::testDisplayContext", "tests/test_main.py::TestContext::testReset", "tests/test_main.py::TestContext::testSetFirstTime", "tests/test_main.py::TestContext::testSetSecondTime", "tests/test_main.py::TestGroupCmd::testLs", "tests/test_main.py::TestGroupCmd::testLl", "tests/test_main.py::TestGroupCmd::testRename", "tests/test_main.py::TestGroupCmd::testRenameError", "tests/test_main.py::TestGroupCmd::testRm[xx-expected0]", "tests/test_main.py::TestGroupCmd::testRm[xx", "tests/test_main.py::TestGroupCmd::testAdd", "tests/test_main.py::TestGroupCmd::testAddToExisting", "tests/test_main.py::TestGroupCmd::testRmRepo", "tests/test_main.py::test_rename", "tests/test_main.py::TestInfo::testLl", "tests/test_main.py::TestInfo::testAdd", "tests/test_main.py::TestInfo::testRm" ]
2021-01-18 17:44:55+00:00
4,236
nosarthur__gita-170
diff --git a/README.md b/README.md index d260fac..4b4c516 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,8 @@ The additional status symbols denote The bookkeeping sub-commands are - `gita add <repo-path(s)>`: add repo(s) to `gita` +- `gita add -a <repo-parent-path(s)>`: add repo(s) in <repo-parent-path(s)> recursively + and automatically generate hierarchical groups. See the [customization section](#custom) for more details. - `gita add -b <bare-repo-path(s)>`: add bare repo(s) to `gita`. See the [customization section](#custom) for more details on setting custom worktree. - `gita add -m <main-repo-path(s)>`: add main repo(s) to `gita`. See the [customization section](#custom) for more details. - `gita add -r <repo-parent-path(s)>`: add repo(s) in <repo-parent-path(s)> recursively @@ -207,6 +209,32 @@ gita ll gita pull ``` +It is also possible to recursively add repos within a directory and +generate hierarchical groups automatically. For example, running + +``` +gita add -a src +``` +on the following folder structure +``` +src +├── project1 +│   ├── repo1 +│   └── repo2 +├── repo3 +├── project2 +│   ├── repo4 +│   └── repo5 +└── repo6 +``` +gives rise to +``` +src:repo1,repo2,repo3,repo4,repo5,repo6 +src-project1:repo1,repo2 +src-project2:repo4,repo5 +``` + + ### define main repos and shadow the global configuration setting with local setting The so-called main repos contain `.gita` folder for local configurations. diff --git a/doc/README_CN.md b/doc/README_CN.md index 45f5926..03d96a7 100644 --- a/doc/README_CN.md +++ b/doc/README_CN.md @@ -46,6 +46,7 @@ 基础指令: - `gita add <repo-path(s)>`: 添加库 +- `gita add -a <repo-parent-path(s)>`: - `gita add -b <bare-repo-path(s)>`: - `gita add -m <main-repo-path(s)>`: - `gita add -r <repo-parent-path(s)>`: diff --git a/gita/__main__.py b/gita/__main__.py index 5288632..ee4e7e7 100644 --- a/gita/__main__.py +++ b/gita/__main__.py @@ -52,11 +52,16 @@ def f_add(args: argparse.Namespace): sub_paths = glob.glob(os.path.join(main_path,'**/'), recursive=True) utils.add_repos({}, sub_paths, root=main_path) else: - if args.recursive: + if args.recursive or args.auto_group: paths = chain.from_iterable( glob.glob(os.path.join(p, '**/'), recursive=True) for p in args.paths) - utils.add_repos(repos, paths, is_bare=args.bare) + new_repos = utils.add_repos(repos, paths, is_bare=args.bare) + if args.auto_group: + new_groups = utils.auto_group(new_repos, args.paths) + if new_groups: + print(f'Created {len(new_groups)} new group(s).') + utils.write_to_groups_file(new_groups, 'a+') def f_rename(args: argparse.Namespace): @@ -377,12 +382,15 @@ def main(argv=None): # bookkeeping sub-commands p_add = subparsers.add_parser('add', description='add repo(s)', help='add repo(s)') - p_add.add_argument('paths', nargs='+', help="repo(s) to add") + p_add.add_argument('paths', nargs='+', type=os.path.abspath, help="repo(s) to add") xgroup = p_add.add_mutually_exclusive_group() xgroup.add_argument('-r', '--recursive', action='store_true', - help="recursively add repo(s) in the given path.") + help="recursively add repo(s) in the given path(s).") xgroup.add_argument('-m', '--main', action='store_true', help="make main repo(s), sub-repos are recursively added.") + xgroup.add_argument('-a', '--auto-group', action='store_true', + help="recursively add repo(s) in the given path(s) " + "and create hierarchical groups based on folder structure.") xgroup.add_argument('-b', '--bare', action='store_true', help="add bare repo(s)") p_add.set_defaults(func=f_add) diff --git a/gita/utils.py b/gita/utils.py index 21d7a8f..34fc435 100644 --- a/gita/utils.py +++ b/gita/utils.py @@ -6,8 +6,8 @@ import platform import subprocess from functools import lru_cache, partial from pathlib import Path -from typing import List, Dict, Coroutine, Union, Iterator -from collections import Counter +from typing import List, Dict, Coroutine, Union, Iterator, Tuple +from collections import Counter, defaultdict from . import info from . import common @@ -187,7 +187,7 @@ def _make_name(path: str, repos: Dict[str, Dict[str, str]], Given a new repo `path`, create a repo name. By default, basename is used. If name collision exists, further include parent path name. - @param path: It should not be in `repos` + @param path: It should not be in `repos` and is absolute """ name = os.path.basename(os.path.normpath(path)) if name in repos or name_counts[name] > 1: @@ -202,7 +202,7 @@ def _get_repo_type(path, repo_type, root) -> str: """ if repo_type != '': # explicitly set return repo_type - if root == path: # main repo + if root is not None and os.path.normpath(root) == os.path.normpath(path): return 'm' return '' @@ -215,7 +215,7 @@ def add_repos(repos: Dict[str, Dict[str, str]], new_paths: List[str], @param repos: name -> path """ existing_paths = {prop['path'] for prop in repos.values()} - new_paths = {os.path.abspath(p) for p in new_paths if is_git(p, is_bare)} + new_paths = {p for p in new_paths if is_git(p, is_bare)} new_paths = new_paths - existing_paths new_repos = {} if new_paths: @@ -236,6 +236,42 @@ def add_repos(repos: Dict[str, Dict[str, str]], new_paths: List[str], return new_repos +def _generate_dir_hash(repo_path: str, paths: List[str]) -> Tuple[str, ...]: + """ + Return relative parent strings + + For example, if `repo_path` is /a/b/c/d/here, and one of `paths` is /a/b/ + then return (b, c, d) + """ + for p in paths: + if is_relative_to(repo_path, p): + break + else: + return () + return (os.path.basename(p), + *os.path.normpath(os.path.relpath(repo_path, p)).split(os.sep)[:-1]) + + +def auto_group(repos: Dict[str, Dict[str, str]], paths: List[str] + ) -> Dict[str, List[str]]: + """ + + """ + # FIXME: the upstream code should make sure that paths are all independent + # i.e., each repo should be contained in one and only one path + new_groups = defaultdict(list) + for repo_name, prop in repos.items(): + hash = _generate_dir_hash(prop['path'], paths) + if not hash: + continue + for i in range(1, len(hash)+1): + group_name = '-'.join(hash[:i]) + new_groups[group_name].append(repo_name) + # FIXME: need to make sure the new group names don't clash with old ones + # or repo names + return new_groups + + def parse_clone_config(fname: str) -> Iterator[List[str]]: """ Return the url, name, and path of all repos in `fname`. diff --git a/setup.py b/setup.py index 8bf0fc9..6fb92eb 100644 --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ with open('README.md', encoding='utf-8') as f: setup( name='gita', packages=['gita'], - version='0.15.0', + version='0.15.1', license='MIT', description='Manage multiple git repos with sanity', long_description=long_description,
nosarthur/gita
e1b16e0df4708e8ebe6a91c8009ab3e2bc8ccbc9
diff --git a/tests/test_main.py b/tests/test_main.py index 6223660..490f5d2 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -29,7 +29,7 @@ class TestAdd: (['add', '-m', '.'], 'm'), ]) @patch('gita.common.get_config_fname') - def testAdd(self, mock_path_fname, tmp_path, input, expected): + def test_add(self, mock_path_fname, tmp_path, input, expected): def side_effect(input, _=None): return tmp_path / f'{input}.txt' mock_path_fname.side_effect = side_effect @@ -88,7 +88,7 @@ def test_flags(mock_path_fname, _, __, path_fname, expected, capfd): class TestLsLl: @patch('gita.common.get_config_fname') - def testLl(self, mock_path_fname, capfd, tmp_path): + def test_ll(self, mock_path_fname, capfd, tmp_path): """ functional test """ @@ -128,7 +128,7 @@ class TestLsLl: assert err == '' assert out.strip() == utils.get_repos()['gita']['path'] - def testLs(self, monkeypatch, capfd): + def test_ls(self, monkeypatch, capfd): monkeypatch.setattr(utils, 'get_repos', lambda: {'repo1': {'path': '/a/'}, 'repo2': {'path': '/b/'}}) monkeypatch.setattr(utils, 'describe', lambda x: x) @@ -157,7 +157,7 @@ class TestLsLl: @patch('gita.info.get_commit_msg', return_value="msg") @patch('gita.info.get_commit_time', return_value="") @patch('gita.common.get_config_fname') - def testWithPathFiles(self, mock_path_fname, _0, _1, _2, _3, _4, path_fname, + def test_with_path_files(self, mock_path_fname, _0, _1, _2, _3, _4, path_fname, expected, capfd): def side_effect(input, _=None): if input == 'repos.csv': @@ -301,21 +301,21 @@ class TestContext: @patch('gita.utils.get_context', return_value=Path('gname.context')) @patch('gita.utils.get_groups', return_value={'gname': ['a', 'b']}) - def testDisplayContext(self, _, __, capfd): + def test_display_context(self, _, __, capfd): __main__.main(['context']) out, err = capfd.readouterr() assert err == '' assert 'gname: a b\n' == out @patch('gita.utils.get_context') - def testReset(self, mock_ctx): + def test_reset(self, mock_ctx): __main__.main(['context', 'none']) mock_ctx.return_value.unlink.assert_called() @patch('gita.utils.get_context', return_value=None) @patch('gita.common.get_config_dir', return_value=TEST_DIR) @patch('gita.utils.get_groups', return_value={'lala': ['b'], 'kaka': []}) - def testSetFirstTime(self, *_): + def test_set_first_time(self, *_): ctx = TEST_DIR / 'lala.context' assert not ctx.is_file() __main__.main(['context', 'lala']) @@ -325,7 +325,7 @@ class TestContext: @patch('gita.common.get_config_dir', return_value=TEST_DIR) @patch('gita.utils.get_groups', return_value={'lala': ['b'], 'kaka': []}) @patch('gita.utils.get_context') - def testSetSecondTime(self, mock_ctx, *_): + def test_set_second_time(self, mock_ctx, *_): __main__.main(['context', 'kaka']) mock_ctx.return_value.rename.assert_called() @@ -333,7 +333,7 @@ class TestContext: class TestGroupCmd: @patch('gita.common.get_config_fname', return_value=GROUP_FNAME) - def testLs(self, _, capfd): + def test_ls(self, _, capfd): args = argparse.Namespace() args.to_group = None args.group_cmd = 'ls' @@ -344,7 +344,7 @@ class TestGroupCmd: assert 'xx yy\n' == out @patch('gita.common.get_config_fname', return_value=GROUP_FNAME) - def testLl(self, _, capfd): + def test_ll(self, _, capfd): args = argparse.Namespace() args.to_group = None args.group_cmd = None @@ -356,7 +356,7 @@ class TestGroupCmd: @patch('gita.common.get_config_fname', return_value=GROUP_FNAME) @patch('gita.utils.write_to_groups_file') - def testRename(self, mock_write, _): + def test_rename(self, mock_write, _): args = argparse.Namespace() args.gname = 'xx' args.new_name = 'zz' @@ -367,7 +367,7 @@ class TestGroupCmd: mock_write.assert_called_once_with(expected, 'w') @patch('gita.common.get_config_fname', return_value=GROUP_FNAME) - def testRenameError(self, *_): + def test_rename_error(self, *_): args = argparse.Namespace() args.gname = 'xx' args.new_name = 'yy' @@ -383,7 +383,7 @@ class TestGroupCmd: @patch('gita.utils.get_repos', return_value={'a': '', 'b': '', 'c': '', 'd': ''}) @patch('gita.common.get_config_fname', return_value=GROUP_FNAME) @patch('gita.utils.write_to_groups_file') - def testRm(self, mock_write, _, __, input, expected): + def test_rm(self, mock_write, _, __, input, expected): utils.get_groups.cache_clear() args = ['group', 'rm'] + shlex.split(input) __main__.main(args) @@ -392,7 +392,7 @@ class TestGroupCmd: @patch('gita.utils.get_repos', return_value={'a': '', 'b': '', 'c': '', 'd': ''}) @patch('gita.common.get_config_fname', return_value=GROUP_FNAME) @patch('gita.utils.write_to_groups_file') - def testAdd(self, mock_write, *_): + def test_add(self, mock_write, *_): args = argparse.Namespace() args.to_group = ['a', 'c'] args.group_cmd = 'add' @@ -404,7 +404,7 @@ class TestGroupCmd: @patch('gita.utils.get_repos', return_value={'a': '', 'b': '', 'c': '', 'd': ''}) @patch('gita.common.get_config_fname', return_value=GROUP_FNAME) @patch('gita.utils.write_to_groups_file') - def testAddToExisting(self, mock_write, *_): + def test_add_to_existing(self, mock_write, *_): args = argparse.Namespace() args.to_group = ['a', 'c'] args.group_cmd = 'add' @@ -417,7 +417,7 @@ class TestGroupCmd: @patch('gita.utils.get_repos', return_value={'a': '', 'b': '', 'c': '', 'd': ''}) @patch('gita.common.get_config_fname', return_value=GROUP_FNAME) @patch('gita.utils.write_to_groups_file') - def testRmRepo(self, mock_write, *_): + def test_rm_repo(self, mock_write, *_): args = argparse.Namespace() args.from_group = ['a', 'c'] args.group_cmd = 'rmrepo' diff --git a/tests/test_utils.py b/tests/test_utils.py index 78c496b..39430b0 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -10,6 +10,27 @@ from conftest import ( ) [email protected]('repo_path, paths, expected', [ + ('/a/b/c/repo', ['/a/b'], ('b', 'c')), + ]) +def test_generate_dir_hash(repo_path, paths, expected): + got = utils._generate_dir_hash(repo_path, paths) + assert got == expected + + [email protected]('repos, paths, expected', [ + ({'r1': {'path': '/a/b//repo1'}, 'r2': {'path': '/a/b/repo2'}}, + ['/a/b'], {'b': ['r1', 'r2']}), + ({'r1': {'path': '/a/b//repo1'}, 'r2': {'path': '/a/b/c/repo2'}}, + ['/a/b'], {'b': ['r1', 'r2'], 'b-c': ['r2']}), + ({'r1': {'path': '/a/b/c/repo1'}, 'r2': {'path': '/a/b/c/repo2'}}, + ['/a/b'], {'b-c': ['r1', 'r2'], 'b': ['r1', 'r2']}), + ]) +def test_auto_group(repos, paths, expected): + got = utils.auto_group(repos, paths) + assert got == expected + + @pytest.mark.parametrize('test_input, diff_return, expected', [ ([{'abc': {'path': '/root/repo/', 'type': '', 'flags': []}}, False], True, 'abc \x1b[31mrepo *+_ \x1b[0m msg xx'), @@ -83,7 +104,7 @@ def test_custom_push_cmd(*_): @pytest.mark.parametrize( 'path_input, expected', [ - (['/home/some/repo/'], '/home/some/repo,some/repo,,\r\n'), # add one new + (['/home/some/repo'], '/home/some/repo,some/repo,,\r\n'), # add one new (['/home/some/repo1', '/repo2'], {'/repo2,repo2,,\r\n', # add two new '/home/some/repo1,repo1,,\r\n'}), # add two new
Allow automatic group creation on recursive add Use case: I've got tons of git repos I need to manage, but they are already nicely grouped into folders (e.g. `Work/Client-5/Project-4/Service-1/<code>`). Currently I'm using `gita add -r` to add them all, then grouping using bash (e.g. `for i in $(gita ls); do echo "target-group" | gita group add $i; done` With #93 we got a lovely `-r` flag on the add command. Would it be possible to add a `--auto-group` flag that only works if `-r` was passed. Preferably, this would cause groups to be created after the add, with one group per parent folder (e.g. a repo stored at `Foo/Bar/Code` would be in two different groups, `Foo`, `Bar`. It would also be fine if the tool auto-created groups as `Foo` and `Foo-Bar` (to avoid issues where subfolders might have the same names as other projects). Thoughts?
0.0
[ "tests/test_utils.py::test_generate_dir_hash[/a/b/c/repo-paths0-expected0]", "tests/test_utils.py::test_auto_group[repos0-paths0-expected0]", "tests/test_utils.py::test_auto_group[repos1-paths1-expected1]", "tests/test_utils.py::test_auto_group[repos2-paths2-expected2]" ]
[ "tests/test_main.py::test_group_name", "tests/test_main.py::TestAdd::test_add_main", "tests/test_main.py::test_flags[/root/data/temp_dir/tmp73pfyuqv/nosarthur__gita__0.0/tests/mock_path_file-]", "tests/test_main.py::test_flags[/root/data/temp_dir/tmp73pfyuqv/nosarthur__gita__0.0/tests/clash_path_file-repo2:", "tests/test_main.py::TestLsLl::test_ls", "tests/test_main.py::TestLsLl::test_with_path_files[/root/data/temp_dir/tmp73pfyuqv/nosarthur__gita__0.0/tests/mock_path_file-repo1", "tests/test_main.py::TestLsLl::test_with_path_files[/root/data/temp_dir/tmp73pfyuqv/nosarthur__gita__0.0/tests/empty_path_file-]", "tests/test_main.py::TestLsLl::test_with_path_files[/root/data/temp_dir/tmp73pfyuqv/nosarthur__gita__0.0/tests/main_path_file-\\x1b[4mmain1\\x1b[0m", "tests/test_main.py::TestLsLl::test_with_path_files[/root/data/temp_dir/tmp73pfyuqv/nosarthur__gita__0.0/tests/clash_path_file-repo1", "tests/test_main.py::test_freeze[input0-]", "tests/test_main.py::test_clone", "tests/test_main.py::test_clone_with_preserve_path", "tests/test_main.py::test_rm", "tests/test_main.py::test_not_add", "tests/test_main.py::test_fetch", "tests/test_main.py::test_async_fetch", "tests/test_main.py::test_superman[diff", "tests/test_main.py::test_superman[commit", "tests/test_main.py::test_shell[diff", "tests/test_main.py::test_shell[commit", "tests/test_main.py::TestContext::testDisplayNoContext", "tests/test_main.py::TestContext::test_display_context", "tests/test_main.py::TestContext::test_reset", "tests/test_main.py::TestContext::test_set_first_time", "tests/test_main.py::TestContext::test_set_second_time", "tests/test_main.py::TestGroupCmd::test_ls", "tests/test_main.py::TestGroupCmd::test_ll", "tests/test_main.py::TestGroupCmd::test_rename", "tests/test_main.py::TestGroupCmd::test_rename_error", "tests/test_main.py::TestGroupCmd::test_rm[xx-expected0]", "tests/test_main.py::TestGroupCmd::test_rm[xx", "tests/test_main.py::TestGroupCmd::test_add", "tests/test_main.py::TestGroupCmd::test_add_to_existing", "tests/test_main.py::TestGroupCmd::test_rm_repo", "tests/test_main.py::test_rename", "tests/test_main.py::TestInfo::test_ll", "tests/test_main.py::TestInfo::test_add", "tests/test_main.py::TestInfo::test_rm", "tests/test_main.py::test_set_color", "tests/test_utils.py::test_describe[test_input0-True-abc", "tests/test_utils.py::test_describe[test_input1-True-abc", "tests/test_utils.py::test_describe[test_input2-False-repo", "tests/test_utils.py::test_get_repos[/root/data/temp_dir/tmp73pfyuqv/nosarthur__gita__0.0/tests/mock_path_file-expected0]", "tests/test_utils.py::test_get_repos[/root/data/temp_dir/tmp73pfyuqv/nosarthur__gita__0.0/tests/empty_path_file-expected1]", "tests/test_utils.py::test_get_repos[/root/data/temp_dir/tmp73pfyuqv/nosarthur__gita__0.0/tests/clash_path_file-expected2]", "tests/test_utils.py::test_get_context", "tests/test_utils.py::test_get_groups[/root/data/temp_dir/tmp73pfyuqv/nosarthur__gita__0.0/tests/mock_group_file-expected0]", "tests/test_utils.py::test_custom_push_cmd", "tests/test_utils.py::test_add_repos[path_input0-/home/some/repo,some/repo,,\\r\\n]", "tests/test_utils.py::test_add_repos[path_input1-expected1]", "tests/test_utils.py::test_add_repos[path_input2-/home/some/repo1,repo1,,\\r\\n]", "tests/test_utils.py::test_rename_repo", "tests/test_utils.py::test_async_output", "tests/test_utils.py::test_is_git" ]
2021-07-14 03:17:10+00:00
4,237
nosarthur__gita-196
diff --git a/gita/__main__.py b/gita/__main__.py index 73e12fb..d489f55 100644 --- a/gita/__main__.py +++ b/gita/__main__.py @@ -303,20 +303,11 @@ def f_git_cmd(args: argparse.Namespace): Delegate git command/alias defined in `args.cmd`. Asynchronous execution is disabled for commands in the `args.async_blacklist`. """ - repos = utils.get_repos() - groups = utils.get_groups() - ctx = utils.get_context() - if not args.repo and ctx: - args.repo = [ctx.stem] - if args.repo: # with user specified repo(s) or group(s) - chosen = {} - for k in args.repo: - if k in repos: - chosen[k] = repos[k] - if k in groups: - for r in groups[k]['repos']: - chosen[r] = repos[r] - repos = chosen + if '_parsed_repos' in args: + repos = args._parsed_repos + else: + repos, _ = utils.parse_repos_and_rest(args.repo) + per_repo_cmds = [] for prop in repos.values(): cmds = args.cmd.copy() @@ -351,29 +342,12 @@ def f_shell(args): Delegate shell command defined in `args.man`, which may or may not contain repo names. """ - names = [] - repos = utils.get_repos() - groups = utils.get_groups() - ctx = utils.get_context() - for i, word in enumerate(args.man): - if word in repos or word in groups: - names.append(word) - else: - break - args.repo = names - # TODO: redundant with f_git_cmd - if not args.repo and ctx: - args.repo = [ctx.stem] - if args.repo: # with user specified repo(s) or group(s) - chosen = {} - for k in args.repo: - if k in repos: - chosen[k] = repos[k] - if k in groups: - for r in groups[k]['repos']: - chosen[r] = repos[r] - repos = chosen - cmds = ' '.join(args.man[i:]) # join the shell command into a single string + repos, cmds = utils.parse_repos_and_rest(args.man) + if not cmds: + print('Missing commands') + sys.exit(2) + + cmds = ' '.join(cmds) # join the shell command into a single string for name, prop in repos.items(): # TODO: pull this out as a function got = subprocess.run(cmds, cwd=prop['path'], shell=True, @@ -387,16 +361,13 @@ def f_super(args): Delegate git command/alias defined in `args.man`, which may or may not contain repo names. """ - names = [] - repos = utils.get_repos() - groups = utils.get_groups() - for i, word in enumerate(args.man): - if word in repos or word in groups: - names.append(word) - else: - break - args.cmd = ['git'] + args.man[i:] - args.repo = names + repos, cmds = utils.parse_repos_and_rest(args.man) + if not cmds: + print('Missing commands') + sys.exit(2) + + args.cmd = ['git'] + cmds + args._parsed_repos = repos args.shell = False f_git_cmd(args) diff --git a/gita/utils.py b/gita/utils.py index e55c008..2431fde 100644 --- a/gita/utils.py +++ b/gita/utils.py @@ -479,3 +479,38 @@ def get_cmds_from_files() -> Dict[str, Dict[str, str]]: # custom commands shadow default ones cmds.update(custom_cmds) return cmds + + +def parse_repos_and_rest(input: List[str] + ) -> Tuple[Dict[str, Dict[str, str]], List[str]]: + """ + Parse gita input arguments + + @return: repos and the rest (e.g., gita shell and super commands) + """ + i = None + names = [] + repos = get_repos() + groups = get_groups() + ctx = get_context() + for i, word in enumerate(input): + if word in repos or word in groups: + names.append(word) + else: + break + else: # all input is repos and groups, shift the index once more + if i is not None: + i += 1 + if not names and ctx: + names = [ctx.stem] + if names: + chosen = {} + for k in names: + if k in repos: + chosen[k] = repos[k] + if k in groups: + for r in groups[k]['repos']: + chosen[r] = repos[r] + # if not set here, all repos are chosen + repos = chosen + return repos, input[i:]
nosarthur/gita
bdb046acefea0e9d32defb132deb9669532608be
diff --git a/tests/test_utils.py b/tests/test_utils.py index 3ff0cb1..65096e9 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -10,6 +10,19 @@ from conftest import ( ) [email protected]('input, expected', [ + ([], ({'repo1': {'path': '/a/bcd/repo1', 'type': '', 'flags': []}, 'xxx': {'path': '/a/b/c/repo3', 'type': '', 'flags': []}, 'repo2': {'path': '/e/fgh/repo2', 'type': '', 'flags': []}}, [])), + (['st'], ({'repo1': {'path': '/a/bcd/repo1', 'type': '', 'flags': []}, 'xxx': {'path': '/a/b/c/repo3', 'type': '', 'flags': []}, 'repo2': {'path': '/e/fgh/repo2', 'type': '', 'flags': []}}, ['st'])), + (['repo1', 'st'], ({'repo1': {'flags': [], 'path': '/a/bcd/repo1', 'type': ''}}, ['st'])), + (['repo1'], ({'repo1': {'flags': [], 'path': '/a/bcd/repo1', 'type': ''}}, [])), + ]) +@patch('gita.utils.is_git', return_value=True) +@patch('gita.common.get_config_fname', return_value=PATH_FNAME) +def test_parse_repos_and_rest(mock_path_fname, _, input, expected): + got = utils.parse_repos_and_rest(input) + assert got == expected + + @pytest.mark.parametrize('repo_path, paths, expected', [ ('/a/b/c/repo', ['/a/b'], (('b', 'c'), '/a')), ])
`gita shell` without argument fails with UnboundLocalError: local variable 'i' referenced before assignment By now I have figured `gita shell` needs to be followed by arguments, but the error message is not very user-friendly. Typing `gita shell` by itself yields the following output: ``` gita shell Traceback (most recent call last): File "/usr/local/bin/gita", line 8, in <module> sys.exit(main()) File "xxxxxx/gita/gita/__main__.py", line 680, in main args.func(args) File "xxxxxx/gita/gita/__main__.py", line 378, in f_shell cmds = ' '.join(args.man[i:]) # join the shell command into a single string UnboundLocalError: local variable 'i' referenced before assignment ```
0.0
[ "tests/test_utils.py::test_parse_repos_and_rest[input0-expected0]", "tests/test_utils.py::test_parse_repos_and_rest[input1-expected1]", "tests/test_utils.py::test_parse_repos_and_rest[input2-expected2]", "tests/test_utils.py::test_parse_repos_and_rest[input3-expected3]" ]
[ "tests/test_utils.py::test_generate_dir_hash[/a/b/c/repo-paths0-expected0]", "tests/test_utils.py::test_auto_group[repos0-paths0-expected0]", "tests/test_utils.py::test_auto_group[repos1-paths1-expected1]", "tests/test_utils.py::test_auto_group[repos2-paths2-expected2]", "tests/test_utils.py::test_describe[test_input0-True-abc", "tests/test_utils.py::test_describe[test_input1-True-abc", "tests/test_utils.py::test_describe[test_input2-False-repo", "tests/test_utils.py::test_get_repos[/root/data/temp_dir/tmpc2lgdt63/nosarthur__gita__0.0/tests/mock_path_file-expected0]", "tests/test_utils.py::test_get_repos[/root/data/temp_dir/tmpc2lgdt63/nosarthur__gita__0.0/tests/empty_path_file-expected1]", "tests/test_utils.py::test_get_repos[/root/data/temp_dir/tmpc2lgdt63/nosarthur__gita__0.0/tests/clash_path_file-expected2]", "tests/test_utils.py::test_get_context", "tests/test_utils.py::test_get_groups[/root/data/temp_dir/tmpc2lgdt63/nosarthur__gita__0.0/tests/mock_group_file-expected0]", "tests/test_utils.py::test_custom_push_cmd", "tests/test_utils.py::test_add_repos[path_input0-/home/some/repo,some/repo,,\\r\\n]", "tests/test_utils.py::test_add_repos[path_input1-expected1]", "tests/test_utils.py::test_add_repos[path_input2-/home/some/repo1,repo1,,\\r\\n]", "tests/test_utils.py::test_rename_repo", "tests/test_utils.py::test_async_output", "tests/test_utils.py::test_is_git" ]
2021-09-13 11:36:35+00:00
4,238
nosarthur__gita-241
diff --git a/gita/__init__.py b/gita/__init__.py index eeb79a3..33c0f41 100644 --- a/gita/__init__.py +++ b/gita/__init__.py @@ -1,3 +1,3 @@ import pkg_resources -__version__ = pkg_resources.get_distribution('gita').version +__version__ = pkg_resources.get_distribution("gita").version diff --git a/gita/common.py b/gita/common.py index 994e5e0..64116af 100644 --- a/gita/common.py +++ b/gita/common.py @@ -2,8 +2,11 @@ import os def get_config_dir() -> str: - root = os.environ.get('GITA_PROJECT_HOME') or os.environ.get('XDG_CONFIG_HOME') or os.path.join( - os.path.expanduser('~'), '.config') + root = ( + os.environ.get("GITA_PROJECT_HOME") + or os.environ.get("XDG_CONFIG_HOME") + or os.path.join(os.path.expanduser("~"), ".config") + ) return os.path.join(root, "gita") diff --git a/gita/info.py b/gita/info.py index 57bb1a8..a6d5bca 100644 --- a/gita/info.py +++ b/gita/info.py @@ -3,7 +3,7 @@ import csv import subprocess from enum import Enum from pathlib import Path -from functools import lru_cache +from functools import lru_cache, partial from typing import Tuple, List, Callable, Dict from . import common @@ -13,24 +13,25 @@ class Color(Enum): """ Terminal color """ - black = '\x1b[30m' - red = '\x1b[31m' # local diverges from remote - green = '\x1b[32m' # local == remote - yellow = '\x1b[33m' # local is behind - blue = '\x1b[34m' - purple = '\x1b[35m' # local is ahead - cyan = '\x1b[36m' - white = '\x1b[37m' # no remote branch - end = '\x1b[0m' - b_black = '\x1b[30;1m' - b_red = '\x1b[31;1m' - b_green = '\x1b[32;1m' - b_yellow = '\x1b[33;1m' - b_blue = '\x1b[34;1m' - b_purple = '\x1b[35;1m' - b_cyan = '\x1b[36;1m' - b_white = '\x1b[37;1m' - underline = '\x1B[4m' + + black = "\x1b[30m" + red = "\x1b[31m" # local diverges from remote + green = "\x1b[32m" # local == remote + yellow = "\x1b[33m" # local is behind + blue = "\x1b[34m" + purple = "\x1b[35m" # local is ahead + cyan = "\x1b[36m" + white = "\x1b[37m" # no remote branch + end = "\x1b[0m" + b_black = "\x1b[30;1m" + b_red = "\x1b[31;1m" + b_green = "\x1b[32;1m" + b_yellow = "\x1b[33;1m" + b_blue = "\x1b[34;1m" + b_purple = "\x1b[35;1m" + b_cyan = "\x1b[36;1m" + b_white = "\x1b[37;1m" + underline = "\x1B[4m" # Make f"{Color.foo}" expand to Color.foo.value . # @@ -40,26 +41,24 @@ class Color(Enum): default_colors = { - 'no-remote': Color.white.name, - 'in-sync': Color.green.name, - 'diverged': Color.red.name, - 'local-ahead': Color.purple.name, - 'remote-ahead': Color.yellow.name, - } + "no-remote": Color.white.name, + "in-sync": Color.green.name, + "diverged": Color.red.name, + "local-ahead": Color.purple.name, + "remote-ahead": Color.yellow.name, +} def show_colors(): # pragma: no cover - """ - - """ + """ """ for i, c in enumerate(Color, start=1): if c != Color.end and c != Color.underline: - print(f'{c.value}{c.name:<8} ', end='') + print(f"{c.value}{c.name:<8} ", end="") if i % 9 == 0: print() - print(f'{Color.end}') + print(f"{Color.end}") for situation, c in sorted(get_color_encoding().items()): - print(f'{situation:<12}: {Color[c].value}{c:<8}{Color.end} ') + print(f"{situation:<12}: {Color[c].value}{c:<8}{Color.end} ") @lru_cache() @@ -69,9 +68,9 @@ def get_color_encoding() -> Dict[str, str]: In the format of {situation: color name} """ # custom settings - csv_config = Path(common.get_config_fname('color.csv')) + csv_config = Path(common.get_config_fname("color.csv")) if csv_config.is_file(): - with open(csv_config, 'r') as f: + with open(csv_config, "r") as f: reader = csv.DictReader(f) colors = next(reader) else: @@ -79,7 +78,7 @@ def get_color_encoding() -> Dict[str, str]: return colors -def get_info_funcs() -> List[Callable[[str], str]]: +def get_info_funcs(no_colors=False) -> List[Callable[[str], str]]: """ Return the functions to generate `gita ll` information. All these functions take the repo path as input and return the corresponding information as str. @@ -88,11 +87,11 @@ def get_info_funcs() -> List[Callable[[str], str]]: to_display = get_info_items() # This re-definition is to make unit test mocking to work all_info_items = { - 'branch': get_repo_status, - 'commit_msg': get_commit_msg, - 'commit_time': get_commit_time, - 'path': get_path, - } + "branch": partial(get_repo_status, no_colors=no_colors), + "commit_msg": get_commit_msg, + "commit_time": get_commit_time, + "path": get_path, + } return [all_info_items[k] for k in to_display] @@ -101,15 +100,15 @@ def get_info_items() -> List[str]: Return the information items to be displayed in the `gita ll` command. """ # custom settings - csv_config = Path(common.get_config_fname('info.csv')) + csv_config = Path(common.get_config_fname("info.csv")) if csv_config.is_file(): - with open(csv_config, 'r') as f: + with open(csv_config, "r") as f: reader = csv.reader(f) display_items = next(reader) display_items = [x for x in display_items if x in ALL_INFO_ITEMS] else: # default settings - display_items = ['branch', 'commit_msg', 'commit_time'] + display_items = ["branch", "commit_msg", "commit_time"] return display_items @@ -119,43 +118,48 @@ def get_path(prop: Dict[str, str]) -> str: # TODO: do we need to add the flags here too? def get_head(path: str) -> str: - result = subprocess.run('git symbolic-ref -q --short HEAD || git describe --tags --exact-match', - shell=True, - stdout=subprocess.PIPE, - stderr=subprocess.DEVNULL, - universal_newlines=True, - cwd=path) + result = subprocess.run( + "git symbolic-ref -q --short HEAD || git describe --tags --exact-match", + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + universal_newlines=True, + cwd=path, + ) return result.stdout.strip() -def run_quiet_diff(flags: List[str], args: List[str]) -> int: +def run_quiet_diff(flags: List[str], args: List[str], path) -> int: """ Return the return code of git diff `args` in quiet mode """ result = subprocess.run( - ['git'] + flags + ['diff', '--quiet'] + args, + ["git"] + flags + ["diff", "--quiet"] + args, stderr=subprocess.DEVNULL, + cwd=path, ) return result.returncode -def get_common_commit() -> str: +def get_common_commit(path) -> str: """ Return the hash of the common commit of the local and upstream branches. """ - result = subprocess.run('git merge-base @{0} @{u}'.split(), - stdout=subprocess.PIPE, - universal_newlines=True) + result = subprocess.run( + "git merge-base @{0} @{u}".split(), + stdout=subprocess.PIPE, + universal_newlines=True, + cwd=path, + ) return result.stdout.strip() -def has_untracked(flags: List[str]) -> bool: +def has_untracked(flags: List[str], path) -> bool: """ Return True if untracked file/folder exists """ - cmd = ['git'] + flags + 'ls-files -zo --exclude-standard'.split() - result = subprocess.run(cmd, - stdout=subprocess.PIPE) + cmd = ["git"] + flags + "ls-files -zo --exclude-standard".split() + result = subprocess.run(cmd, stdout=subprocess.PIPE, cwd=path) return bool(result.stdout) @@ -164,12 +168,14 @@ def get_commit_msg(prop: Dict[str, str]) -> str: Return the last commit message. """ # `git show-branch --no-name HEAD` is faster than `git show -s --format=%s` - cmd = ['git'] + prop['flags'] + 'show-branch --no-name HEAD'.split() - result = subprocess.run(cmd, - stdout=subprocess.PIPE, - stderr=subprocess.DEVNULL, - universal_newlines=True, - cwd=prop['path']) + cmd = ["git"] + prop["flags"] + "show-branch --no-name HEAD".split() + result = subprocess.run( + cmd, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + universal_newlines=True, + cwd=prop["path"], + ) return result.stdout.strip() @@ -177,17 +183,19 @@ def get_commit_time(prop: Dict[str, str]) -> str: """ Return the last commit time in parenthesis. """ - cmd = ['git'] + prop['flags'] + 'log -1 --format=%cd --date=relative'.split() - result = subprocess.run(cmd, - stdout=subprocess.PIPE, - stderr=subprocess.DEVNULL, - universal_newlines=True, - cwd=prop['path']) + cmd = ["git"] + prop["flags"] + "log -1 --format=%cd --date=relative".split() + result = subprocess.run( + cmd, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + universal_newlines=True, + cwd=prop["path"], + ) return f"({result.stdout.strip()})" def get_repo_status(prop: Dict[str, str], no_colors=False) -> str: - head = get_head(prop['path']) + head = get_head(prop["path"]) dirty, staged, untracked, color = _get_repo_status(prop, no_colors) if color: return f'{color}{head+" "+dirty+staged+untracked:<10}{Color.end}' @@ -198,39 +206,37 @@ def _get_repo_status(prop: Dict[str, str], no_colors: bool) -> Tuple[str]: """ Return the status of one repo """ - path = prop['path'] - flags = prop['flags'] - os.chdir(path) - dirty = '*' if run_quiet_diff(flags, []) else '' - staged = '+' if run_quiet_diff(flags, ['--cached']) else '' - untracked = '_' if has_untracked(flags) else '' + path = prop["path"] + flags = prop["flags"] + dirty = "*" if run_quiet_diff(flags, [], path) else "" + staged = "+" if run_quiet_diff(flags, ["--cached"], path) else "" + untracked = "_" if has_untracked(flags, path) else "" if no_colors: - return dirty, staged, untracked, '' + return dirty, staged, untracked, "" - colors = {situ: Color[name].value - for situ, name in get_color_encoding().items()} - diff_returncode = run_quiet_diff(flags, ['@{u}', '@{0}']) + colors = {situ: Color[name].value for situ, name in get_color_encoding().items()} + diff_returncode = run_quiet_diff(flags, ["@{u}", "@{0}"], path) has_no_remote = diff_returncode == 128 has_no_diff = diff_returncode == 0 if has_no_remote: - color = colors['no-remote'] + color = colors["no-remote"] elif has_no_diff: - color = colors['in-sync'] + color = colors["in-sync"] else: - common_commit = get_common_commit() - outdated = run_quiet_diff(flags, ['@{u}', common_commit]) + common_commit = get_common_commit(path) + outdated = run_quiet_diff(flags, ["@{u}", common_commit], path) if outdated: - diverged = run_quiet_diff(flags, ['@{0}', common_commit]) - color = colors['diverged'] if diverged else colors['remote-ahead'] + diverged = run_quiet_diff(flags, ["@{0}", common_commit], path) + color = colors["diverged"] if diverged else colors["remote-ahead"] else: # local is ahead of remote - color = colors['local-ahead'] + color = colors["local-ahead"] return dirty, staged, untracked, color ALL_INFO_ITEMS = { - 'branch': get_repo_status, - 'commit_msg': get_commit_msg, - 'commit_time': get_commit_time, - 'path': get_path, - } + "branch": get_repo_status, + "commit_msg": get_commit_msg, + "commit_time": get_commit_time, + "path": get_path, +} diff --git a/gita/utils.py b/gita/utils.py index 76aebce..6746d7f 100644 --- a/gita/utils.py +++ b/gita/utils.py @@ -5,7 +5,7 @@ import csv import asyncio import platform import subprocess -from functools import lru_cache, partial +from functools import lru_cache from pathlib import Path from typing import List, Dict, Coroutine, Union, Iterator, Tuple from collections import Counter, defaultdict @@ -431,18 +431,14 @@ def describe(repos: Dict[str, Dict[str, str]], no_colors: bool = False) -> str: """ if repos: name_width = len(max(repos, key=len)) + 1 - funcs = info.get_info_funcs() - - get_repo_status = info.get_repo_status - if get_repo_status in funcs and no_colors: - idx = funcs.index(get_repo_status) - funcs[idx] = partial(get_repo_status, no_colors=True) + funcs = info.get_info_funcs(no_colors=no_colors) num_threads = min(multiprocessing.cpu_count(), len(repos)) with ThreadPoolExecutor(max_workers=num_threads) as executor: for line in executor.map( - lambda repo: f'{repo:<{name_width}}{" ".join(f(repos[repo]) for f in funcs)}', - sorted(repos)): + lambda name: f'{name:<{name_width}}{" ".join(f(repos[name]) for f in funcs)}', + sorted(repos), + ): yield line diff --git a/setup.py b/setup.py index 71b23ec..f7194d6 100644 --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ with open("README.md", encoding="utf-8") as f: setup( name="gita", packages=["gita"], - version="0.16.3", + version="0.16.3.1", license="MIT", description="Manage multiple git repos with sanity", long_description=long_description,
nosarthur/gita
619926e68c769133bdc5b5bae7c0aa65782a4c50
diff --git a/tests/conftest.py b/tests/conftest.py index b3e59ed..5236a90 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -8,10 +8,11 @@ def fullpath(fname: str): return str(TEST_DIR / fname) -PATH_FNAME = fullpath('mock_path_file') -PATH_FNAME_EMPTY = fullpath('empty_path_file') -PATH_FNAME_CLASH = fullpath('clash_path_file') -GROUP_FNAME = fullpath('mock_group_file') +PATH_FNAME = fullpath("mock_path_file") +PATH_FNAME_EMPTY = fullpath("empty_path_file") +PATH_FNAME_CLASH = fullpath("clash_path_file") +GROUP_FNAME = fullpath("mock_group_file") + def async_mock(): """ diff --git a/tests/test_info.py b/tests/test_info.py index c234d78..0af8a47 100644 --- a/tests/test_info.py +++ b/tests/test_info.py @@ -4,13 +4,14 @@ from unittest.mock import patch, MagicMock from gita import info -@patch('subprocess.run') +@patch("subprocess.run") def test_run_quiet_diff(mock_run): mock_return = MagicMock() mock_run.return_value = mock_return - got = info.run_quiet_diff(['--flags'], ['my', 'args']) + got = info.run_quiet_diff(["--flags"], ["my", "args"], "/a/b/c") mock_run.assert_called_once_with( - ['git', '--flags', 'diff', '--quiet', 'my', 'args'], + ["git", "--flags", "diff", "--quiet", "my", "args"], stderr=subprocess.DEVNULL, + cwd="/a/b/c", ) assert got == mock_return.returncode diff --git a/tests/test_main.py b/tests/test_main.py index 0f2eeb5..a892042 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -71,6 +71,7 @@ class TestLsLl: """ functional test """ + # avoid modifying the local configuration def side_effect(input, _=None): return tmp_path / f"{input}.txt" diff --git a/tests/test_utils.py b/tests/test_utils.py index 9679116..c39c626 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -135,7 +135,7 @@ def test_describe(test_input, diff_return, expected, monkeypatch): monkeypatch.setattr(info, "get_commit_msg", lambda *_: "msg") monkeypatch.setattr(info, "get_commit_time", lambda *_: "xx") monkeypatch.setattr(info, "has_untracked", lambda *_: True) - monkeypatch.setattr("os.chdir", lambda x: None) + monkeypatch.setattr(info, "get_common_commit", lambda x: "") info.get_color_encoding.cache_clear() # avoid side effect assert expected == next(utils.describe(*test_input))
problem displaying repo status properly Hello, I have an odd problem displaying repo status properly. I run "gita ll" several times after each other. each run status is reported randomly for different repositories, that is, the status color changes from green to white, to back again. This of course makes the functionality unusable, so I suspect something fundamentally wrong in my local setup, but I cant figure out what. Any debugging help would be appreciated. Im sorry for the vagueness in the report, but its a really odd problem. Some more info: Python 3.10.11 The repos I try to work with are from: gitlab.com/arbetsformedlingen, a group of about 400 repos. They where initially cloned with Ghorg. I run gita in an emacs shell buffer, but the problem is the same in a terminal.
0.0
[ "tests/test_info.py::test_run_quiet_diff", "tests/test_utils.py::test_describe[test_input0-True-abc", "tests/test_utils.py::test_describe[test_input1-True-abc", "tests/test_utils.py::test_describe[test_input2-False-repo" ]
[ "tests/test_main.py::test_group_name", "tests/test_main.py::test_flags[/root/data/temp_dir/tmpzy_ovvx7/nosarthur__gita__0.0/tests/mock_path_file-]", "tests/test_main.py::test_flags[/root/data/temp_dir/tmpzy_ovvx7/nosarthur__gita__0.0/tests/clash_path_file-repo2:", "tests/test_main.py::TestLsLl::test_ls", "tests/test_main.py::TestLsLl::test_with_path_files[/root/data/temp_dir/tmpzy_ovvx7/nosarthur__gita__0.0/tests/mock_path_file-repo1", "tests/test_main.py::TestLsLl::test_with_path_files[/root/data/temp_dir/tmpzy_ovvx7/nosarthur__gita__0.0/tests/empty_path_file-]", "tests/test_main.py::TestLsLl::test_with_path_files[/root/data/temp_dir/tmpzy_ovvx7/nosarthur__gita__0.0/tests/clash_path_file-repo1", "tests/test_main.py::test_freeze[input0-]", "tests/test_main.py::test_clone_with_url", "tests/test_main.py::test_clone_with_config_file", "tests/test_main.py::test_clone_with_preserve_path", "tests/test_main.py::test_rm", "tests/test_main.py::test_not_add", "tests/test_main.py::test_fetch", "tests/test_main.py::test_async_fetch", "tests/test_main.py::test_superman[diff", "tests/test_main.py::test_superman[commit", "tests/test_main.py::test_shell[diff", "tests/test_main.py::test_shell[commit", "tests/test_main.py::TestContext::test_display_no_context", "tests/test_main.py::TestContext::test_display_context", "tests/test_main.py::TestContext::test_reset", "tests/test_main.py::TestContext::test_set_first_time", "tests/test_main.py::TestContext::test_set_second_time", "tests/test_main.py::TestGroupCmd::test_ls", "tests/test_main.py::TestGroupCmd::test_ll", "tests/test_main.py::TestGroupCmd::test_ll_with_group", "tests/test_main.py::TestGroupCmd::test_rename", "tests/test_main.py::TestGroupCmd::test_rename_error", "tests/test_main.py::TestGroupCmd::test_rm[xx-expected0]", "tests/test_main.py::TestGroupCmd::test_rm[xx", "tests/test_main.py::TestGroupCmd::test_add", "tests/test_main.py::TestGroupCmd::test_add_to_existing", "tests/test_main.py::TestGroupCmd::test_rm_repo", "tests/test_main.py::test_rename", "tests/test_main.py::TestInfo::test_ll", "tests/test_main.py::TestInfo::test_add", "tests/test_main.py::TestInfo::test_rm", "tests/test_main.py::test_set_color", "tests/test_main.py::test_clear[input0-]", "tests/test_utils.py::test_get_relative_path[/a/b/repo-/a/b-expected0]", "tests/test_utils.py::test_get_relative_path[/a/b/repo-/a-expected1]", "tests/test_utils.py::test_get_relative_path[/a/b/repo-/a/-expected2]", "tests/test_utils.py::test_get_relative_path[/a/b/repo--None]", "tests/test_utils.py::test_get_relative_path[/a/b/repo-/a/b/repo-expected4]", "tests/test_utils.py::test_parse_repos_and_rest[input0-expected0]", "tests/test_utils.py::test_parse_repos_and_rest[input1-expected1]", "tests/test_utils.py::test_parse_repos_and_rest[input2-expected2]", "tests/test_utils.py::test_parse_repos_and_rest[input3-expected3]", "tests/test_utils.py::test_generate_dir_hash[/a/b/c/repo-paths0-expected0]", "tests/test_utils.py::test_auto_group[repos0-paths0-expected0]", "tests/test_utils.py::test_auto_group[repos1-paths1-expected1]", "tests/test_utils.py::test_auto_group[repos2-paths2-expected2]", "tests/test_utils.py::test_get_repos[/root/data/temp_dir/tmpzy_ovvx7/nosarthur__gita__0.0/tests/mock_path_file-expected0]", "tests/test_utils.py::test_get_repos[/root/data/temp_dir/tmpzy_ovvx7/nosarthur__gita__0.0/tests/empty_path_file-expected1]", "tests/test_utils.py::test_get_repos[/root/data/temp_dir/tmpzy_ovvx7/nosarthur__gita__0.0/tests/clash_path_file-expected2]", "tests/test_utils.py::test_get_context", "tests/test_utils.py::test_get_groups[/root/data/temp_dir/tmpzy_ovvx7/nosarthur__gita__0.0/tests/mock_group_file-expected0]", "tests/test_utils.py::test_custom_push_cmd", "tests/test_utils.py::test_add_repos[path_input0-/home/some/repo,some/repo,,\\r\\n]", "tests/test_utils.py::test_add_repos[path_input1-expected1]", "tests/test_utils.py::test_add_repos[path_input2-/home/some/repo1,repo1,,\\r\\n]", "tests/test_utils.py::test_rename_repo", "tests/test_utils.py::test_async_output", "tests/test_utils.py::test_is_git" ]
2023-05-19 04:49:01+00:00
4,239
nosarthur__gita-256
diff --git a/README.md b/README.md index 1ba5d33..a1f7df3 100644 --- a/README.md +++ b/README.md @@ -337,16 +337,17 @@ Here `branch` includes both branch name and status. Another choice is to enable `spaceship_status`, which mimics the symbols used in [spaceship-prompt](https://spaceship-prompt.sh/sections/git/#Git-status-git_status). -For example, -symbol | meaning ----|--- - ∅| local has no remote -(no string) | local is the same as remote -⇕ | local has diverged from remote - ⇡| local is ahead of remote (good for push) - ⇣| local is behind remote (good for merge) +To customize these symbols, add a file in `$XDG_CONFIG_HOME/gita/symbols.csv`. +The default `spaceship_status` settings corresponds to + +```csv +dirty,staged,untracked,local_ahead,remote_ahead,diverged,in_sync,no_remote +!,+,?,↑,↓,⇕,,∅ +``` +Only the symbols to be overridden need to be defined. +You can search unicode symbols [here](https://www.compart.com/en/unicode/). ### customize git command flags diff --git a/gita/info.py b/gita/info.py index 85041ca..f781cd0 100644 --- a/gita/info.py +++ b/gita/info.py @@ -1,8 +1,8 @@ -import os import csv import subprocess from enum import Enum from pathlib import Path +from collections import namedtuple from functools import lru_cache, partial from typing import Tuple, List, Callable, Dict @@ -41,11 +41,11 @@ class Color(Enum): default_colors = { - "no-remote": Color.white.name, - "in-sync": Color.green.name, + "no_remote": Color.white.name, + "in_sync": Color.green.name, "diverged": Color.red.name, - "local-ahead": Color.purple.name, - "remote-ahead": Color.yellow.name, + "local_ahead": Color.purple.name, + "remote_ahead": Color.yellow.name, } @@ -196,11 +196,39 @@ def get_commit_time(prop: Dict[str, str]) -> str: return f"({result.stdout.strip()})" +# better solution exists for python3.7+ +# https://stackoverflow.com/questions/11351032/named-tuple-and-default-values-for-optional-keyword-arguments +Symbols = namedtuple( + "Symbols", + "dirty staged untracked local_ahead remote_ahead diverged in_sync no_remote", +) +Symbols.__new__.__defaults__ = ("",) * len(Symbols._fields) +default_symbols = Symbols("*", "+", "?") + + +@lru_cache() +def get_symbols(baseline: Symbols = default_symbols) -> Dict[str, str]: + """ + return status symbols with customization + """ + symbols = baseline._asdict() + symbols[""] = "" + custom = {} + csv_config = Path(common.get_config_fname("symbols.csv")) + if csv_config.is_file(): + with open(csv_config, "r") as f: + reader = csv.DictReader(f) + custom = next(reader) + symbols.update(custom) + return symbols + + def get_repo_status(prop: Dict[str, str], no_colors=False) -> str: head = get_head(prop["path"]) colors = {situ: Color[name].value for situ, name in get_color_encoding().items()} dirty, staged, untracked, situ = _get_repo_status(prop, skip_situ=no_colors) - info = f"{head:<10} [{dirty+staged+untracked}]" + symbols = get_symbols(default_symbols) + info = f"{head:<10} [{symbols[dirty]+symbols[staged]+symbols[untracked]}]" if no_colors: return f"{info:<17}" @@ -208,19 +236,14 @@ def get_repo_status(prop: Dict[str, str], no_colors=False) -> str: return f"{color}{info:<17}{Color.end}" -spaceship = { - "local-ahead": "⇡", - "remote-ahead": "⇣", - "diverged": "⇕", - "in-sync": "", - "no-remote": "∅", -} +spaceship = Symbols("!", "+", "?", "↑", "↓", "⇕", "", "∅") def get_spaceship_status(prop: Dict[str, str]) -> str: head = get_head(prop["path"]) dirty, staged, untracked, situ = _get_repo_status(prop) - info = f"{head:<10} [{dirty+staged+untracked+spaceship[situ]}]" + symbols = get_symbols(spaceship) + info = f"{head:<10} [{symbols[dirty]+symbols[staged]+symbols[untracked]+symbols[situ]}]" return f"{info:<18}" @@ -236,26 +259,26 @@ def _get_repo_status( """ path = prop["path"] flags = prop["flags"] - dirty = "*" if run_quiet_diff(flags, [], path) else "" - staged = "+" if run_quiet_diff(flags, ["--cached"], path) else "" - untracked = "?" if has_untracked(flags, path) else "" + dirty = "dirty" if run_quiet_diff(flags, [], path) else "" + staged = "staged" if run_quiet_diff(flags, ["--cached"], path) else "" + untracked = "untracked" if has_untracked(flags, path) else "" if skip_situ: return dirty, staged, untracked, "" diff_returncode = run_quiet_diff(flags, ["@{u}", "@{0}"], path) if diff_returncode == 128: - situ = "no-remote" + situ = "no_remote" elif diff_returncode == 0: - situ = "in-sync" + situ = "in_sync" else: common_commit = get_common_commit(path) outdated = run_quiet_diff(flags, ["@{u}", common_commit], path) if outdated: diverged = run_quiet_diff(flags, ["@{0}", common_commit], path) - situ = "diverged" if diverged else "remote-ahead" + situ = "diverged" if diverged else "remote_ahead" else: # local is ahead of remote - situ = "local-ahead" + situ = "local_ahead" return dirty, staged, untracked, situ
nosarthur/gita
28ffaf6095c97c31594513d9ae467e879f00a0a7
diff --git a/tests/test_main.py b/tests/test_main.py index 7080428..7c82501 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -130,18 +130,21 @@ class TestLsLl: [ ( PATH_FNAME, - "repo1 \x1b[31mmaster [dsu] \x1b[0m msg \nrepo2 \x1b[31mmaster [dsu] \x1b[0m msg \nxxx \x1b[31mmaster [dsu] \x1b[0m msg \n", + "repo1 \x1b[31mmaster [*+?] \x1b[0m msg \nrepo2 \x1b[31mmaster [*+?] \x1b[0m msg \nxxx \x1b[31mmaster [*+?] \x1b[0m msg \n", ), (PATH_FNAME_EMPTY, ""), ( PATH_FNAME_CLASH, - "repo1 \x1b[31mmaster [dsu] \x1b[0m msg \nrepo2 \x1b[31mmaster [dsu] \x1b[0m msg \n", + "repo1 \x1b[31mmaster [*+?] \x1b[0m msg \nrepo2 \x1b[31mmaster [*+?] \x1b[0m msg \n", ), ], ) @patch("gita.utils.is_git", return_value=True) @patch("gita.info.get_head", return_value="master") - @patch("gita.info._get_repo_status", return_value=("d", "s", "u", "diverged")) + @patch( + "gita.info._get_repo_status", + return_value=("dirty", "staged", "untracked", "diverged"), + ) @patch("gita.info.get_commit_msg", return_value="msg") @patch("gita.info.get_commit_time", return_value="") @patch("gita.common.get_config_fname") @@ -567,7 +570,7 @@ def test_set_color(mock_get_fname, tmpdir): args = argparse.Namespace() args.color_cmd = "set" args.color = "b_white" - args.situation = "no-remote" + args.situation = "no_remote" with tmpdir.as_cwd(): csv_config = Path.cwd() / "colors.csv" mock_get_fname.return_value = csv_config @@ -577,11 +580,11 @@ def test_set_color(mock_get_fname, tmpdir): items = info.get_color_encoding() info.get_color_encoding.cache_clear() # avoid side effect assert items == { - "no-remote": "b_white", - "in-sync": "green", + "no_remote": "b_white", + "in_sync": "green", "diverged": "red", - "local-ahead": "purple", - "remote-ahead": "yellow", + "local_ahead": "purple", + "remote_ahead": "yellow", }
Customising edit status symbols It would be great to be able to configure the edit status symbols `*_-` to the characters and colors that the user prefers.
0.0
[ "tests/test_main.py::TestLsLl::test_with_path_files[/root/data/temp_dir/tmp5g4uud7e/nosarthur__gita__0.0/tests/mock_path_file-repo1", "tests/test_main.py::TestLsLl::test_with_path_files[/root/data/temp_dir/tmp5g4uud7e/nosarthur__gita__0.0/tests/clash_path_file-repo1", "tests/test_main.py::test_set_color" ]
[ "tests/test_main.py::test_group_name", "tests/test_main.py::test_flags[/root/data/temp_dir/tmp5g4uud7e/nosarthur__gita__0.0/tests/mock_path_file-]", "tests/test_main.py::test_flags[/root/data/temp_dir/tmp5g4uud7e/nosarthur__gita__0.0/tests/clash_path_file-repo2:", "tests/test_main.py::TestLsLl::test_ls", "tests/test_main.py::TestLsLl::test_with_path_files[/root/data/temp_dir/tmp5g4uud7e/nosarthur__gita__0.0/tests/empty_path_file-]", "tests/test_main.py::test_freeze[input0-]", "tests/test_main.py::test_clone_with_url", "tests/test_main.py::test_clone_with_config_file", "tests/test_main.py::test_clone_with_preserve_path", "tests/test_main.py::test_rm", "tests/test_main.py::test_not_add", "tests/test_main.py::test_fetch", "tests/test_main.py::test_async_fetch", "tests/test_main.py::test_superman[diff", "tests/test_main.py::test_superman[commit", "tests/test_main.py::test_shell[diff", "tests/test_main.py::test_shell[commit", "tests/test_main.py::TestContext::test_display_no_context", "tests/test_main.py::TestContext::test_display_context", "tests/test_main.py::TestContext::test_reset", "tests/test_main.py::TestContext::test_set_first_time", "tests/test_main.py::TestContext::test_set_second_time", "tests/test_main.py::TestGroupCmd::test_ls", "tests/test_main.py::TestGroupCmd::test_ll", "tests/test_main.py::TestGroupCmd::test_ll_with_group", "tests/test_main.py::TestGroupCmd::test_rename", "tests/test_main.py::TestGroupCmd::test_rename_error", "tests/test_main.py::TestGroupCmd::test_rm[xx-expected0]", "tests/test_main.py::TestGroupCmd::test_rm[xx", "tests/test_main.py::TestGroupCmd::test_add", "tests/test_main.py::TestGroupCmd::test_add_to_existing", "tests/test_main.py::TestGroupCmd::test_rm_repo", "tests/test_main.py::test_rename", "tests/test_main.py::TestInfo::test_ll", "tests/test_main.py::TestInfo::test_add", "tests/test_main.py::TestInfo::test_rm", "tests/test_main.py::test_clear[input0-]" ]
2023-07-16 16:29:02+00:00
4,240
nosarthur__gita-257
diff --git a/README.md b/README.md index a1f7df3..79c6009 100644 --- a/README.md +++ b/README.md @@ -334,19 +334,16 @@ branch,commit_msg,commit_time ``` Here `branch` includes both branch name and status. - -Another choice is to enable `spaceship_status`, which mimics -the symbols used in [spaceship-prompt](https://spaceship-prompt.sh/sections/git/#Git-status-git_status). +The status symbols are similar to the ones used in [spaceship-prompt](https://spaceship-prompt.sh/sections/git/#Git-status-git_status). To customize these symbols, add a file in `$XDG_CONFIG_HOME/gita/symbols.csv`. -The default `spaceship_status` settings corresponds to +The default settings corresponds to ```csv dirty,staged,untracked,local_ahead,remote_ahead,diverged,in_sync,no_remote -!,+,?,↑,↓,⇕,,∅ +*,+,?,↑,↓,⇕,,∅ ``` Only the symbols to be overridden need to be defined. - You can search unicode symbols [here](https://www.compart.com/en/unicode/). ### customize git command flags diff --git a/gita/info.py b/gita/info.py index f781cd0..10d8bea 100644 --- a/gita/info.py +++ b/gita/info.py @@ -89,7 +89,6 @@ def get_info_funcs(no_colors=False) -> List[Callable[[str], str]]: all_info_items = { "branch": partial(get_repo_status, no_colors=no_colors), "branch_name": get_repo_branch, - "spaceship_status": get_spaceship_status, "commit_msg": get_commit_msg, "commit_time": get_commit_time, "path": get_path, @@ -196,64 +195,52 @@ def get_commit_time(prop: Dict[str, str]) -> str: return f"({result.stdout.strip()})" -# better solution exists for python3.7+ -# https://stackoverflow.com/questions/11351032/named-tuple-and-default-values-for-optional-keyword-arguments -Symbols = namedtuple( - "Symbols", - "dirty staged untracked local_ahead remote_ahead diverged in_sync no_remote", -) -Symbols.__new__.__defaults__ = ("",) * len(Symbols._fields) -default_symbols = Symbols("*", "+", "?") +default_symbols = { + "dirty": "*", + "staged": "+", + "untracked": "?", + "local_ahead": "↑", + "remote_ahead": "↓", + "diverged": "⇕", + "in_sync": "", + "no_remote": "∅", + "": "", +} @lru_cache() -def get_symbols(baseline: Symbols = default_symbols) -> Dict[str, str]: +def get_symbols() -> Dict[str, str]: """ return status symbols with customization """ - symbols = baseline._asdict() - symbols[""] = "" custom = {} csv_config = Path(common.get_config_fname("symbols.csv")) if csv_config.is_file(): with open(csv_config, "r") as f: reader = csv.DictReader(f) custom = next(reader) - symbols.update(custom) - return symbols + default_symbols.update(custom) + return default_symbols def get_repo_status(prop: Dict[str, str], no_colors=False) -> str: - head = get_head(prop["path"]) - colors = {situ: Color[name].value for situ, name in get_color_encoding().items()} - dirty, staged, untracked, situ = _get_repo_status(prop, skip_situ=no_colors) - symbols = get_symbols(default_symbols) - info = f"{head:<10} [{symbols[dirty]+symbols[staged]+symbols[untracked]}]" + branch = get_head(prop["path"]) + dirty, staged, untracked, situ = _get_repo_status(prop) + symbols = get_symbols() + info = f"{branch:<10} [{symbols[dirty]+symbols[staged]+symbols[untracked]+symbols[situ]}]" if no_colors: - return f"{info:<17}" + return f"{info:<18}" + colors = {situ: Color[name].value for situ, name in get_color_encoding().items()} color = colors[situ] - return f"{color}{info:<17}{Color.end}" - - -spaceship = Symbols("!", "+", "?", "↑", "↓", "⇕", "", "∅") - - -def get_spaceship_status(prop: Dict[str, str]) -> str: - head = get_head(prop["path"]) - dirty, staged, untracked, situ = _get_repo_status(prop) - symbols = get_symbols(spaceship) - info = f"{head:<10} [{symbols[dirty]+symbols[staged]+symbols[untracked]+symbols[situ]}]" - return f"{info:<18}" + return f"{color}{info:<18}{Color.end}" def get_repo_branch(prop: Dict[str, str]) -> str: return get_head(prop["path"]) -def _get_repo_status( - prop: Dict[str, str], skip_situ=False -) -> Tuple[str, str, str, str]: +def _get_repo_status(prop: Dict[str, str]) -> Tuple[str, str, str, str]: """ Return the status of one repo """ @@ -263,9 +250,6 @@ def _get_repo_status( staged = "staged" if run_quiet_diff(flags, ["--cached"], path) else "" untracked = "untracked" if has_untracked(flags, path) else "" - if skip_situ: - return dirty, staged, untracked, "" - diff_returncode = run_quiet_diff(flags, ["@{u}", "@{0}"], path) if diff_returncode == 128: situ = "no_remote" @@ -285,7 +269,6 @@ def _get_repo_status( ALL_INFO_ITEMS = { "branch", "branch_name", - "spaceship_status", "commit_msg", "commit_time", "path", diff --git a/setup.py b/setup.py index d62cb5f..4950b49 100644 --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ with open("README.md", encoding="utf-8") as f: setup( name="gita", packages=["gita"], - version="0.16.5", + version="0.16.6", license="MIT", description="Manage multiple git repos with sanity", long_description=long_description,
nosarthur/gita
091cd91c80e59f684b1c1aa9c05043d52cc60238
diff --git a/tests/test_main.py b/tests/test_main.py index 7c82501..a877160 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -130,12 +130,12 @@ class TestLsLl: [ ( PATH_FNAME, - "repo1 \x1b[31mmaster [*+?] \x1b[0m msg \nrepo2 \x1b[31mmaster [*+?] \x1b[0m msg \nxxx \x1b[31mmaster [*+?] \x1b[0m msg \n", + "repo1 \x1b[31mmaster [*+?⇕] \x1b[0m msg \nrepo2 \x1b[31mmaster [*+?⇕] \x1b[0m msg \nxxx \x1b[31mmaster [*+?⇕] \x1b[0m msg \n", ), (PATH_FNAME_EMPTY, ""), ( PATH_FNAME_CLASH, - "repo1 \x1b[31mmaster [*+?] \x1b[0m msg \nrepo2 \x1b[31mmaster [*+?] \x1b[0m msg \n", + "repo1 \x1b[31mmaster [*+?⇕] \x1b[0m msg \nrepo2 \x1b[31mmaster [*+?⇕] \x1b[0m msg \n", ), ], ) @@ -535,8 +535,7 @@ class TestInfo: __main__.f_info(args) out, err = capfd.readouterr() assert ( - "In use: branch,commit_msg,commit_time\nUnused: branch_name,path,spaceship_status\n" - == out + "In use: branch,commit_msg,commit_time\nUnused: branch_name,path\n" == out ) assert err == "" diff --git a/tests/test_utils.py b/tests/test_utils.py index 1e4f125..2936f0e 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -115,17 +115,17 @@ def test_auto_group(repos, paths, expected): ( [{"abc": {"path": "/root/repo/", "type": "", "flags": []}}, False], True, - "abc \x1b[31mrepo [*+?] \x1b[0m msg xx", + "abc \x1b[31mrepo [*+?⇕] \x1b[0m msg xx", ), ( [{"abc": {"path": "/root/repo/", "type": "", "flags": []}}, True], True, - "abc repo [*+?] msg xx", + "abc repo [*+?⇕] msg xx", ), ( [{"repo": {"path": "/root/repo2/", "type": "", "flags": []}}, False], False, - "repo \x1b[32mrepo [?] \x1b[0m msg xx", + "repo \x1b[32mrepo [?] \x1b[0m msg xx", ), ], )
Revised symbols May I kindly suggest adopting the following symbols: symbol | meaning --- | --- `?` | Untracked changes `+` | Added changes `!` | Unstaged files `»` | Renamed files `✘` | Deleted files `$` | Stashed changes `=` | Unmerged changes `⇡` | Unpushed changes (ahead of remote branch) `⇣` | Unpulled changes (behind of remote branch) `⇕` | Diverged changes (diverged with remote branch) > _Based on https://spaceship-prompt.sh/sections/git/#Git-status-git_status_ I also believe it would be a great style to enclose them in `[` and `]` as well. For example: ``` $ gita ll blog master [!?] minor changes (2 weeks ago) dotfiles master [! ] update mac colmak ah json (31 minutes ago) gita master [ ] update CN readme and image (35 minutes ago) repol feature1 [ ] add readme (50 minutes ago) worklog refactor [ ] Update onboard-desmond.m (7 months ago) ```
0.0
[ "tests/test_main.py::TestLsLl::test_with_path_files[/root/data/temp_dir/tmpinttivrf/nosarthur__gita__0.0/tests/mock_path_file-repo1", "tests/test_main.py::TestLsLl::test_with_path_files[/root/data/temp_dir/tmpinttivrf/nosarthur__gita__0.0/tests/clash_path_file-repo1", "tests/test_main.py::TestInfo::test_ll", "tests/test_utils.py::test_describe[test_input0-True-abc", "tests/test_utils.py::test_describe[test_input1-True-abc", "tests/test_utils.py::test_describe[test_input2-False-repo" ]
[ "tests/test_main.py::test_group_name", "tests/test_main.py::test_flags[/root/data/temp_dir/tmpinttivrf/nosarthur__gita__0.0/tests/mock_path_file-]", "tests/test_main.py::test_flags[/root/data/temp_dir/tmpinttivrf/nosarthur__gita__0.0/tests/clash_path_file-repo2:", "tests/test_main.py::TestLsLl::test_ls", "tests/test_main.py::TestLsLl::test_with_path_files[/root/data/temp_dir/tmpinttivrf/nosarthur__gita__0.0/tests/empty_path_file-]", "tests/test_main.py::test_freeze[input0-]", "tests/test_main.py::test_clone_with_url", "tests/test_main.py::test_clone_with_config_file", "tests/test_main.py::test_clone_with_preserve_path", "tests/test_main.py::test_rm", "tests/test_main.py::test_not_add", "tests/test_main.py::test_fetch", "tests/test_main.py::test_async_fetch", "tests/test_main.py::test_superman[diff", "tests/test_main.py::test_superman[commit", "tests/test_main.py::test_shell[diff", "tests/test_main.py::test_shell[commit", "tests/test_main.py::TestContext::test_display_no_context", "tests/test_main.py::TestContext::test_display_context", "tests/test_main.py::TestContext::test_reset", "tests/test_main.py::TestContext::test_set_first_time", "tests/test_main.py::TestContext::test_set_second_time", "tests/test_main.py::TestGroupCmd::test_ls", "tests/test_main.py::TestGroupCmd::test_ll", "tests/test_main.py::TestGroupCmd::test_ll_with_group", "tests/test_main.py::TestGroupCmd::test_rename", "tests/test_main.py::TestGroupCmd::test_rename_error", "tests/test_main.py::TestGroupCmd::test_rm[xx-expected0]", "tests/test_main.py::TestGroupCmd::test_rm[xx", "tests/test_main.py::TestGroupCmd::test_add", "tests/test_main.py::TestGroupCmd::test_add_to_existing", "tests/test_main.py::TestGroupCmd::test_rm_repo", "tests/test_main.py::test_rename", "tests/test_main.py::TestInfo::test_add", "tests/test_main.py::TestInfo::test_rm", "tests/test_main.py::test_set_color", "tests/test_main.py::test_clear[input0-]", "tests/test_utils.py::test_get_relative_path[/a/b/repo-/a/b-expected0]", "tests/test_utils.py::test_get_relative_path[/a/b/repo-/a-expected1]", "tests/test_utils.py::test_get_relative_path[/a/b/repo-/a/-expected2]", "tests/test_utils.py::test_get_relative_path[/a/b/repo--None]", "tests/test_utils.py::test_get_relative_path[/a/b/repo-/a/b/repo-expected4]", "tests/test_utils.py::test_parse_repos_and_rest[input0-expected0]", "tests/test_utils.py::test_parse_repos_and_rest[input1-expected1]", "tests/test_utils.py::test_parse_repos_and_rest[input2-expected2]", "tests/test_utils.py::test_parse_repos_and_rest[input3-expected3]", "tests/test_utils.py::test_generate_dir_hash[/a/b/c/repo-paths0-expected0]", "tests/test_utils.py::test_auto_group[repos0-paths0-expected0]", "tests/test_utils.py::test_auto_group[repos1-paths1-expected1]", "tests/test_utils.py::test_auto_group[repos2-paths2-expected2]", "tests/test_utils.py::test_get_repos[/root/data/temp_dir/tmpinttivrf/nosarthur__gita__0.0/tests/mock_path_file-expected0]", "tests/test_utils.py::test_get_repos[/root/data/temp_dir/tmpinttivrf/nosarthur__gita__0.0/tests/empty_path_file-expected1]", "tests/test_utils.py::test_get_repos[/root/data/temp_dir/tmpinttivrf/nosarthur__gita__0.0/tests/clash_path_file-expected2]", "tests/test_utils.py::test_get_context", "tests/test_utils.py::test_get_groups[/root/data/temp_dir/tmpinttivrf/nosarthur__gita__0.0/tests/mock_group_file-expected0]", "tests/test_utils.py::test_custom_push_cmd", "tests/test_utils.py::test_add_repos[path_input0-/home/some/repo,some/repo,,\\r\\n]", "tests/test_utils.py::test_add_repos[path_input1-expected1]", "tests/test_utils.py::test_add_repos[path_input2-/home/some/repo1,repo1,,\\r\\n]", "tests/test_utils.py::test_rename_repo", "tests/test_utils.py::test_async_output", "tests/test_utils.py::test_is_git" ]
2023-07-17 16:39:37+00:00
4,241
nosarthur__gita-96
diff --git a/gita/__main__.py b/gita/__main__.py index fa88600..1e47e31 100644 --- a/gita/__main__.py +++ b/gita/__main__.py @@ -67,8 +67,19 @@ def f_ls(args: argparse.Namespace): def f_group(args: argparse.Namespace): groups = utils.get_groups() - if args.to_group: - gname = input('group name? ') + cmd = args.group_cmd or 'll' + if cmd == 'll': + for group, repos in groups.items(): + print(f"{group}: {' '.join(repos)}") + elif cmd == 'rm': + for name in args.to_ungroup: + del groups[name] + utils.write_to_groups_file(groups, 'w') + elif cmd == 'add': + while True: + gname = input('group name?') + if gname: + break if gname in groups: gname_repos = set(groups[gname]) gname_repos.update(args.to_group) @@ -76,24 +87,6 @@ def f_group(args: argparse.Namespace): utils.write_to_groups_file(groups, 'w') else: utils.write_to_groups_file({gname: sorted(args.to_group)}, 'a+') - else: - for group, repos in groups.items(): - print(f"{group}: {' '.join(repos)}") - - -def f_ungroup(args: argparse.Namespace): - groups = utils.get_groups() - to_ungroup = set(args.to_ungroup) - to_del = [] - for name, repos in groups.items(): - remaining = set(repos) - to_ungroup - if remaining: - groups[name] = list(sorted(remaining)) - else: - to_del.append(name) - for name in to_del: - del groups[name] - utils.write_to_groups_file(groups, 'w') def f_rm(args: argparse.Namespace): @@ -230,21 +223,21 @@ def main(argv=None): p_ls.set_defaults(func=f_ls) p_group = subparsers.add_parser( - 'group', help='group repos or display names of all groups if no repo is provided') - p_group.add_argument('to_group', - nargs='*', - choices=utils.get_choices(), - help="repo(s) to be grouped") + 'group', help='list, add, or remove repo group(s)') p_group.set_defaults(func=f_group) - - p_ungroup = subparsers.add_parser( - 'ungroup', help='remove group information for repos', - description="Remove group information on repos") - p_ungroup.add_argument('to_ungroup', - nargs='+', - choices=utils.get_repos(), - help="repo(s) to be ungrouped") - p_ungroup.set_defaults(func=f_ungroup) + group_cmds = p_group.add_subparsers(dest='group_cmd', + help='additional help with sub-command -h') + group_cmds.add_parser('ll', description='List all groups.') + group_cmds.add_parser('add', + description='Add repo(s) to a group.').add_argument('to_group', + nargs='+', + choices=utils.get_repos(), + help="repo(s) to be grouped") + group_cmds.add_parser('rm', + description='Remove group(s).').add_argument('to_ungroup', + nargs='+', + choices=utils.get_groups(), + help="group(s) to be deleted") # superman mode p_super = subparsers.add_parser( diff --git a/gita/utils.py b/gita/utils.py index d14484a..dd5cca3 100644 --- a/gita/utils.py +++ b/gita/utils.py @@ -114,8 +114,11 @@ def write_to_groups_file(groups: Dict[str, List[str]], mode: str): """ fname = get_config_fname('groups.yml') os.makedirs(os.path.dirname(fname), exist_ok=True) - with open(fname, mode) as f: - yaml.dump(groups, f, default_flow_style=None) + if not groups: # all groups are deleted + open(fname, 'w').close() + else: + with open(fname, mode) as f: + yaml.dump(groups, f, default_flow_style=None) def add_repos(repos: Dict[str, str], new_paths: List[str]): diff --git a/setup.py b/setup.py index 42d9502..32d6859 100644 --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ with open('README.md', encoding='utf-8') as f: setup( name='gita', packages=['gita'], - version='0.11.1', + version='0.11.2', license='MIT', description='Manage multiple git repos', long_description=long_description,
nosarthur/gita
bc33ff0907fed2a613f04c45dbedf035fd2bfef1
diff --git a/tests/test_main.py b/tests/test_main.py index ff28111..fcea12b 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -131,30 +131,56 @@ def test_superman(mock_run, _, input): mock_run.assert_called_once_with(expected_cmds, cwd='path7') [email protected]('input, expected', [ - ('a', {'xx': ['b'], 'yy': ['c', 'd']}), - ("c", {'xx': ['a', 'b'], 'yy': ['a', 'd']}), - ("a b", {'yy': ['c', 'd']}), -]) -@patch('gita.utils.get_repos', return_value={'a': '', 'b': '', 'c': '', 'd': ''}) -@patch('gita.utils.get_config_fname', return_value=GROUP_FNAME) -@patch('gita.utils.write_to_groups_file') -def test_ungroup(mock_write, _, __, input, expected): - utils.get_groups.cache_clear() - args = ['ungroup'] + shlex.split(input) - __main__.main(args) - mock_write.assert_called_once_with(expected, 'w') - +class TestGroupCmd: + + @patch('gita.utils.get_config_fname', return_value=GROUP_FNAME) + def testLl(self, _, capfd): + args = argparse.Namespace() + args.to_group = None + args.group_cmd = None + utils.get_groups.cache_clear() + __main__.f_group(args) + out, err = capfd.readouterr() + assert err == '' + assert 'xx: a b\nyy: a c d\n' == out -@patch('gita.utils.get_config_fname', return_value=GROUP_FNAME) -def test_group_display(_, capfd): - args = argparse.Namespace() - args.to_group = None - utils.get_groups.cache_clear() - __main__.f_group(args) - out, err = capfd.readouterr() - assert err == '' - assert 'xx: a b\nyy: a c d\n' == out + @pytest.mark.parametrize('input, expected', [ + ('xx', {'yy': ['a', 'c', 'd']}), + ("xx yy", {}), + ]) + @patch('gita.utils.get_repos', return_value={'a': '', 'b': '', 'c': '', 'd': ''}) + @patch('gita.utils.get_config_fname', return_value=GROUP_FNAME) + @patch('gita.utils.write_to_groups_file') + def testRm(self, mock_write, _, __, input, expected): + utils.get_groups.cache_clear() + args = ['group', 'rm'] + shlex.split(input) + __main__.main(args) + mock_write.assert_called_once_with(expected, 'w') + + @patch('gita.utils.get_repos', return_value={'a': '', 'b': '', 'c': '', 'd': ''}) + @patch('gita.utils.get_config_fname', return_value=GROUP_FNAME) + @patch('gita.utils.write_to_groups_file') + def testAdd(self, mock_write, _, __, monkeypatch): + args = argparse.Namespace() + args.to_group = ['a', 'c'] + args.group_cmd = 'add' + utils.get_groups.cache_clear() + monkeypatch.setattr('builtins.input', lambda _: 'zz') + __main__.f_group(args) + mock_write.assert_called_once_with({'zz': ['a', 'c']}, 'a+') + + @patch('gita.utils.get_repos', return_value={'a': '', 'b': '', 'c': '', 'd': ''}) + @patch('gita.utils.get_config_fname', return_value=GROUP_FNAME) + @patch('gita.utils.write_to_groups_file') + def testAddToExisting(self, mock_write, _, __, monkeypatch): + args = argparse.Namespace() + args.to_group = ['a', 'c'] + args.group_cmd = 'add' + utils.get_groups.cache_clear() + monkeypatch.setattr('builtins.input', lambda _: 'xx') + __main__.f_group(args) + mock_write.assert_called_once_with( + {'xx': ['a', 'b', 'c'], 'yy': ['a', 'c', 'd']}, 'w') @patch('gita.utils.is_git', return_value=True)
Add sub-commands for `gita group` IMO the command syntax is confusing - you have to pass a list of groups before you get any indication that a name will be requested. I spent 4-5min reading the help text thinking I was missing something, because there was no indication a name would be requested. At a minimum, update the help text to say "You will be prompted for the group name". However, ideally you woudl support a `--name` arg before the positional args, so the entire command could be scripted if needed
0.0
[ "tests/test_main.py::TestGroupCmd::testRm[xx-expected0]", "tests/test_main.py::TestGroupCmd::testRm[xx" ]
[ "tests/test_main.py::TestLsLl::testLs", "tests/test_main.py::TestLsLl::testWithPathFiles[/root/data/temp_dir/tmpzbct3zax/nosarthur__gita__0.0/tests/mock_path_file-repo1", "tests/test_main.py::TestLsLl::testWithPathFiles[/root/data/temp_dir/tmpzbct3zax/nosarthur__gita__0.0/tests/empty_path_file-]", "tests/test_main.py::TestLsLl::testWithPathFiles[/root/data/temp_dir/tmpzbct3zax/nosarthur__gita__0.0/tests/clash_path_file-repo1", "tests/test_main.py::test_rm", "tests/test_main.py::test_not_add", "tests/test_main.py::test_fetch", "tests/test_main.py::test_async_fetch", "tests/test_main.py::test_superman[diff", "tests/test_main.py::test_superman[commit", "tests/test_main.py::TestGroupCmd::testLl", "tests/test_main.py::TestGroupCmd::testAdd", "tests/test_main.py::TestGroupCmd::testAddToExisting", "tests/test_main.py::test_rename", "tests/test_main.py::test_info" ]
2020-09-13 05:19:53+00:00
4,242
nosarthur__gita-99
diff --git a/gita/__main__.py b/gita/__main__.py index 8d08742..9e4871c 100644 --- a/gita/__main__.py +++ b/gita/__main__.py @@ -72,6 +72,23 @@ def f_info(args: argparse.Namespace): yaml.dump(to_display, f, default_flow_style=None) +def f_clone(args: argparse.Namespace): + path = Path.cwd() + errors = utils.exec_async_tasks( + utils.run_async(repo_name, path, ['git', 'clone', url]) + for url, repo_name, _ in utils.parse_clone_config(args.fname)) + + +def f_freeze(_): + repos = utils.get_repos() + for name, path in repos.items(): + url = '' + cp = subprocess.run(['git', 'remote', '-v'], cwd=path, capture_output=True) + if cp.returncode == 0: + url = cp.stdout.decode('utf-8').split('\n')[0].split()[1] + print(f'{url},{name},{path}') + + def f_ll(args: argparse.Namespace): """ Display details of all repos @@ -238,15 +255,21 @@ def main(argv=None): help="remove the chosen repo(s)") p_rm.set_defaults(func=f_rm) + p_freeze = subparsers.add_parser('freeze', help='print all repo information') + p_freeze.set_defaults(func=f_freeze) + + p_clone = subparsers.add_parser('clone', help='clone repos from config file') + p_clone.add_argument('fname', + help='config file. Its content should be the output of `gita freeze`.') + p_clone.set_defaults(func=f_clone) + p_rename = subparsers.add_parser('rename', help='rename a repo') p_rename.add_argument( 'repo', nargs=1, choices=utils.get_repos(), help="rename the chosen repo") - p_rename.add_argument( - 'new_name', - help="new name") + p_rename.add_argument('new_name', help="new name") p_rename.set_defaults(func=f_rename) p_color = subparsers.add_parser('color', diff --git a/gita/utils.py b/gita/utils.py index d30a82e..06cdf07 100644 --- a/gita/utils.py +++ b/gita/utils.py @@ -4,7 +4,7 @@ import asyncio import platform from functools import lru_cache, partial from pathlib import Path -from typing import List, Dict, Coroutine, Union +from typing import List, Dict, Coroutine, Union, Iterator from . import info from . import common @@ -128,6 +128,8 @@ def write_to_groups_file(groups: Dict[str, List[str]], mode: str): def add_repos(repos: Dict[str, str], new_paths: List[str]): """ Write new repo paths to file + + @param repos: name -> path """ existing_paths = set(repos.values()) new_paths = set(os.path.abspath(p) for p in new_paths if is_git(p)) @@ -142,6 +144,15 @@ def add_repos(repos: Dict[str, str], new_paths: List[str]): print('No new repos found!') +def parse_clone_config(fname: str) -> Iterator[List[str]]: + """ + Return the url, name, and path of all repos in `fname`. + """ + with open(fname) as f: + for line in f: + yield line.strip().split(',') + + async def run_async(repo_name: str, path: str, cmds: List[str]) -> Union[None, str]: """ Run `cmds` asynchronously in `path` directory. Return the `path` if diff --git a/setup.py b/setup.py index 1c6ebd0..bfaaa01 100644 --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ with open('README.md', encoding='utf-8') as f: setup( name='gita', packages=['gita'], - version='0.12.2', + version='0.12.3', license='MIT', description='Manage multiple git repos with sanity', long_description=long_description,
nosarthur/gita
f0bc6e58b6b5e169041f2a5cc1eb7dff51a2263f
diff --git a/tests/test_main.py b/tests/test_main.py index e90050d..ecb13fe 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -95,6 +95,16 @@ class TestLsLl: assert out == expected +@patch('subprocess.run') +@patch('gita.utils.get_repos', return_value={'repo1': '/a/', 'repo2': '/b/'}) +def test_freeze(_, mock_run, capfd): + __main__.main(['freeze']) + assert mock_run.call_count == 2 + out, err = capfd.readouterr() + assert err == '' + assert out == ',repo1,/a/\n,repo2,/b/\n' + + @patch('os.path.isfile', return_value=True) @patch('gita.common.get_config_fname', return_value='some path') @patch('gita.utils.get_repos', return_value={'repo1': '/a/', 'repo2': '/b/'})
Command for mass-clone Hi, thank you so much for gita, it's a very nice tool. The one thing I'm missing is a "clone" command. I'd like to have a list of URLs in the config file of gita, together with the location it should clone them on the filesystem. This would allow me to do a 'gita clone' which then would clone all these repositories (if not already existing). Use-case: when re-installing a system, a 'gita clone' would be enough to be ready again. Regards, Daniel
0.0
[ "tests/test_main.py::test_freeze" ]
[ "tests/test_main.py::TestLsLl::testLs", "tests/test_main.py::TestLsLl::testWithPathFiles[/root/data/temp_dir/tmp5pz1sgtv/nosarthur__gita__0.0/tests/mock_path_file-repo1", "tests/test_main.py::TestLsLl::testWithPathFiles[/root/data/temp_dir/tmp5pz1sgtv/nosarthur__gita__0.0/tests/empty_path_file-]", "tests/test_main.py::TestLsLl::testWithPathFiles[/root/data/temp_dir/tmp5pz1sgtv/nosarthur__gita__0.0/tests/clash_path_file-repo1", "tests/test_main.py::test_rm", "tests/test_main.py::test_not_add", "tests/test_main.py::test_fetch", "tests/test_main.py::test_async_fetch", "tests/test_main.py::test_superman[diff", "tests/test_main.py::test_superman[commit", "tests/test_main.py::TestContext::testDisplayNoContext", "tests/test_main.py::TestContext::testDisplayContext", "tests/test_main.py::TestContext::testReset", "tests/test_main.py::TestContext::testSetFirstTime", "tests/test_main.py::TestContext::testSetSecondTime", "tests/test_main.py::TestGroupCmd::testLs", "tests/test_main.py::TestGroupCmd::testLl", "tests/test_main.py::TestGroupCmd::testRename", "tests/test_main.py::TestGroupCmd::testRenameError", "tests/test_main.py::TestGroupCmd::testRm[xx-expected0]", "tests/test_main.py::TestGroupCmd::testRm[xx", "tests/test_main.py::TestGroupCmd::testAdd", "tests/test_main.py::TestGroupCmd::testAddToExisting", "tests/test_main.py::test_rename", "tests/test_main.py::TestInfo::testLl", "tests/test_main.py::TestInfo::testAdd", "tests/test_main.py::TestInfo::testRm" ]
2020-09-27 01:35:25+00:00
4,243
nose-devs__nose2-370
diff --git a/nose2/plugins/layers.py b/nose2/plugins/layers.py index 43025ca..eda14dc 100644 --- a/nose2/plugins/layers.py +++ b/nose2/plugins/layers.py @@ -235,6 +235,9 @@ class LayerReporter(events.Plugin): if event.errorList and hasattr(event.test, 'layer'): # walk back layers to build full description self.describeLayers(event) + # we need to remove "\n" from description to keep a well indented report when tests have docstrings + # see https://github.com/nose-devs/nose2/issues/327 for more information + event.description = event.description.replace('\n', ' ') def describeLayers(self, event): desc = [event.description]
nose-devs/nose2
862b130652b9118eb8d5681923c04edb000245d3
diff --git a/nose2/tests/functional/support/scenario/layers/test_layers.py b/nose2/tests/functional/support/scenario/layers/test_layers.py index e800780..a35bb0f 100644 --- a/nose2/tests/functional/support/scenario/layers/test_layers.py +++ b/nose2/tests/functional/support/scenario/layers/test_layers.py @@ -180,6 +180,8 @@ class InnerD(unittest.TestCase): layer = LayerD def test(self): + """test with docstring + """ self.assertEqual( {'base': 'setup', 'layerD': 'setup'}, diff --git a/nose2/tests/functional/test_layers_plugin.py b/nose2/tests/functional/test_layers_plugin.py index 9666dba..c658bbe 100644 --- a/nose2/tests/functional/test_layers_plugin.py +++ b/nose2/tests/functional/test_layers_plugin.py @@ -56,7 +56,7 @@ class TestLayers(FunctionalTestCase): Base test \(test_layers.Outer\) ... ok LayerD - test \(test_layers.InnerD\) ... ok + test \(test_layers.InnerD\) test with docstring ... ok LayerA test \(test_layers.InnerA\) ... ok LayerB
Layer-reporter does not indent docstring Given a test def test_mymethond(self): """what this does hi there """ nose2 will output 'what this does' when the test is run, but the text will not be indented to reflect the layers used. Result of test run: TopLayer &nbsp;&nbsp;SecondLayer &nbsp;&nbsp;&nbsp;&nbsp;test_find_unassigned_signals (test_wrapper.SecondLayerTests) ... ok &nbsp;&nbsp;&nbsp;&nbsp;test_no_newer_definitions (test_wrapper.SecondLayerTests) Test that versions in API Wrapper are the latest ... ok &nbsp;&nbsp;&nbsp;&nbsp;test_only_add_customer_once (test_wrapper.SecondLayerTests) ... ok &nbsp;&nbsp;&nbsp;&nbsp;test_only_one_parquet_file_pr_customer (test_wrapper.SecondLayerTests) ... ok Expected: TopLayer &nbsp;&nbsp;SecondLayer &nbsp;&nbsp;&nbsp;&nbsp;test_find_unassigned_signals (test_wrapper.SecondLayerTests) ... ok &nbsp;&nbsp;&nbsp;&nbsp;test_no_newer_definitions (test_wrapper.SecondLayerTests) &nbsp;&nbsp;&nbsp;&nbsp;Test that versions in API Wrapper are the latest ... ok &nbsp;&nbsp;&nbsp;&nbsp;test_only_add_customer_once (test_wrapper.SecondLayerTests) ... ok &nbsp;&nbsp;&nbsp;&nbsp;test_only_one_parquet_file_pr_customer (test_wrapper.SecondLayerTests) ... ok or maybe even TopLayer &nbsp;&nbsp;SecondLayer &nbsp;&nbsp;&nbsp;&nbsp;test_find_unassigned_signals (test_wrapper.SecondLayerTests) ... ok &nbsp;&nbsp;&nbsp;&nbsp;Test that versions in API Wrapper are the latest (test_wrapper.SecondLayerTests) ... ok &nbsp;&nbsp;&nbsp;&nbsp;test_only_add_customer_once (test_wrapper.SecondLayerTests) ... ok &nbsp;&nbsp;&nbsp;&nbsp;test_only_one_parquet_file_pr_customer (test_wrapper.SecondLayerTests) ... ok
0.0
[ "nose2/tests/functional/test_layers_plugin.py::TestLayers::test_layer_reporter_output" ]
[ "nose2/tests/functional/support/scenario/layers/test_layers.py::NoLayer::test", "nose2/tests/functional/test_layers_plugin.py::TestLayers::test_layer_reporter_error_output", "nose2/tests/functional/test_layers_plugin.py::TestLayers::test_layers_and_attributes", "nose2/tests/functional/test_layers_plugin.py::TestLayers::test_layers_and_non_layers", "nose2/tests/functional/test_layers_plugin.py::TestLayers::test_methods_run_once_per_class", "nose2/tests/functional/test_layers_plugin.py::TestLayers::test_runs_layer_fixtures", "nose2/tests/functional/test_layers_plugin.py::TestLayers::test_scenario_fails_without_plugin", "nose2/tests/functional/test_layers_plugin.py::TestLayers::test_setup_fail", "nose2/tests/functional/test_layers_plugin.py::TestLayers::test_teardown_fail" ]
2017-11-13 16:40:20+00:00
4,244
nose-devs__nose2-409
diff --git a/.travis.yml b/.travis.yml index 29ef0a7..9137f5f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,9 +10,12 @@ python: - '3.4' - '3.5' - '3.6' -# include 3.7-dev, but put it in allow_failures (so we can easily view status, -# but not block on it) -- '3.7-dev' +matrix: + fast_finish: true + include: + - python: '3.7' + dist: xenial # required for Python 3.7 (travis-ci/travis-ci#9069) + sudo: required # required for Python 3.7 (travis-ci/travis-ci#9069) install: - travis_retry pip install tox-travis - travis_retry pip install coveralls @@ -30,10 +33,6 @@ deploy: tags: true distributions: sdist bdist_wheel repo: nose-devs/nose2 -matrix: - fast_finish: true - allow_failures: - - python: "3.7-dev" notifications: webhooks: urls: diff --git a/README.rst b/README.rst index d5c20d3..0ff4532 100644 --- a/README.rst +++ b/README.rst @@ -1,24 +1,16 @@ -.. image:: https://travis-ci.org/nose-devs/nose2.png?branch=master +.. image:: https://travis-ci.org/nose-devs/nose2.svg?branch=master :target: https://travis-ci.org/nose-devs/nose2 :alt: Build Status - -.. image:: https://coveralls.io/repos/nose-devs/nose2/badge.png?branch=master - :target: https://coveralls.io/r/nose-devs/nose2?branch=master + +.. image:: https://coveralls.io/repos/github/nose-devs/nose2/badge.svg?branch=master + :target: https://coveralls.io/github/nose-devs/nose2?branch=master :alt: Coverage Status - -.. image:: https://landscape.io/github/nose-devs/nose2/master/landscape.png - :target: https://landscape.io/github/nose-devs/nose2/master - :alt: Code Health - + .. image:: https://img.shields.io/pypi/v/nose2.svg :target: https://pypi.org/project/nose2/ :alt: Latest PyPI version -.. image:: https://www.versioneye.com/user/projects/52037a30632bac57a00257ea/badge.png - :target: https://www.versioneye.com/user/projects/52037a30632bac57a00257ea/ - :alt: Dependencies Status - -.. image:: https://badges.gitter.im/gitterHQ/gitter.png +.. image:: https://badges.gitter.im/gitterHQ/gitter.svg :target: https://gitter.im/nose2 :alt: Gitter Channel diff --git a/docs/changelog.rst b/docs/changelog.rst index a855226..0ca0c62 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -103,6 +103,37 @@ Added support for python 3.6. * Make the ``collect`` plugin work with layers * Fix coverage plugin to take import-time coverage into account +0.5.0 +----- + +* Added + * Add with_setup and with_teardown decorators to set the setup & teardown + on a function + * dundertests plugin to skip tests with `__test__ == False` + * Add `cartesian_params` decorator + * Add coverage plugin + * Add EggDiscoveryLoader for discovering tests within Eggs + * Support `params` with `such` + * `such` errors early if Layers plugin is not loaded + * Include logging output in junit XML + +* Fixed + * Such DSL ignores two `such.A` with the same description + * Record skipped tests as 'skipped' instead of 'skips' + * Result output failed on unicode characters + * Fix multiprocessing plugin on Windows + * Allow use of `nose2.main()` from within a test module + * Ensure plugins write to the event stream + * multiprocessing could lock master proc and fail to exit + * junit report path was sensitive to changes in cwd + * Test runs would crash if a TestCase `__init__` threw an exception + * Plugin failures no longer crash the whole test run + * Handle errors in test setup and teardown + * Fix reporting of xfail tests + * Log capture was waiting too long to render mutable objects to strings + * Layers plugin was not running testSetUp/testTearDown from higher `such` layers + + 0.4.7 ----- diff --git a/nose2/plugins/junitxml.py b/nose2/plugins/junitxml.py index ced1ce7..9f8f50a 100644 --- a/nose2/plugins/junitxml.py +++ b/nose2/plugins/junitxml.py @@ -160,6 +160,9 @@ class JUnitXmlReporter(events.Plugin): elif event.outcome == result.SKIP: self.skipped += 1 skipped = ET.SubElement(testcase, 'skipped') + if msg: + skipped.set('message', 'test skipped') + skipped.text = msg elif event.outcome == result.FAIL and event.expected: self.skipped += 1 skipped = ET.SubElement(testcase, 'skipped') @@ -245,15 +248,6 @@ class JUnitXmlReporter(events.Plugin): # xml utility functions # -# six doesn't include a unichr function - - -def _unichr(string): - if six.PY3: - return chr(string) - else: - return unichr(string) - # etree outputs XML 1.0 so the 1.1 Restricted characters are invalid. # and there are no characters that can be given as entities aside # form & < > ' " which ever have to be escaped (etree handles these fine) @@ -278,12 +272,12 @@ if sys.maxunicode > 0xFFFF: ILLEGAL_REGEX_STR = \ six.u('[') + \ - six.u('').join(["%s-%s" % (_unichr(l), _unichr(h)) + six.u('').join(["%s-%s" % (six.unichr(l), six.unichr(h)) for (l, h) in ILLEGAL_RANGES]) + \ six.u(']') RESTRICTED_REGEX_STR = \ six.u('[') + \ - six.u('').join(["%s-%s" % (_unichr(l), _unichr(h)) + six.u('').join(["%s-%s" % (six.unichr(l), six.unichr(h)) for (l, h) in RESTRICTED_RANGES]) + \ six.u(']') diff --git a/setup.py b/setup.py index b6084bb..495076b 100644 --- a/setup.py +++ b/setup.py @@ -25,6 +25,7 @@ CLASSIFIERS = [ 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Operating System :: OS Independent',
nose-devs/nose2
338e161109fd6ade9319be2738e35ad29756b944
diff --git a/nose2/tests/unit/test_junitxml.py b/nose2/tests/unit/test_junitxml.py index 9bfae3b..0748672 100644 --- a/nose2/tests/unit/test_junitxml.py +++ b/nose2/tests/unit/test_junitxml.py @@ -88,6 +88,9 @@ class TestJunitXmlPlugin(TestCase): def test_skip(self): self.skipTest('skip') + def test_skip_no_reason(self): + self.skipTest('') + def test_bad_xml(self): raise RuntimeError(TestJunitXmlPlugin.BAD_FOR_XML_U) @@ -172,6 +175,17 @@ class TestJunitXmlPlugin(TestCase): case = self.plugin.tree.find('testcase') skip = case.find('skipped') assert skip is not None + self.assertEqual(skip.get('message'), 'test skipped') + self.assertEqual(skip.text, 'skip') + + def test_skip_includes_skipped_no_reason(self): + test = self.case('test_skip_no_reason') + test(self.result) + case = self.plugin.tree.find('testcase') + skip = case.find('skipped') + assert skip is not None + self.assertIsNone(skip.get('message')) + self.assertIsNone(skip.text) def test_generator_test_name_correct(self): gen = generators.Generators(session=self.session) @@ -234,7 +248,7 @@ class TestJunitXmlPlugin(TestCase): for case in event.extraTests: case(self.result) xml = self.plugin.tree.findall('testcase') - self.assertEqual(len(xml), 12) + self.assertEqual(len(xml), 13) params = [x for x in xml if x.get('name').startswith('test_params')] self.assertEqual(len(params), 3) self.assertEqual(params[0].get('name'), 'test_params:1') @@ -259,7 +273,7 @@ class TestJunitXmlPlugin(TestCase): for case in event.extraTests: case(self.result) xml = self.plugin.tree.findall('testcase') - self.assertEqual(len(xml), 12) + self.assertEqual(len(xml), 13) params = [x for x in xml if x.get('name').startswith('test_params')] self.assertEqual(len(params), 3) self.assertEqual(params[0].get('name'), 'test_params:1 (1)')
changelog.rst does not describe differences in 0.5.0 PyPI has 0.5.0 but the changelog.rst only describes changes up to 0.4.7. What's new in 0.5.0?
0.0
[ "nose2/tests/unit/test_junitxml.py::TestJunitXmlPlugin::test_skip_includes_skipped" ]
[ "nose2/tests/unit/test_junitxml.py::TestJunitXmlPlugin::test_error_bad_xml", "nose2/tests/unit/test_junitxml.py::TestJunitXmlPlugin::test_error_bad_xml_b", "nose2/tests/unit/test_junitxml.py::TestJunitXmlPlugin::test_error_bad_xml_b_keep", "nose2/tests/unit/test_junitxml.py::TestJunitXmlPlugin::test_error_bad_xml_keep", "nose2/tests/unit/test_junitxml.py::TestJunitXmlPlugin::test_error_includes_traceback", "nose2/tests/unit/test_junitxml.py::TestJunitXmlPlugin::test_failure_includes_traceback", "nose2/tests/unit/test_junitxml.py::TestJunitXmlPlugin::test_function_classname_is_module", "nose2/tests/unit/test_junitxml.py::TestJunitXmlPlugin::test_generator_test_full_name_correct", "nose2/tests/unit/test_junitxml.py::TestJunitXmlPlugin::test_generator_test_name_correct", "nose2/tests/unit/test_junitxml.py::TestJunitXmlPlugin::test_params_test_full_name_correct", "nose2/tests/unit/test_junitxml.py::TestJunitXmlPlugin::test_params_test_name_correct", "nose2/tests/unit/test_junitxml.py::TestJunitXmlPlugin::test_skip_includes_skipped_no_reason", "nose2/tests/unit/test_junitxml.py::TestJunitXmlPlugin::test_success_added_to_xml", "nose2/tests/unit/test_junitxml.py::TestJunitXmlPlugin::test_writes_xml_file_at_end", "nose2/tests/unit/test_junitxml.py::TestJunitXmlPlugin::test_xml_contains_empty_system_out_without_logcapture", "nose2/tests/unit/test_junitxml.py::TestJunitXmlPlugin::test_xml_contains_log_message_in_system_out_with_logcapture", "nose2/tests/unit/test_junitxml.py::TestJunitXmlPlugin::test_xml_file_path_is_not_affected_by_chdir_in_test" ]
2018-08-15 04:33:05+00:00
4,245
nose-devs__nose2-410
diff --git a/nose2/main.py b/nose2/main.py index 67d5483..ea533c6 100644 --- a/nose2/main.py +++ b/nose2/main.py @@ -155,9 +155,17 @@ class PluggableTestProgram(unittest.TestProgram): dest='exclude_plugins', default=[], help="Do not load this plugin module") self.argparse.add_argument( - '--verbose', '-v', action='count', default=0, help="print test case names and statuses") - self.argparse.add_argument('--quiet', action='store_const', - dest='verbose', const=0) + '--verbosity', type=int, + help=("Set starting verbosity level (int). " + "Applies before -v and -q")) + self.argparse.add_argument( + '--verbose', '-v', action='count', default=0, + help=("Print test case names and statuses. " + "Use multiple '-v's for higher verbosity.")) + self.argparse.add_argument( + '--quiet', '-q', action='count', default=0, dest='quiet', + help=("Reduce verbosity. Multiple '-q's result in " + "lower verbosity.")) self.argparse.add_argument( '--log-level', default=logging.WARN, help='Set logging level for message logged to console.') @@ -172,13 +180,13 @@ class PluggableTestProgram(unittest.TestProgram): self.session.logLevel = util.parse_log_level(cfg_args.log_level) logging.basicConfig(level=self.session.logLevel) log.debug('logging initialized %s', cfg_args.log_level) - if cfg_args.verbose: - self.session.verbosity += cfg_args.verbose - self.session.startDir = cfg_args.start_dir if cfg_args.top_level_directory: self.session.topLevelDir = cfg_args.top_level_directory self.session.loadConfigFiles(*self.findConfigFiles(cfg_args)) - self.session.setStartDir() + # set verbosity from config + opts + self.session.setVerbosity( + cfg_args.verbosity, cfg_args.verbose, cfg_args.quiet) + self.session.setStartDir(args_start_dir=cfg_args.start_dir) self.session.prepareSysPath() if cfg_args.load_plugins: self.defaultPlugins.extend(cfg_args.plugins) diff --git a/nose2/session.py b/nose2/session.py index ee47c6d..e6c633c 100644 --- a/nose2/session.py +++ b/nose2/session.py @@ -72,7 +72,7 @@ class Session(object): """ configClass = config.Config - + def __init__(self): self.argparse = argparse.ArgumentParser(prog='nose2', add_help=False) self.pluginargs = self.argparse.add_argument_group( @@ -81,6 +81,8 @@ class Session(object): self.config = configparser.ConfigParser() self.hooks = events.PluginInterface() self.plugins = [] + # this will be reset later, whenever handleCfgArgs happens, but it + # starts at 1 so that it always has a non-negative integer value self.verbosity = 1 self.startDir = None self.topLevelDir = None @@ -183,9 +185,32 @@ class Session(object): log.debug("Register method %s for plugin %s", method, plugin) self.hooks.register(method, plugin) - def setStartDir(self): - if self.startDir is None: - self.startDir = self.unittest.as_str('start-dir', '.') + def setVerbosity(self, args_verbosity, args_verbose, args_quiet): + """ + Determine verbosity from various (possibly conflicting) sources of info + + :param args_verbosity: The --verbosity argument value + :param args_verbose: count of -v options + :param args_quiet: count of -q options + + start with config, override with any given --verbosity, then adjust + up/down with -vvv -qq, etc + """ + self.verbosity = self.unittest.as_int('verbosity', 1) + if args_verbosity is not None: + self.verbosity = args_verbosity + # adjust up or down, depending on the difference of these counts + self.verbosity += args_verbose - args_quiet + # floor the value at 0 -- verbosity is always a non-negative integer + self.verbosity = max(self.verbosity, 0) + + def setStartDir(self, args_start_dir=None): + """ + start dir comes from config and may be overridden by an argument + """ + self.startDir = self.unittest.as_str('start-dir', '.') + if args_start_dir is not None: + self.startDir = args_start_dir def prepareSysPath(self): """Add code directories to sys.path""" @@ -220,7 +245,8 @@ class Session(object): def isPluginLoaded(self, pluginName): """Returns ``True`` if a given plugin is loaded. - :param pluginName: the name of the plugin module: e.g. "nose2.plugins.layers". + :param pluginName: the name of the plugin module: + e.g. "nose2.plugins.layers". """ for plugin in self.plugins:
nose-devs/nose2
a964dacd3f5a9d74788299fa5dabdacabc86a2e2
diff --git a/nose2/tests/functional/test_verbosity.py b/nose2/tests/functional/test_verbosity.py new file mode 100644 index 0000000..e297e9c --- /dev/null +++ b/nose2/tests/functional/test_verbosity.py @@ -0,0 +1,77 @@ +from nose2.tests._common import FunctionalTestCase + +_SUFFIX = ( + "\n----------------------------------------------------------------------" + "\nRan 1 test " +) + +Q_TEST_PATTERN = r"(?<!\.)(?<!ok)" + _SUFFIX +MID_TEST_PATTERN = r"\." + _SUFFIX +V_TEST_PATTERN = r"test \(__main__\.Test\) \.\.\. ok" + "\n" + _SUFFIX + + +class TestVerbosity(FunctionalTestCase): + def test_no_modifier(self): + proc = self.runModuleAsMain("scenario/one_test/tests.py") + self.assertTestRunOutputMatches(proc, stderr=MID_TEST_PATTERN) + + def test_one_v(self): + proc = self.runModuleAsMain("scenario/one_test/tests.py", "-v") + self.assertTestRunOutputMatches(proc, stderr=V_TEST_PATTERN) + + def test_one_q(self): + proc = self.runModuleAsMain("scenario/one_test/tests.py", "-q") + self.assertTestRunOutputMatches(proc, stderr=Q_TEST_PATTERN) + + def test_one_q_one_v(self): + proc = self.runModuleAsMain("scenario/one_test/tests.py", "-q", "-v") + self.assertTestRunOutputMatches(proc, stderr=MID_TEST_PATTERN) + + proc = self.runModuleAsMain("scenario/one_test/tests.py", "-qv") + self.assertTestRunOutputMatches(proc, stderr=MID_TEST_PATTERN) + + def test_one_q_two_vs(self): + proc = self.runModuleAsMain("scenario/one_test/tests.py", "-q", "-v", "-v") + self.assertTestRunOutputMatches(proc, stderr=V_TEST_PATTERN) + + proc = self.runModuleAsMain("scenario/one_test/tests.py", "-qvv") + self.assertTestRunOutputMatches(proc, stderr=V_TEST_PATTERN) + + def test_one_v_two_qs(self): + proc = self.runModuleAsMain("scenario/one_test/tests.py", "-v", "-q", "-q") + self.assertTestRunOutputMatches(proc, stderr=Q_TEST_PATTERN) + + proc = self.runModuleAsMain("scenario/one_test/tests.py", "-vqq") + self.assertTestRunOutputMatches(proc, stderr=Q_TEST_PATTERN) + + def test_explicit_verbosity(self): + proc = self.runModuleAsMain("scenario/one_test/tests.py", "--verbosity", "0") + self.assertTestRunOutputMatches(proc, stderr=Q_TEST_PATTERN) + + proc = self.runModuleAsMain("scenario/one_test/tests.py", "--verbosity", "1") + self.assertTestRunOutputMatches(proc, stderr=MID_TEST_PATTERN) + + proc = self.runModuleAsMain("scenario/one_test/tests.py", "--verbosity", "2") + self.assertTestRunOutputMatches(proc, stderr=V_TEST_PATTERN) + + proc = self.runModuleAsMain("scenario/one_test/tests.py", "--verbosity", "-1") + self.assertTestRunOutputMatches(proc, stderr=Q_TEST_PATTERN) + + def test_tweaked_explicit_verbosity(self): + proc = self.runModuleAsMain( + "scenario/one_test/tests.py", "--verbosity", "0", "-vv" + ) + self.assertTestRunOutputMatches(proc, stderr=V_TEST_PATTERN) + proc = self.runModuleAsMain( + "scenario/one_test/tests.py", "-vv", "--verbosity", "0" + ) + self.assertTestRunOutputMatches(proc, stderr=V_TEST_PATTERN) + + proc = self.runModuleAsMain( + "scenario/one_test/tests.py", "--verbosity", "2", "-q" + ) + self.assertTestRunOutputMatches(proc, stderr=MID_TEST_PATTERN) + proc = self.runModuleAsMain( + "scenario/one_test/tests.py", "-q", "--verbosity", "2", "-q" + ) + self.assertTestRunOutputMatches(proc, stderr=Q_TEST_PATTERN)
verbosity is ignored when set in configuration file or as an argument to nose2.main() This is, I think, related to, but is not the same as, issue #115. After seeing no affect when I set verbosity in my .cfg file or passed it as an argument from nose2.main(), I used a debugger to dive into the code and it seemed to lose its verbosity somewhere along the line and revert to using the session's default verbosity of 1. I haven't been able to figure out what value verbosity takes when nose2 is run from the command line with "-v", though that does work.
0.0
[ "nose2/tests/functional/test_verbosity.py::TestVerbosity::test_explicit_verbosity", "nose2/tests/functional/test_verbosity.py::TestVerbosity::test_one_q", "nose2/tests/functional/test_verbosity.py::TestVerbosity::test_one_q_one_v", "nose2/tests/functional/test_verbosity.py::TestVerbosity::test_one_q_two_vs", "nose2/tests/functional/test_verbosity.py::TestVerbosity::test_one_v_two_qs", "nose2/tests/functional/test_verbosity.py::TestVerbosity::test_tweaked_explicit_verbosity" ]
[ "nose2/tests/functional/test_verbosity.py::TestVerbosity::test_no_modifier", "nose2/tests/functional/test_verbosity.py::TestVerbosity::test_one_v" ]
2018-08-15 17:22:29+00:00
4,246
nose-devs__nose2-439
diff --git a/nose2/plugins/prof.py b/nose2/plugins/prof.py index b24207f..1127f43 100644 --- a/nose2/plugins/prof.py +++ b/nose2/plugins/prof.py @@ -1,8 +1,8 @@ """ -Profile test execution using hotshot. +Profile test execution using cProfile. This plugin implements :func:`startTestRun` and replaces -``event.executeTests`` with :meth:`hotshot.Profile.runcall`. It +``event.executeTests`` with :meth:`cProfile.Profile.runcall`. It implements :func:`beforeSummaryReport` to output profiling information before the final test summary time. Config file options ``filename``, ``sort`` and ``restrict`` can be used to change where profiling @@ -15,14 +15,9 @@ entries (`plugin` and `always_on`) in the respective sections of the configuration file. """ -try: - import hotshot - from hotshot import stats -except ImportError: - hotshot, stats = None, None +import cProfile +import pstats import logging -import os -import tempfile from nose2 import events, util @@ -41,20 +36,11 @@ class Profiler(events.Plugin): self.pfile = self.config.as_str('filename', '') self.sort = self.config.as_str('sort', 'cumulative') self.restrict = self.config.as_list('restrict', []) - self.clean = False self.fileno = None - def register(self): - """Don't register if hotshot is not found""" - if hotshot is None: - log.error("Unable to profile: hotshot module not available") - return - super(Profiler, self).register() - def startTestRun(self, event): """Set up the profiler""" - self.createPfile() - self.prof = hotshot.Profile(self.pfile) + self.prof = cProfile.Profile() event.executeTests = self.prof.runcall def beforeSummaryReport(self, event): @@ -68,34 +54,16 @@ class Profiler(events.Plugin): event.stream.write(' ') event.stream.flush() stream = Stream() - self.prof.close() - prof_stats = stats.load(self.pfile) + prof_stats = pstats.Stats(self.prof, stream=stream) prof_stats.sort_stats(self.sort) event.stream.writeln(util.ln("Profiling results")) - tmp = prof_stats.stream - prof_stats.stream = stream - try: - if self.restrict: - prof_stats.print_stats(*self.restrict) - else: - prof_stats.print_stats() - finally: - prof_stats.stream = tmp - self.prof.close() - event.stream.writeln('') + if self.restrict: + prof_stats.print_stats(*self.restrict) + else: + prof_stats.print_stats() - if self.clean: - if self.fileno: - try: - os.close(self.fileno) - except OSError: - pass - try: - os.unlink(self.pfile) - except OSError: - pass + if self.pfile: + prof_stats.dump_stats(self.pfile) - def createPfile(self): - if not self.pfile: - self.fileno, self.pfile = tempfile.mkstemp() - self.clean = True + self.prof.disable() + event.stream.writeln('')
nose-devs/nose2
9583d518b338d70dbccc66604c6ff5ca6cfc912b
diff --git a/nose2/tests/unit/test_prof_plugin.py b/nose2/tests/unit/test_prof_plugin.py index 8455d56..b9f61d7 100644 --- a/nose2/tests/unit/test_prof_plugin.py +++ b/nose2/tests/unit/test_prof_plugin.py @@ -9,19 +9,20 @@ class TestProfPlugin(TestCase): def setUp(self): self.plugin = prof.Profiler(session=session.Session()) - self.hotshot = prof.hotshot - self.stats = prof.stats - prof.hotshot = Stub() - prof.stats = Stub() + # stub out and save the cProfile and pstats modules + self.cProfile = prof.cProfile + self.pstats = prof.pstats + prof.cProfile = Stub() + prof.pstats = Stub() def tearDown(self): - prof.hotshot = self.hotshot - prof.stats = self.stats + prof.cProfile = self.cProfile + prof.pstats = self.pstats def test_startTestRun_sets_executeTests(self): _prof = Stub() _prof.runcall = object() - prof.hotshot.Profile = lambda filename: _prof + prof.cProfile.Profile = lambda: _prof event = StartTestRunEvent(runner=None, suite=None, result=None, startTime=None, executeTests=None) self.plugin.startTestRun(event)
[profile plugin] hotshot is broken In Python there is a 10 years old bug and I stumbled upon it: http://bugs.python.org/issue900092 And quote from python [docs](https://docs.python.org/2/library/hotshot.html) about hotspot: ``` For common usage it is recommended to use cProfile instead. hotshot is not maintained and might be removed from the standard library in the future. ``` So, my proposal is to replace hotspot by cProfile (or something else, actually I'm not familiar with this part of python)
0.0
[ "nose2/tests/unit/test_prof_plugin.py::TestProfPlugin::test_startTestRun_sets_executeTests" ]
[]
2019-04-01 13:15:26+00:00
4,247
nose-devs__nose2-469
diff --git a/nose2/plugins/loader/functions.py b/nose2/plugins/loader/functions.py index d7b6563..5bd7212 100644 --- a/nose2/plugins/loader/functions.py +++ b/nose2/plugins/loader/functions.py @@ -87,6 +87,7 @@ class Functions(Plugin): parent, obj, name, index = result if (isinstance(obj, types.FunctionType) and not + isinstance(parent, type) and not util.isgenerator(obj) and not hasattr(obj, 'paramList') and util.num_expected_args(obj) == 0): diff --git a/nose2/plugins/mp.py b/nose2/plugins/mp.py index 33f488e..da71f7e 100644 --- a/nose2/plugins/mp.py +++ b/nose2/plugins/mp.py @@ -22,7 +22,7 @@ class MultiProcess(events.Plugin): configSection = 'multiprocess' def __init__(self): - self.addArgument(self.setProcs, 'N', 'processes', '# o procs') + self.addArgument(self.setProcs, 'N', 'processes', 'Number of processes used to run tests (0 = auto)') self.testRunTimeout = self.config.as_float('test-run-timeout', 60.0) self._procs = self.config.as_int( 'processes', 0) @@ -46,7 +46,7 @@ class MultiProcess(events.Plugin): def procs(self, value): """Setter for procs property""" if value < 0: - raise AttributeError("Can't set the procs number to less than 0, (0 = Auto)") + raise ValueError("Number of processes cannot be less than 0") self._procs = value def setProcs(self, num):
nose-devs/nose2
049afb837852881460c18c81d32008c8fdef025b
diff --git a/nose2/plugins/doctests.py b/nose2/plugins/doctests.py index 20a25e6..af16195 100644 --- a/nose2/plugins/doctests.py +++ b/nose2/plugins/doctests.py @@ -42,6 +42,9 @@ class DocTestLoader(Plugin): return name, package_path = util.name_from_path(path) + # ignore top-level setup.py which cannot be imported + if name == 'setup': + return util.ensure_importable(package_path) try: module = util.module_from_name(name) diff --git a/nose2/tests/unit/test_doctest_plugin.py b/nose2/tests/unit/test_doctest_plugin.py index 79b2967..6ea9344 100644 --- a/nose2/tests/unit/test_doctest_plugin.py +++ b/nose2/tests/unit/test_doctest_plugin.py @@ -2,6 +2,8 @@ import sys import doctest +from textwrap import dedent + from nose2 import events, loader, session from nose2.plugins import doctests from nose2.tests._common import TestCase @@ -60,6 +62,22 @@ def func(): else: self.assertEqual(event.extraTests, []) + def test_handle_file_python_setup_py(self): + # Test calling handleFile on a top-level setup.py file. + # The file should be ignored by the plugin as it cannot safely be + # imported. + + setup_py = dedent("""\ + ''' + >>> never executed + ''' + from setuptools import setup + setup(name='foo') + """ + ) + event = self._handle_file("setup.py", setup_py) + self.assertEqual(event.extraTests, []) + def _handle_file(self, fpath, content): """Have plugin handle a file with certain content. diff --git a/nose2/tests/unit/test_functions_loader.py b/nose2/tests/unit/test_functions_loader.py index cf1d6fd..e6fd25d 100644 --- a/nose2/tests/unit/test_functions_loader.py +++ b/nose2/tests/unit/test_functions_loader.py @@ -1,4 +1,11 @@ import unittest + +try: + from unittest import mock +except ImportError: + # Python versions older than 3.3 don't have mock by default + import mock + from nose2 import events, loader, session from nose2.plugins.loader import functions from nose2.tests._common import TestCase @@ -47,3 +54,37 @@ class TestFunctionLoader(TestCase): event = events.LoadFromModuleEvent(self.loader, m) self.session.hooks.loadTestsFromModule(event) self.assertEqual(len(event.extraTests), 0) + + def test_can_load_test_functions_from_name(self): + event = events.LoadFromNameEvent(self.loader, __name__+'.func', None) + suite = self.session.hooks.loadTestsFromName(event) + self.assertNotEqual(suite, None) + + def test_ignores_test_methods_from_name(self): + # Should ignore test methods even when specified directly + event = events.LoadFromNameEvent(self.loader, __name__+'.Case.test_method', None) + suite = self.session.hooks.loadTestsFromName(event) + self.assertEqual(suite, None) + + def test_ignores_decorated_test_methods_from_name(self): + # Should ignore test methods even when they are of FunctionType + event = events.LoadFromNameEvent(self.loader, __name__+'.Case.test_patched', None) + suite = self.session.hooks.loadTestsFromName(event) + self.assertEqual(suite, None) + + +def func(): + pass + +def dummy(): + pass + +class Case(unittest.TestCase): + __test__ = False # do not run this + + def test_method(self): + pass + + @mock.patch(__name__+'.dummy') + def test_patched(self, mock): + pass
Enabling [doctest] always-on = true makes nose2 exit with "error: no commands supplied" I'm trying to migrate check-manifest's test suite from nose to nose2. I have a couple of doctests I'm trying to include in the test suite, by creating a `unittest2.cfg` with ```ini [unittest] plugins = nose2.plugins.doctests [doctest] always-on = true ``` However as soon as I do that, running `nose2` with no command-line arguments fails: ``` $ nose2 usage: nose2 [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: nose2 --help [cmd1 cmd2 ...] or: nose2 --help-commands or: nose2 cmd --help error: no commands supplied ``` I can comment out the `always-on = true` line and then nose2 runs all the tests (but no doctests).
0.0
[ "nose2/tests/unit/test_functions_loader.py::TestFunctionLoader::test_ignores_decorated_test_methods_from_name" ]
[ "nose2/tests/unit/test_doctest_plugin.py::UnitTestDocTestLoader::test___init__", "nose2/tests/unit/test_doctest_plugin.py::UnitTestDocTestLoader::test_handle_file", "nose2/tests/unit/test_doctest_plugin.py::UnitTestDocTestLoader::test_handle_file_python_setup_py", "nose2/tests/unit/test_doctest_plugin.py::UnitTestDocTestLoader::test_handle_file_python_without_doctests", "nose2/tests/unit/test_functions_loader.py::TestFunctionLoader::test_can_load_test_functions_from_module", "nose2/tests/unit/test_functions_loader.py::TestFunctionLoader::test_can_load_test_functions_from_name", "nose2/tests/unit/test_functions_loader.py::TestFunctionLoader::test_ignores_functions_that_take_args", "nose2/tests/unit/test_functions_loader.py::TestFunctionLoader::test_ignores_generator_functions", "nose2/tests/unit/test_functions_loader.py::TestFunctionLoader::test_ignores_test_methods_from_name" ]
2020-06-08 13:12:25+00:00
4,248
nose-devs__nose2-472
diff --git a/nose2/plugins/loader/functions.py b/nose2/plugins/loader/functions.py index d7b6563..5bd7212 100644 --- a/nose2/plugins/loader/functions.py +++ b/nose2/plugins/loader/functions.py @@ -87,6 +87,7 @@ class Functions(Plugin): parent, obj, name, index = result if (isinstance(obj, types.FunctionType) and not + isinstance(parent, type) and not util.isgenerator(obj) and not hasattr(obj, 'paramList') and util.num_expected_args(obj) == 0):
nose-devs/nose2
049afb837852881460c18c81d32008c8fdef025b
diff --git a/nose2/tests/unit/test_functions_loader.py b/nose2/tests/unit/test_functions_loader.py index cf1d6fd..e6fd25d 100644 --- a/nose2/tests/unit/test_functions_loader.py +++ b/nose2/tests/unit/test_functions_loader.py @@ -1,4 +1,11 @@ import unittest + +try: + from unittest import mock +except ImportError: + # Python versions older than 3.3 don't have mock by default + import mock + from nose2 import events, loader, session from nose2.plugins.loader import functions from nose2.tests._common import TestCase @@ -47,3 +54,37 @@ class TestFunctionLoader(TestCase): event = events.LoadFromModuleEvent(self.loader, m) self.session.hooks.loadTestsFromModule(event) self.assertEqual(len(event.extraTests), 0) + + def test_can_load_test_functions_from_name(self): + event = events.LoadFromNameEvent(self.loader, __name__+'.func', None) + suite = self.session.hooks.loadTestsFromName(event) + self.assertNotEqual(suite, None) + + def test_ignores_test_methods_from_name(self): + # Should ignore test methods even when specified directly + event = events.LoadFromNameEvent(self.loader, __name__+'.Case.test_method', None) + suite = self.session.hooks.loadTestsFromName(event) + self.assertEqual(suite, None) + + def test_ignores_decorated_test_methods_from_name(self): + # Should ignore test methods even when they are of FunctionType + event = events.LoadFromNameEvent(self.loader, __name__+'.Case.test_patched', None) + suite = self.session.hooks.loadTestsFromName(event) + self.assertEqual(suite, None) + + +def func(): + pass + +def dummy(): + pass + +class Case(unittest.TestCase): + __test__ = False # do not run this + + def test_method(self): + pass + + @mock.patch(__name__+'.dummy') + def test_patched(self, mock): + pass
Failed to run a specific test with mock.patch decorator using nose2 This is my test file `test_mock.py` that minimally reproduces the failure: ``` import unittest from unittest.mock import patch class TestMock(unittest.TestCase): @patch("urllib3.PoolManager") def test_foo(self, mock_urllib3_poolmanager): pass ``` When I use nose2 to run all tests in this file. Everything works. ``` bash-4.2# nose2 test_mock . ---------------------------------------------------------------------- Ran 1 test in 0.102s OK ``` But when I use nose2 to select a specific test to run. It throws an error. ``` bash-4.2# nose2 test_mock.TestMock.test_foo E ====================================================================== ERROR: test_mock.transplant_class.<locals>.C (test_foo) ---------------------------------------------------------------------- Traceback (most recent call last): File "/var/lang/lib/python3.7/unittest/mock.py", line 1256, in patched return func(*args, **keywargs) TypeError: test_foo() missing 1 required positional argument: 'mock_urllib3_poolmanager' ---------------------------------------------------------------------- Ran 1 test in 0.087s FAILED (errors=1) ``` Any insight is greatly appreciated. Thanks!
0.0
[ "nose2/tests/unit/test_functions_loader.py::TestFunctionLoader::test_ignores_decorated_test_methods_from_name" ]
[ "nose2/tests/unit/test_functions_loader.py::TestFunctionLoader::test_can_load_test_functions_from_module", "nose2/tests/unit/test_functions_loader.py::TestFunctionLoader::test_can_load_test_functions_from_name", "nose2/tests/unit/test_functions_loader.py::TestFunctionLoader::test_ignores_functions_that_take_args", "nose2/tests/unit/test_functions_loader.py::TestFunctionLoader::test_ignores_generator_functions", "nose2/tests/unit/test_functions_loader.py::TestFunctionLoader::test_ignores_test_methods_from_name" ]
2020-07-27 18:27:49+00:00
4,249
nose-devs__nose2-474
diff --git a/nose2/plugins/loader/functions.py b/nose2/plugins/loader/functions.py index d7b6563..5bd7212 100644 --- a/nose2/plugins/loader/functions.py +++ b/nose2/plugins/loader/functions.py @@ -87,6 +87,7 @@ class Functions(Plugin): parent, obj, name, index = result if (isinstance(obj, types.FunctionType) and not + isinstance(parent, type) and not util.isgenerator(obj) and not hasattr(obj, 'paramList') and util.num_expected_args(obj) == 0): diff --git a/nose2/plugins/mp.py b/nose2/plugins/mp.py index 33f488e..da71f7e 100644 --- a/nose2/plugins/mp.py +++ b/nose2/plugins/mp.py @@ -22,7 +22,7 @@ class MultiProcess(events.Plugin): configSection = 'multiprocess' def __init__(self): - self.addArgument(self.setProcs, 'N', 'processes', '# o procs') + self.addArgument(self.setProcs, 'N', 'processes', 'Number of processes used to run tests (0 = auto)') self.testRunTimeout = self.config.as_float('test-run-timeout', 60.0) self._procs = self.config.as_int( 'processes', 0) @@ -46,7 +46,7 @@ class MultiProcess(events.Plugin): def procs(self, value): """Setter for procs property""" if value < 0: - raise AttributeError("Can't set the procs number to less than 0, (0 = Auto)") + raise ValueError("Number of processes cannot be less than 0") self._procs = value def setProcs(self, num):
nose-devs/nose2
049afb837852881460c18c81d32008c8fdef025b
diff --git a/nose2/tests/unit/test_functions_loader.py b/nose2/tests/unit/test_functions_loader.py index cf1d6fd..e6fd25d 100644 --- a/nose2/tests/unit/test_functions_loader.py +++ b/nose2/tests/unit/test_functions_loader.py @@ -1,4 +1,11 @@ import unittest + +try: + from unittest import mock +except ImportError: + # Python versions older than 3.3 don't have mock by default + import mock + from nose2 import events, loader, session from nose2.plugins.loader import functions from nose2.tests._common import TestCase @@ -47,3 +54,37 @@ class TestFunctionLoader(TestCase): event = events.LoadFromModuleEvent(self.loader, m) self.session.hooks.loadTestsFromModule(event) self.assertEqual(len(event.extraTests), 0) + + def test_can_load_test_functions_from_name(self): + event = events.LoadFromNameEvent(self.loader, __name__+'.func', None) + suite = self.session.hooks.loadTestsFromName(event) + self.assertNotEqual(suite, None) + + def test_ignores_test_methods_from_name(self): + # Should ignore test methods even when specified directly + event = events.LoadFromNameEvent(self.loader, __name__+'.Case.test_method', None) + suite = self.session.hooks.loadTestsFromName(event) + self.assertEqual(suite, None) + + def test_ignores_decorated_test_methods_from_name(self): + # Should ignore test methods even when they are of FunctionType + event = events.LoadFromNameEvent(self.loader, __name__+'.Case.test_patched', None) + suite = self.session.hooks.loadTestsFromName(event) + self.assertEqual(suite, None) + + +def func(): + pass + +def dummy(): + pass + +class Case(unittest.TestCase): + __test__ = False # do not run this + + def test_method(self): + pass + + @mock.patch(__name__+'.dummy') + def test_patched(self, mock): + pass
Improve mp plugin's command line help '# o procs' does not quite cut it, IMHO.
0.0
[ "nose2/tests/unit/test_functions_loader.py::TestFunctionLoader::test_ignores_decorated_test_methods_from_name" ]
[ "nose2/tests/unit/test_functions_loader.py::TestFunctionLoader::test_can_load_test_functions_from_module", "nose2/tests/unit/test_functions_loader.py::TestFunctionLoader::test_can_load_test_functions_from_name", "nose2/tests/unit/test_functions_loader.py::TestFunctionLoader::test_ignores_functions_that_take_args", "nose2/tests/unit/test_functions_loader.py::TestFunctionLoader::test_ignores_generator_functions", "nose2/tests/unit/test_functions_loader.py::TestFunctionLoader::test_ignores_test_methods_from_name" ]
2020-07-28 09:42:44+00:00
4,250
novonordisk-research__ProcessOptimizer-91
diff --git a/ProcessOptimizer/bokeh_plot.py b/ProcessOptimizer/bokeh_plot.py index e71b40a..24d8d69 100644 --- a/ProcessOptimizer/bokeh_plot.py +++ b/ProcessOptimizer/bokeh_plot.py @@ -280,7 +280,7 @@ def get_plot_list(layout, result, active_list, n_points, x_eval, confidence): elif i == j: # Diagonal # Passing j = None to dependence # makes it calculate a diagonal plot - xi, yi = dependence( + xi, yi, _ = dependence( space, model, i, diff --git a/ProcessOptimizer/space/space.py b/ProcessOptimizer/space/space.py index a31b04f..e66e504 100644 --- a/ProcessOptimizer/space/space.py +++ b/ProcessOptimizer/space/space.py @@ -305,10 +305,13 @@ class Real(Dimension): * `n` [int] Number of samples. """ - a = (np.arange(n)+0.5)/n # Evenly distributed betweeen 0 and 1 + # Generate sample points by splitting the space 0 to 1 into n pieces + # and picking the middle of each piece. Samples are spaced 1/n apart + # inside the interval with a buffer of half a step size to the extremes + samples = (np.arange(n)+0.5)/n - # Transform to the bounds of this dimension - return a*(self.high-self.low)+self.low + # Transform the samples to the range used for this dimension + return samples*(self.high - self.low) + self.low class Integer(Dimension): @@ -413,9 +416,17 @@ class Integer(Dimension): * `n` [int] Number of samples. """ - rounded_numbers = np.round(np.linspace(self.low, self.high, n)) - # convert to a list of integers - return [int(a) for a in rounded_numbers] + # Generate sample points by splitting the space 0 to 1 into n pieces + # and picking the middle of each piece. Samples are spaced 1/n apart + # inside the interval with a buffer of half a step size to the extremes + samples = (np.arange(n)+0.5)/n + # Transform the samples to the range used for this dimension and then + # round them back to integers. If your space is less than n wide, some + # of your samples will be rounded to the same number + samples = np.round(samples*(self.high - self.low) + self.low) + + # Convert samples to a list of integers + return samples.astype(int) class Categorical(Dimension):
novonordisk-research/ProcessOptimizer
993e20f35646901862616b4218a1443eeb0866cc
diff --git a/ProcessOptimizer/tests/test_space.py b/ProcessOptimizer/tests/test_space.py index 82e0c43..7f458fe 100644 --- a/ProcessOptimizer/tests/test_space.py +++ b/ProcessOptimizer/tests/test_space.py @@ -671,12 +671,21 @@ def test_purely_categorical_space(): @pytest.mark.fast_test def test_lhs_arange(): - dim = Categorical(["a", "b", "c"]) - dim.lhs_arange(10) - dim = Integer(1, 20) - dim.lhs_arange(10) - dim = Real(-10, 20) - dim.lhs_arange(10) + # Test that the latin hypercube sampling functions run normally + dim_cat = Categorical(["a", "b", "c"]) + dim_cat.lhs_arange(10) + dim_int = Integer(-10, 20) + lhs_int = dim_int.lhs_arange(10) + dim_real = Real(-10, 20) + lhs_real = dim_real.lhs_arange(10) + # Test that the Integer and Real classes return identical points after + # rounding, using Numpy's allclose function + assert np.allclose(lhs_int, lhs_real, atol=0.5) + # Test that the Integer class returns values that are ints for all intents + # and purposes + assert all([np.mod(x,1) == 0 for x in lhs_int]) + # Test that the Real class returns flots in all locations + assert all([isinstance(x,np.float64) for x in lhs_real]) @pytest.mark.fast_test @@ -687,3 +696,4 @@ def test_lhs(): samples = SPACE.lhs(10) assert len(samples) == 10 assert len(samples[0]) == 3 +
LHS sampling is different if limits are continuous or discrete The points returned by the latin hypercube sampling differs, depending on whether the min/max limits are defined as integers or reals. An example that illustrates it is the following code: ``` from ProcessOptimizer import Optimizer n_init = 5 space1 = [(0,100),(0,100),(0,100)] space2 = [(0.0,100.0),(0.0,100.0),(0.0,100.0)] opt1 = Optimizer(space1,n_initial_points=n_init) opt2 = Optimizer(space2,n_initial_points=n_init) opt1.ask(5) opt2.ask(5) ``` op1 returns: ```[[25, 75, 0], [100, 50, 50], [50, 25, 25], [0, 0, 75], [75, 100, 100]]``` while opt2 returns: ```[[30.0, 70.0, 10.0], [90.0, 50.0, 50.0], [50.0, 30.0, 30.0], [10.0, 10.0, 70.0], [70.0, 90.0, 90.0]]``` In my opinion, these lists should be the same within rounding. The difference is caused by different definitions of `lhs_arange` for the class Real and the class Integer in space.py. In the case of Real the points are spaced equally, with a half-step buffer to the limit values like this: `a = (np.arange(n)+0.5)/n`, while Integers do not include the buffer at the limits: `rounded_numbers = np.round(np.linspace(self.low, self.high, n))`. I'll work on a fix for the integer class.
0.0
[ "ProcessOptimizer/tests/test_space.py::test_lhs_arange" ]
[ "ProcessOptimizer/tests/test_space.py::test_dimensions", "ProcessOptimizer/tests/test_space.py::test_real_log_sampling_in_bounds", "ProcessOptimizer/tests/test_space.py::test_real", "ProcessOptimizer/tests/test_space.py::test_real_bounds", "ProcessOptimizer/tests/test_space.py::test_integer", "ProcessOptimizer/tests/test_space.py::test_categorical_transform", "ProcessOptimizer/tests/test_space.py::test_categorical_transform_binary", "ProcessOptimizer/tests/test_space.py::test_categorical_repr", "ProcessOptimizer/tests/test_space.py::test_space_consistency", "ProcessOptimizer/tests/test_space.py::test_space_api", "ProcessOptimizer/tests/test_space.py::test_space_from_space", "ProcessOptimizer/tests/test_space.py::test_normalize", "ProcessOptimizer/tests/test_space.py::test_valid_transformation", "ProcessOptimizer/tests/test_space.py::test_invalid_dimension", "ProcessOptimizer/tests/test_space.py::test_categorical_identity", "ProcessOptimizer/tests/test_space.py::test_categorical_distance", "ProcessOptimizer/tests/test_space.py::test_integer_distance", "ProcessOptimizer/tests/test_space.py::test_integer_distance_out_of_range", "ProcessOptimizer/tests/test_space.py::test_real_distance_out_of_range", "ProcessOptimizer/tests/test_space.py::test_real_distance", "ProcessOptimizer/tests/test_space.py::test_dimension_bounds[Real-bounds0]", "ProcessOptimizer/tests/test_space.py::test_dimension_bounds[Integer-bounds1]", "ProcessOptimizer/tests/test_space.py::test_dimension_bounds[Real-bounds2]", "ProcessOptimizer/tests/test_space.py::test_dimension_bounds[Integer-bounds3]", "ProcessOptimizer/tests/test_space.py::test_dimension_name[dimension0-learning", "ProcessOptimizer/tests/test_space.py::test_dimension_name[dimension1-no", "ProcessOptimizer/tests/test_space.py::test_dimension_name[dimension2-colors]", "ProcessOptimizer/tests/test_space.py::test_dimension_name_none[dimension0]", "ProcessOptimizer/tests/test_space.py::test_dimension_name_none[dimension1]", "ProcessOptimizer/tests/test_space.py::test_dimension_name_none[dimension2]", "ProcessOptimizer/tests/test_space.py::test_space_from_yaml", "ProcessOptimizer/tests/test_space.py::test_dimension_with_invalid_names[1]", "ProcessOptimizer/tests/test_space.py::test_dimension_with_invalid_names[1.0]", "ProcessOptimizer/tests/test_space.py::test_dimension_with_invalid_names[True]", "ProcessOptimizer/tests/test_space.py::test_purely_categorical_space", "ProcessOptimizer/tests/test_space.py::test_lhs" ]
2022-01-27 12:35:26+00:00
4,251
nteract__vdom-22
diff --git a/README.md b/README.md index 413c20e..b232b49 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ ## Why use VDOM? - Write **Declarative** Pythonic layouts. -- Render the layout in Jupyter and nteract frontends. +- Render the layout in Jupyter frontends. - Serialize layout for rehydration in your web app. :warning: This library is a work in progress. :warning: diff --git a/docs/design-patterns.md b/docs/design-patterns.md new file mode 100644 index 0000000..fcff958 --- /dev/null +++ b/docs/design-patterns.md @@ -0,0 +1,150 @@ +# Design Patterns + +The main operating principle for `vdom` (virtual DOM) is: + +> Write functions that return `vdom` elements + +In matching with `React` parlance, we'll call these functions components. This allows you to share, remix, and use components amongst everyone. You'll be able to compose together components to create greater components than you have before. + +## Introductory component + +We'll start with a component that takes a level of happiness and produces a light visualization: + +```python +from vdom.helpers import div, span, p, meter + +def happiness(level=90): + smiley = "😃" + percent = level / 100. + + if(percent < 0.25): + smiley = "☹️" + elif(percent < 0.50): + smiley = "😐" + elif(percent < 0.75): + smiley = "😀" + + + return span( + p('Happiness ', smiley), + meter(level, min=0, low=25, high=75, optimum=90, max=100, value=level) + ) +``` + +The user of the component only needs to call it with a level of happiness from 0 to 100. + +```python +happiness(96) +``` + +<span> +<p>Happiness 😃</p> +<meter min="0" low="25" high="75" optimum="90" max="100" value="96"> + 96 +</meter> +</span> + +------------ + +:tada: Our first component is ready! Since we can think of `happiness` as a little building block component, we can put several of these together to create whole layouts: + +```python +div( + happiness(10), + happiness(32), + happiness(65), + happiness(80) +) +``` + +<span> +<p>Happiness ☹️</p> +<meter min="0" low="25" high="75" optimum="90" max="100" value="10"> + 10 +</meter> +</span> +<span> +<p>Happiness 😐</p> +<meter min="0" low="25" high="75" optimum="90" max="100" value="32"> + 32 +</meter> +</span> +<span> +<p>Happiness 😀</p> +<meter min="0" low="25" high="75" optimum="90" max="100" value="65"> + 65 +</meter> +</span> +<span> +<p>Happiness 😃</p> +<meter min="0" low="25" high="75" optimum="90" max="100" value="80"> + 80 +</meter> +</span> + +------------------- + + +## Working with Python objects + +For this section, you'll need `ggplot` and `matplotlib` packages installed. We'll create a component, `fancy_hist` that creates a histogram which allows for displaying side by side + +```python +import matplotlib.pyplot as plt +import io, base64, urllib + +def fancy_hist(value, data=mpg, title="Plot", bins=12, style=None): + if(style is None): + style = {"display": "inline-block"} + + f = plt.figure() + plt.hist(value, bins=bins, data=data) + + buf = io.BytesIO() + f.savefig(buf, format='png') + buf.seek(0) + string = base64.b64encode(buf.read()) + + plt.close() + + return div( + h1(title), + p(str(bins), " bins"), + img(src='data:image/png;base64,' + urllib.parse.quote(string)), + style=style + ) +``` + + +```python +from ggplot import mpg +fancy_hist('cty', data=mpg, title="City MPG") +``` + +<div style="display: inline-block"> + <h1>City MPG</h1> + <p>12 bins</p> + <img src="" /> +</div> + + +```python +div( + fancy_hist('hwy', data=mpg, title="Highway MPG"), + fancy_hist('cty', data=mpg, title="City MPG") +) + +``` + +<div> +<div style="display: inline-block"> + <h1>Highway MPG</h1> + <p>12 bins</p> + <img src="" /> +</div> +<div style="display: inline-block"> + <h1>City MPG</h1> + <p>12 bins</p> + <img src="" /> +</div> +</div> diff --git a/vdom/core.py b/vdom/core.py index 23bb4e1..448fe7d 100644 --- a/vdom/core.py +++ b/vdom/core.py @@ -17,9 +17,11 @@ def toJSON(el, schema=None): If you wish to validate the JSON, pass in a schema via the schema keyword argument. If a schema is provided, this raises a ValidationError if JSON does not match the schema. """ + if(type(el) is str): + return el if(type(el) is list): - json_el = list(map(toJSON, el)) - if(type(el) is dict): + return list(map(toJSON, el)) + elif(type(el) is dict): assert 'tagName' in el json_el = el.copy() if 'attributes' not in el: @@ -45,7 +47,20 @@ def toJSON(el, schema=None): class VDOM(): - """A basic virtual DOM class""" + """A basic virtual DOM class which allows you to write literal VDOM spec + + >>> VDOM({ 'tagName': 'h1', 'children': 'Hey', 'attributes': {}}) + + It's probably better to use `vdom.h` or the helper functions: + + >>> from vdom import h + >>> h('h1', 'Hey') + <h1 /> + + >>> from vdom.helpers import h1 + >>> h1('Hey') + + """ def __init__(self, obj): self.obj = obj @@ -74,8 +89,13 @@ def _flatten_children(*children, **kwargs): # children as keyword argument takes precedence if('children' in kwargs): children = kwargs['children'] - elif children is not None and len(children) > 0: - if isinstance(children[0], list): + elif children is not None: + if len(children) == 0: + children = None + elif len(children) == 1: + # Flatten by default + children = children[0] + elif isinstance(children[0], list): # Only one level of flattening, just to match the old API children = children[0] else:
nteract/vdom
faae2c2c4e74d02a6227277675eae03822a18926
diff --git a/vdom/tests/test_core.py b/vdom/tests/test_core.py index 0f05898..ae40905 100644 --- a/vdom/tests/test_core.py +++ b/vdom/tests/test_core.py @@ -2,6 +2,7 @@ # -*- coding: utf-8 -*- from ..core import _flatten_children, toJSON +from ..helpers import div, p, img, h1, b def test_flatten_children(): @@ -18,25 +19,71 @@ def test_flatten_children(): # array as first argument second highest priority assert _flatten_children([1], 2) == [1] # otherwise, positional arguments are the default - assert _flatten_children(2) == [2] + assert _flatten_children(2, 3) == [2, 3] - # with no arguments, we get an empty array - assert _flatten_children() == [] # an empty array returns an empty array assert _flatten_children([]) == [] + # with no arguments, we get a null + assert _flatten_children() == None # If the first argument is None, we assume they explicitly wanted a # null element for a VDOMEl (this is ok) - assert _flatten_children(None) == [None] + assert _flatten_children(None) == None assert _flatten_children(None, 1, None) == [None, 1, None] def test_toJSON(): assert toJSON({ 'tagName': 'h1', - 'attributes': {} + 'attributes': { 'data-test': True }, + 'children': [] }) == { 'tagName': 'h1', - 'attributes': {}, + 'attributes': { 'data-test': True}, 'children': [] } + + assert toJSON(div(h1('Our Incredibly Declarative Example'))) == { + 'tagName': 'div', + 'children': { + 'tagName': 'h1', + 'children': 'Our Incredibly Declarative Example', + 'attributes': {} + }, + 'attributes': {} + } + + assert toJSON( + div( + h1('Our Incredibly Declarative Example'), + p('Can you believe we wrote this ', b('in Python'), '?'), + img(src="https://media.giphy.com/media/xUPGcguWZHRC2HyBRS/giphy.gif" + ), ) + ) == { + 'tagName': + 'div', + 'children': [{ + 'tagName': 'h1', + 'children': 'Our Incredibly Declarative Example', + 'attributes': {} + }, { + 'tagName': + 'p', + 'attributes': {}, + 'children': [ + 'Can you believe we wrote this ', { + 'tagName': 'b', + 'children': 'in Python', + 'attributes': {} + }, '?' + ] + }, { + 'tagName': 'img', + 'children': None, + 'attributes': { + 'src': + 'https://media.giphy.com/media/xUPGcguWZHRC2HyBRS/giphy.gif' + } + }], + 'attributes': {} + }
Write some best practices guidance for creating components Within `vdom`, the best way (that I can think of right now) to create new elements is to create functions that return elements: ```python from vdom import h, p, div def happiness(level=90): smiley = "😃" percent = level / 100. if(percent < 0.25): smiley = "☹️" elif(percent < 0.50): smiley = "😐" elif(percent < 0.75): smiley = "😀" return p([ 'Happiness ', smiley, h('br'), h('meter', level, min="0", low=25, high=75, optimum=90, max=100, value=level) ]) # Usage: happiness() div([ happiness(10), happiness(32), happiness(65), happiness(80) ]) ``` Example in nteract: ![screen shot 2017-09-25 at 11 49 15 am](https://user-images.githubusercontent.com/836375/30825369-93461922-a1e7-11e7-803c-04bd20e7fb2d.png)
0.0
[ "vdom/tests/test_core.py::test_flatten_children", "vdom/tests/test_core.py::test_toJSON" ]
[]
2017-09-30 22:14:44+00:00
4,252
nteract__vdom-45
diff --git a/vdom/core.py b/vdom/core.py index bea7cd7..798560e 100644 --- a/vdom/core.py +++ b/vdom/core.py @@ -14,7 +14,7 @@ import os import io _vdom_schema_file_path = os.path.join( - os.path.dirname(__file__), "schemas", "vdom_schema_v0.json") + os.path.dirname(__file__), "schemas", "vdom_schema_v1.json") with io.open(_vdom_schema_file_path, "r") as f: VDOM_SCHEMA = json.load(f) _validate_err_template = "Your object didn't match the schema: {}. \n {}" diff --git a/vdom/schemas/vdom_schema_v1.json b/vdom/schemas/vdom_schema_v1.json new file mode 100644 index 0000000..f6f5de5 --- /dev/null +++ b/vdom/schemas/vdom_schema_v1.json @@ -0,0 +1,34 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "additionalProperties": false, + "required": ["tagName", "children", "attributes"], + "$ref": "#/definitions/vdomEl", + "definitions": { + "vdomEl": { + "type": "object", + "required": ["tagName", "children", "attributes"], + "properties": { + "tagName": { + "type": "string" + }, + "children": { + "$ref": "#/definitions/vdomNode" + }, + "attributes": { + "type": "object" + }, + "key": { + "oneOf": [{"type": "number"}, {"type": "string"}, {"type": "null"}] + } + } + }, + "vdomNode": { + "oneOf": [ + { "$ref": "#/definitions/vdomEl" }, + {"type": "array", "items": {"$ref": "#/definitions/vdomNode"}}, + {"type": "null"}, + {"type": "string"} + ] + } + } + } \ No newline at end of file
nteract/vdom
78fa2b549f67afc3525543b0bccfb08a9e06b006
diff --git a/vdom/tests/test_core.py b/vdom/tests/test_core.py index a915a81..85c26b4 100644 --- a/vdom/tests/test_core.py +++ b/vdom/tests/test_core.py @@ -4,9 +4,17 @@ from ..core import _flatten_children, create_component, to_json, VDOM from ..helpers import div, p, img, h1, b from jsonschema import ValidationError, validate +import os +import io +import json import pytest +_vdom_schema_file_path = os.path.join( + os.path.dirname(__file__), "..", "schemas", "vdom_schema_v1.json") +with io.open(_vdom_schema_file_path, "r") as f: + VDOM_SCHEMA = json.load(f) + def test_flatten_children(): # when the first argument is an array, interpret it as the primary argument assert _flatten_children([1, 2, 3]) == [1, 2, 3] @@ -97,6 +105,7 @@ def test_to_json(): _valid_vdom_obj = {'tagName': 'h1', 'children': 'Hey', 'attributes': {}} +_invalid_vdom_obj = {'tagName': 'h1', 'children':[{'randomProperty': 'randomValue'}]} def test_schema_validation(): @@ -106,8 +115,15 @@ def test_schema_validation(): # make sure you can pass empty schema assert (VDOM([_valid_vdom_obj], schema={}).json_contents == [_valid_vdom_obj]) + + # check that you can pass a valid schema + assert (VDOM(_valid_vdom_obj, schema=VDOM_SCHEMA)) + # check that an invalid schema throws ValidationError + with pytest.raises(ValidationError): + test_vdom = VDOM([_invalid_vdom_obj], ) + def test_component_allows_children(): nonvoid = create_component('nonvoid', allow_children=True) test_component = nonvoid(div())
Write JSON Schema for the VDOM Spec Write [JSON Schema](http://json-schema.org/), like Jupyter does for nbformat. To accompany [the spec doc](https://github.com/nteract/vdom/blob/master/docs/spec.md).
0.0
[ "vdom/tests/test_core.py::test_flatten_children", "vdom/tests/test_core.py::test_to_json", "vdom/tests/test_core.py::test_schema_validation", "vdom/tests/test_core.py::test_component_allows_children" ]
[]
2017-11-21 17:40:53+00:00
4,253
numpy__numpy-financial-54
diff --git a/numpy_financial/_financial.py b/numpy_financial/_financial.py index e268424..be3fb67 100644 --- a/numpy_financial/_financial.py +++ b/numpy_financial/_financial.py @@ -849,8 +849,15 @@ def npv(rate, values): 3065.22267 """ - values = np.asarray(values) - return (values / (1+rate)**np.arange(0, len(values))).sum(axis=0) + values = np.atleast_2d(values) + timestep_array = np.arange(0, values.shape[1]) + npv = (values / (1 + rate) ** timestep_array).sum(axis=1) + try: + # If size of array is one, return scalar + return npv.item() + except ValueError: + # Otherwise, return entire array + return npv def mirr(values, finance_rate, reinvest_rate):
numpy/numpy-financial
d02edfb65dcdf23bd571c2cded7fcd4a0528c6af
diff --git a/numpy_financial/tests/test_financial.py b/numpy_financial/tests/test_financial.py index 791f1a7..ff91282 100644 --- a/numpy_financial/tests/test_financial.py +++ b/numpy_financial/tests/test_financial.py @@ -148,6 +148,19 @@ class TestNpv: npf.npv(Decimal('0.05'), [-15000, 1500, 2500, 3500, 4500, 6000]), Decimal('122.894854950942692161628715')) + def test_npv_broadcast(self): + cashflows = [ + [-15000, 1500, 2500, 3500, 4500, 6000], + [-15000, 1500, 2500, 3500, 4500, 6000], + [-15000, 1500, 2500, 3500, 4500, 6000], + [-15000, 1500, 2500, 3500, 4500, 6000], + ] + expected_npvs = [ + 122.8948549, 122.8948549, 122.8948549, 122.8948549 + ] + actual_npvs = npf.npv(0.05, cashflows) + assert_allclose(actual_npvs, expected_npvs) + class TestPmt: def test_pmt_simple(self):
Slow NPV calculations for monte carlo simulation purposes When using a large number of monte carlo simulations (~1e6 or more) for uncertainty calculations on NPV, the present implementation of Numpy-financial NPV is very slow. We suggest a new implementation of the NPV function , which allows calculation of serveral projects simultaneously, and is approximately 200 times faster than the current version for 1e6 simulations for a cash-flow of length 10. In cases where the number of entries in the cash-flow is significantly higher than the number of projects to be calculated, the old implementation will be faster. To solve this, we suggest an adaptive approach which chooses method based on the input dimensions of the 'values' array. Example code: ``` import numpy_financial as npf import numpy as np import time def faster_npv(rate: float, values: list): """ A faster way to calculate NPV for several projects based on numpy arrays. """ discounted_values = [] for i in range(np.shape(values)[0]): discounted_values.append(values[i] / (1 + rate) ** i) return np.sum(discounted_values, axis=0) rate=0.05 no_simulations = int(1e6) capex = np.random.normal(loc=10e5, scale = 10e3, size=no_simulations) lifetime = 10 #years opex = [] for yr in range(lifetime): opex.append(np.random.normal(loc=10e4, scale= 10e2,size=no_simulations)) start_time=time.time() all_npv=np.nan*np.ones_like(capex) for i in range(no_simulations): values = [capex[i]]+[op[i] for op in opex] all_npv[i]=npf.npv(rate, values) print(f"Standard NPF calculations took {time.time()-start_time} s.") start_time=time.time() values=[capex]+opex faster_npv(rate,values ) print(f"Faster NPV calculations took {time.time()-start_time} s.") ```
0.0
[ "numpy_financial/tests/test_financial.py::TestNpv::test_npv_broadcast" ]
[ "numpy_financial/tests/test_financial.py::TestFinancial::test_when", "numpy_financial/tests/test_financial.py::TestFinancial::test_decimal_with_when", "numpy_financial/tests/test_financial.py::TestPV::test_pv", "numpy_financial/tests/test_financial.py::TestPV::test_pv_decimal", "numpy_financial/tests/test_financial.py::TestRate::test_rate", "numpy_financial/tests/test_financial.py::TestRate::test_rate_with_infeasible_solution[0-Decimal]", "numpy_financial/tests/test_financial.py::TestRate::test_rate_with_infeasible_solution[0-float]", "numpy_financial/tests/test_financial.py::TestRate::test_rate_with_infeasible_solution[1-Decimal]", "numpy_financial/tests/test_financial.py::TestRate::test_rate_with_infeasible_solution[1-float]", "numpy_financial/tests/test_financial.py::TestRate::test_rate_with_infeasible_solution[end-Decimal]", "numpy_financial/tests/test_financial.py::TestRate::test_rate_with_infeasible_solution[end-float]", "numpy_financial/tests/test_financial.py::TestRate::test_rate_with_infeasible_solution[begin-Decimal]", "numpy_financial/tests/test_financial.py::TestRate::test_rate_with_infeasible_solution[begin-float]", "numpy_financial/tests/test_financial.py::TestRate::test_rate_decimal", "numpy_financial/tests/test_financial.py::TestRate::test_gh48", "numpy_financial/tests/test_financial.py::TestNpv::test_npv", "numpy_financial/tests/test_financial.py::TestNpv::test_npv_decimal", "numpy_financial/tests/test_financial.py::TestPmt::test_pmt_simple", "numpy_financial/tests/test_financial.py::TestPmt::test_pmt_zero_rate", "numpy_financial/tests/test_financial.py::TestPmt::test_pmt_broadcast", "numpy_financial/tests/test_financial.py::TestPmt::test_pmt_decimal_simple", "numpy_financial/tests/test_financial.py::TestPmt::test_pmt_decimal_zero_rate", "numpy_financial/tests/test_financial.py::TestPmt::test_pmt_decimal_broadcast", "numpy_financial/tests/test_financial.py::TestMirr::test_mirr", "numpy_financial/tests/test_financial.py::TestMirr::test_mirr_decimal", "numpy_financial/tests/test_financial.py::TestNper::test_basic_values", "numpy_financial/tests/test_financial.py::TestNper::test_gh_18", "numpy_financial/tests/test_financial.py::TestNper::test_infinite_payments", "numpy_financial/tests/test_financial.py::TestNper::test_no_interest", "numpy_financial/tests/test_financial.py::TestNper::test_broadcast", "numpy_financial/tests/test_financial.py::TestPpmt::test_float", "numpy_financial/tests/test_financial.py::TestPpmt::test_decimal", "numpy_financial/tests/test_financial.py::TestPpmt::test_when_is_begin[1]", "numpy_financial/tests/test_financial.py::TestPpmt::test_when_is_begin[begin]", "numpy_financial/tests/test_financial.py::TestPpmt::test_when_is_end[None]", "numpy_financial/tests/test_financial.py::TestPpmt::test_when_is_end[0]", "numpy_financial/tests/test_financial.py::TestPpmt::test_when_is_end[end]", "numpy_financial/tests/test_financial.py::TestPpmt::test_when_is_begin_decimal[when0]", "numpy_financial/tests/test_financial.py::TestPpmt::test_when_is_begin_decimal[begin]", "numpy_financial/tests/test_financial.py::TestPpmt::test_when_is_end_decimal[None]", "numpy_financial/tests/test_financial.py::TestPpmt::test_when_is_end_decimal[when1]", "numpy_financial/tests/test_financial.py::TestPpmt::test_when_is_end_decimal[end]", "numpy_financial/tests/test_financial.py::TestPpmt::test_invalid_per[args0]", "numpy_financial/tests/test_financial.py::TestPpmt::test_invalid_per[args1]", "numpy_financial/tests/test_financial.py::TestPpmt::test_broadcast[None-desired0]", "numpy_financial/tests/test_financial.py::TestPpmt::test_broadcast[when1-desired1]", "numpy_financial/tests/test_financial.py::TestPpmt::test_broadcast_decimal[None-desired0]", "numpy_financial/tests/test_financial.py::TestPpmt::test_broadcast_decimal[when1-desired1]", "numpy_financial/tests/test_financial.py::TestIpmt::test_float", "numpy_financial/tests/test_financial.py::TestIpmt::test_decimal", "numpy_financial/tests/test_financial.py::TestIpmt::test_when_is_begin[1]", "numpy_financial/tests/test_financial.py::TestIpmt::test_when_is_begin[begin]", "numpy_financial/tests/test_financial.py::TestIpmt::test_when_is_end[None]", "numpy_financial/tests/test_financial.py::TestIpmt::test_when_is_end[0]", "numpy_financial/tests/test_financial.py::TestIpmt::test_when_is_end[end]", "numpy_financial/tests/test_financial.py::TestIpmt::test_when_is_begin_decimal[when0]", "numpy_financial/tests/test_financial.py::TestIpmt::test_when_is_begin_decimal[begin]", "numpy_financial/tests/test_financial.py::TestIpmt::test_when_is_end_decimal[None]", "numpy_financial/tests/test_financial.py::TestIpmt::test_when_is_end_decimal[when1]", "numpy_financial/tests/test_financial.py::TestIpmt::test_when_is_end_decimal[end]", "numpy_financial/tests/test_financial.py::TestIpmt::test_gh_17[0-nan]", "numpy_financial/tests/test_financial.py::TestIpmt::test_gh_17[1-0]", "numpy_financial/tests/test_financial.py::TestIpmt::test_gh_17[2--594.107158]", "numpy_financial/tests/test_financial.py::TestIpmt::test_gh_17[3--592.971592]", "numpy_financial/tests/test_financial.py::TestIpmt::test_broadcasting", "numpy_financial/tests/test_financial.py::TestIpmt::test_decimal_broadcasting", "numpy_financial/tests/test_financial.py::TestIpmt::test_0d_inputs", "numpy_financial/tests/test_financial.py::TestFv::test_float", "numpy_financial/tests/test_financial.py::TestFv::test_decimal", "numpy_financial/tests/test_financial.py::TestFv::test_when_is_begin_float[1]", "numpy_financial/tests/test_financial.py::TestFv::test_when_is_begin_float[begin]", "numpy_financial/tests/test_financial.py::TestFv::test_when_is_begin_decimal[when0]", "numpy_financial/tests/test_financial.py::TestFv::test_when_is_begin_decimal[begin]", "numpy_financial/tests/test_financial.py::TestFv::test_when_is_end_float[None]", "numpy_financial/tests/test_financial.py::TestFv::test_when_is_end_float[0]", "numpy_financial/tests/test_financial.py::TestFv::test_when_is_end_float[end]", "numpy_financial/tests/test_financial.py::TestFv::test_when_is_end_decimal[None]", "numpy_financial/tests/test_financial.py::TestFv::test_when_is_end_decimal[when1]", "numpy_financial/tests/test_financial.py::TestFv::test_when_is_end_decimal[end]", "numpy_financial/tests/test_financial.py::TestFv::test_broadcast", "numpy_financial/tests/test_financial.py::TestFv::test_some_rates_zero", "numpy_financial/tests/test_financial.py::TestIrr::test_npv_irr_congruence", "numpy_financial/tests/test_financial.py::TestIrr::test_basic_values[v0-0.0524]", "numpy_financial/tests/test_financial.py::TestIrr::test_basic_values[v1--0.0955]", "numpy_financial/tests/test_financial.py::TestIrr::test_basic_values[v2-0.28095]", "numpy_financial/tests/test_financial.py::TestIrr::test_basic_values[v3--0.0833]", "numpy_financial/tests/test_financial.py::TestIrr::test_basic_values[v4-0.06206]", "numpy_financial/tests/test_financial.py::TestIrr::test_basic_values[v5-0.0886]", "numpy_financial/tests/test_financial.py::TestIrr::test_trailing_zeros", "numpy_financial/tests/test_financial.py::TestIrr::test_numpy_gh_6744[v0]", "numpy_financial/tests/test_financial.py::TestIrr::test_numpy_gh_6744[v1]", "numpy_financial/tests/test_financial.py::TestIrr::test_gh_15", "numpy_financial/tests/test_financial.py::TestIrr::test_gh_39", "numpy_financial/tests/test_financial.py::TestIrr::test_gh_44" ]
2022-04-16 07:05:32+00:00
4,254
numpy__numpydoc-145
diff --git a/doc/format.rst b/doc/format.rst index 87f5ff7..cdeec0b 100644 --- a/doc/format.rst +++ b/doc/format.rst @@ -252,13 +252,21 @@ The sections of a function's docstring are: Support for the **Yields** section was added in `numpydoc <https://github.com/numpy/numpydoc>`_ version 0.6. -7. **Other Parameters** +7. **Receives** + + Explanation of parameters passed to a generator's ``.send()`` method, + formatted as for Parameters, above. Since, like for Yields and Returns, a + single object is always passed to the method, this may describe either the + single parameter, or positional arguments passed as a tuple. If a docstring + includes Receives it must also include Yields. + +8. **Other Parameters** An optional section used to describe infrequently used parameters. It should only be used if a function has a large number of keyword parameters, to prevent cluttering the **Parameters** section. -8. **Raises** +9. **Raises** An optional section detailing which errors get raised and under what conditions:: @@ -271,16 +279,16 @@ The sections of a function's docstring are: This section should be used judiciously, i.e., only for errors that are non-obvious or have a large chance of getting raised. -9. **Warns** +10. **Warns** An optional section detailing which warnings get raised and under what conditions, formatted similarly to Raises. -10. **Warnings** +11. **Warnings** An optional section with cautions to the user in free text/reST. -11. **See Also** +12. **See Also** An optional section used to refer to related code. This section can be very useful, but should be used judiciously. The goal is to @@ -319,7 +327,7 @@ The sections of a function's docstring are: func_b, func_c_, func_d func_e -12. **Notes** +13. **Notes** An optional section that provides additional information about the code, possibly including a discussion of the algorithm. This @@ -364,7 +372,7 @@ The sections of a function's docstring are: where filename is a path relative to the reference guide source directory. -13. **References** +14. **References** References cited in the **notes** section may be listed here, e.g. if you cited the article below using the text ``[1]_``, @@ -397,7 +405,7 @@ The sections of a function's docstring are: .. highlight:: pycon -14. **Examples** +15. **Examples** An optional section for examples, using the `doctest <http://docs.python.org/library/doctest.html>`_ format. diff --git a/numpydoc/docscrape.py b/numpydoc/docscrape.py index f3453c6..4e3fc4c 100644 --- a/numpydoc/docscrape.py +++ b/numpydoc/docscrape.py @@ -127,6 +127,7 @@ class NumpyDocString(Mapping): 'Parameters': [], 'Returns': [], 'Yields': [], + 'Receives': [], 'Raises': [], 'Warns': [], 'Other Parameters': [], @@ -350,6 +351,9 @@ class NumpyDocString(Mapping): if has_returns and has_yields: msg = 'Docstring contains both a Returns and Yields section.' raise ValueError(msg) + if not has_yields and 'Receives' in section_names: + msg = 'Docstring contains a Receives section but not Yields.' + raise ValueError(msg) for (section, content) in sections: if not section.startswith('..'): @@ -359,8 +363,8 @@ class NumpyDocString(Mapping): self._error_location("The section %s appears twice" % section) - if section in ('Parameters', 'Returns', 'Yields', 'Raises', - 'Warns', 'Other Parameters', 'Attributes', + if section in ('Parameters', 'Returns', 'Yields', 'Receives', + 'Raises', 'Warns', 'Other Parameters', 'Attributes', 'Methods'): self[section] = self._parse_param_list(content) elif section.startswith('.. index::'): @@ -484,7 +488,7 @@ class NumpyDocString(Mapping): out += self._str_signature() out += self._str_summary() out += self._str_extended_summary() - for param_list in ('Parameters', 'Returns', 'Yields', + for param_list in ('Parameters', 'Returns', 'Yields', 'Receives', 'Other Parameters', 'Raises', 'Warns'): out += self._str_param_list(param_list) out += self._str_section('Warnings') diff --git a/numpydoc/docscrape_sphinx.py b/numpydoc/docscrape_sphinx.py index 4cc95d8..9b23235 100644 --- a/numpydoc/docscrape_sphinx.py +++ b/numpydoc/docscrape_sphinx.py @@ -374,6 +374,7 @@ class SphinxDocString(NumpyDocString): 'parameters': self._str_param_list('Parameters'), 'returns': self._str_returns('Returns'), 'yields': self._str_returns('Yields'), + 'receives': self._str_returns('Receives'), 'other_parameters': self._str_param_list('Other Parameters'), 'raises': self._str_param_list('Raises'), 'warns': self._str_param_list('Warns'), diff --git a/numpydoc/numpydoc.py b/numpydoc/numpydoc.py index c8e676f..2544d0f 100644 --- a/numpydoc/numpydoc.py +++ b/numpydoc/numpydoc.py @@ -27,8 +27,9 @@ try: except ImportError: from collections import Callable import hashlib +import itertools -from docutils.nodes import citation, Text, reference +from docutils.nodes import citation, Text, section, comment, reference import sphinx from sphinx.addnodes import pending_xref, desc_content, only @@ -73,18 +74,39 @@ def rename_references(app, what, name, obj, options, lines): sixu('.. [%s]') % new_r) -def _ascend(node, cls): - while node and not isinstance(node, cls): - node = node.parent - return node +def _is_cite_in_numpydoc_docstring(citation_node): + # Find DEDUPLICATION_TAG in comment as last node of sibling section + + # XXX: I failed to use citation_node.traverse to do this: + section_node = citation_node.parent + + def is_docstring_section(node): + return isinstance(node, (section, desc_content)) + + while not is_docstring_section(section_node): + section_node = section_node.parent + if section_node is None: + return False + + sibling_sections = itertools.chain(section_node.traverse(is_docstring_section, + include_self=True, + descend=False, + siblings=True)) + for sibling_section in sibling_sections: + if not sibling_section.children: + continue + last_child = sibling_section.children[-1] + if not isinstance(last_child, comment): + continue + if last_child.rawsource.strip() == DEDUPLICATION_TAG.strip(): + return True + return False def relabel_references(app, doc): # Change 'hash-ref' to 'ref' in label text for citation_node in doc.traverse(citation): - if _ascend(citation_node, desc_content) is None: - # no desc node in ancestry -> not in a docstring - # XXX: should we also somehow check it's in a References section? + if not _is_cite_in_numpydoc_docstring(citation_node): continue label_node = citation_node[0] prefix, _, new_label = label_node[0].astext().partition('-') diff --git a/numpydoc/templates/numpydoc_docstring.rst b/numpydoc/templates/numpydoc_docstring.rst index 1900db5..79ab1f8 100644 --- a/numpydoc/templates/numpydoc_docstring.rst +++ b/numpydoc/templates/numpydoc_docstring.rst @@ -4,6 +4,7 @@ {{parameters}} {{returns}} {{yields}} +{{receives}} {{other_parameters}} {{raises}} {{warns}}
numpy/numpydoc
40b3733b4bf4604ff7622b5eab592edcef750591
diff --git a/numpydoc/tests/test_docscrape.py b/numpydoc/tests/test_docscrape.py index 2085948..a0fb19c 100644 --- a/numpydoc/tests/test_docscrape.py +++ b/numpydoc/tests/test_docscrape.py @@ -150,6 +150,25 @@ int doc_yields = NumpyDocString(doc_yields_txt) +doc_sent_txt = """ +Test generator + +Yields +------ +a : int + The number of apples. + +Receives +-------- +b : int + The number of bananas. +c : int + The number of oranges. + +""" +doc_sent = NumpyDocString(doc_sent_txt) + + def test_signature(): assert doc['Signature'].startswith('numpy.multivariate_normal(') assert doc['Signature'].endswith('spam=None)') @@ -216,6 +235,38 @@ def test_yields(): assert desc[0].endswith(end) +def test_sent(): + section = doc_sent['Receives'] + assert len(section) == 2 + truth = [('b', 'int', 'bananas.'), + ('c', 'int', 'oranges.')] + for (arg, arg_type, desc), (arg_, arg_type_, end) in zip(section, truth): + assert arg == arg_ + assert arg_type == arg_type_ + assert desc[0].startswith('The number of') + assert desc[0].endswith(end) + + +def test_returnyield(): + doc_text = """ +Test having returns and yields. + +Returns +------- +int + The number of apples. + +Yields +------ +a : int + The number of apples. +b : int + The number of bananas. + +""" + assert_raises(ValueError, NumpyDocString, doc_text) + + def test_returnyield(): doc_text = """ Test having returns and yields. @@ -468,6 +519,25 @@ int .. index:: """) +def test_receives_str(): + line_by_line_compare(str(doc_sent), +"""Test generator + +Yields +------ +a : int + The number of apples. + +Receives +-------- +b : int + The number of bananas. +c : int + The number of oranges. + +.. index:: """) + + def test_no_index_in_str(): assert "index" not in str(NumpyDocString("""Test idx
support for coroutine I have a lot of coroutine to comment but i have not seen any suppport for this python feature. The yield allows to comment what goes out of the coroutine but it would be nice to be able to specify what goes in in a specific manner.
0.0
[ "numpydoc/tests/test_docscrape.py::test_sent" ]
[ "numpydoc/tests/test_docscrape.py::test_signature", "numpydoc/tests/test_docscrape.py::test_summary", "numpydoc/tests/test_docscrape.py::test_extended_summary", "numpydoc/tests/test_docscrape.py::test_parameters", "numpydoc/tests/test_docscrape.py::test_other_parameters", "numpydoc/tests/test_docscrape.py::test_returns", "numpydoc/tests/test_docscrape.py::test_yields", "numpydoc/tests/test_docscrape.py::test_returnyield", "numpydoc/tests/test_docscrape.py::test_section_twice", "numpydoc/tests/test_docscrape.py::test_notes", "numpydoc/tests/test_docscrape.py::test_references", "numpydoc/tests/test_docscrape.py::test_examples", "numpydoc/tests/test_docscrape.py::test_index", "numpydoc/tests/test_docscrape.py::test_str", "numpydoc/tests/test_docscrape.py::test_yield_str", "numpydoc/tests/test_docscrape.py::test_receives_str", "numpydoc/tests/test_docscrape.py::test_no_index_in_str", "numpydoc/tests/test_docscrape.py::test_sphinx_str", "numpydoc/tests/test_docscrape.py::test_sphinx_yields_str", "numpydoc/tests/test_docscrape.py::test_parameters_without_extended_description", "numpydoc/tests/test_docscrape.py::test_escape_stars", "numpydoc/tests/test_docscrape.py::test_empty_extended_summary", "numpydoc/tests/test_docscrape.py::test_raises", "numpydoc/tests/test_docscrape.py::test_warns", "numpydoc/tests/test_docscrape.py::test_see_also", "numpydoc/tests/test_docscrape.py::test_see_also_parse_error", "numpydoc/tests/test_docscrape.py::test_see_also_print", "numpydoc/tests/test_docscrape.py::test_unknown_section", "numpydoc/tests/test_docscrape.py::test_empty_first_line", "numpydoc/tests/test_docscrape.py::test_no_summary", "numpydoc/tests/test_docscrape.py::test_unicode", "numpydoc/tests/test_docscrape.py::test_plot_examples", "numpydoc/tests/test_docscrape.py::test_use_blockquotes", "numpydoc/tests/test_docscrape.py::test_class_members", "numpydoc/tests/test_docscrape.py::test_duplicate_signature", "numpydoc/tests/test_docscrape.py::test_class_members_doc", "numpydoc/tests/test_docscrape.py::test_class_members_doc_sphinx", "numpydoc/tests/test_docscrape.py::test_templated_sections", "numpydoc/tests/test_docscrape.py::test_nonstandard_property", "numpydoc/tests/test_docscrape.py::test_args_and_kwargs" ]
2017-11-14 07:48:31+00:00
4,255
numpy__numpydoc-172
diff --git a/doc/format.rst b/doc/format.rst index 87f5ff7..cdeec0b 100644 --- a/doc/format.rst +++ b/doc/format.rst @@ -252,13 +252,21 @@ The sections of a function's docstring are: Support for the **Yields** section was added in `numpydoc <https://github.com/numpy/numpydoc>`_ version 0.6. -7. **Other Parameters** +7. **Receives** + + Explanation of parameters passed to a generator's ``.send()`` method, + formatted as for Parameters, above. Since, like for Yields and Returns, a + single object is always passed to the method, this may describe either the + single parameter, or positional arguments passed as a tuple. If a docstring + includes Receives it must also include Yields. + +8. **Other Parameters** An optional section used to describe infrequently used parameters. It should only be used if a function has a large number of keyword parameters, to prevent cluttering the **Parameters** section. -8. **Raises** +9. **Raises** An optional section detailing which errors get raised and under what conditions:: @@ -271,16 +279,16 @@ The sections of a function's docstring are: This section should be used judiciously, i.e., only for errors that are non-obvious or have a large chance of getting raised. -9. **Warns** +10. **Warns** An optional section detailing which warnings get raised and under what conditions, formatted similarly to Raises. -10. **Warnings** +11. **Warnings** An optional section with cautions to the user in free text/reST. -11. **See Also** +12. **See Also** An optional section used to refer to related code. This section can be very useful, but should be used judiciously. The goal is to @@ -319,7 +327,7 @@ The sections of a function's docstring are: func_b, func_c_, func_d func_e -12. **Notes** +13. **Notes** An optional section that provides additional information about the code, possibly including a discussion of the algorithm. This @@ -364,7 +372,7 @@ The sections of a function's docstring are: where filename is a path relative to the reference guide source directory. -13. **References** +14. **References** References cited in the **notes** section may be listed here, e.g. if you cited the article below using the text ``[1]_``, @@ -397,7 +405,7 @@ The sections of a function's docstring are: .. highlight:: pycon -14. **Examples** +15. **Examples** An optional section for examples, using the `doctest <http://docs.python.org/library/doctest.html>`_ format. diff --git a/numpydoc/docscrape.py b/numpydoc/docscrape.py index f3453c6..02afd88 100644 --- a/numpydoc/docscrape.py +++ b/numpydoc/docscrape.py @@ -16,6 +16,7 @@ except ImportError: import copy import sys +from sphinx.ext.autodoc import ALL def strip_blank_lines(l): "Remove leading and trailing blank lines from a list of lines" @@ -127,6 +128,7 @@ class NumpyDocString(Mapping): 'Parameters': [], 'Returns': [], 'Yields': [], + 'Receives': [], 'Raises': [], 'Warns': [], 'Other Parameters': [], @@ -236,9 +238,41 @@ class NumpyDocString(Mapping): return params - _name_rgx = re.compile(r"^\s*(:(?P<role>\w+):" - r"`(?P<name>(?:~\w+\.)?[a-zA-Z0-9_.-]+)`|" - r" (?P<name2>[a-zA-Z0-9_.-]+))\s*", re.X) + # See also supports the following formats. + # + # <FUNCNAME> + # <FUNCNAME> SPACE* COLON SPACE+ <DESC> SPACE* + # <FUNCNAME> ( COMMA SPACE+ <FUNCNAME>)* SPACE* + # <FUNCNAME> ( COMMA SPACE+ <FUNCNAME>)* SPACE* COLON SPACE+ <DESC> SPACE* + + # <FUNCNAME> is one of + # <PLAIN_FUNCNAME> + # COLON <ROLE> COLON BACKTICK <PLAIN_FUNCNAME> BACKTICK + # where + # <PLAIN_FUNCNAME> is a legal function name, and + # <ROLE> is any nonempty sequence of word characters. + # Examples: func_f1 :meth:`func_h1` :obj:`~baz.obj_r` :class:`class_j` + # <DESC> is a string describing the function. + + _role = r":(?P<role>\w+):" + _funcbacktick = r"`(?P<name>(?:~\w+\.)?[a-zA-Z0-9_.-]+)`" + _funcplain = r"(?P<name2>[a-zA-Z0-9_.-]+)" + _funcname = r"(" + _role + _funcbacktick + r"|" + _funcplain + r")" + _funcnamenext = _funcname.replace('role', 'rolenext') + _funcnamenext = _funcnamenext.replace('name', 'namenext') + _description = r"(?P<description>\s*:(\s+(?P<desc>\S+.*))?)?\s*$" + _func_rgx = re.compile(r"^\s*" + _funcname + r"\s*") + _line_rgx = re.compile( + r"^\s*" + + r"(?P<allfuncs>" + # group for all function names + _funcname + + r"(?P<morefuncs>([,]\s+" + _funcnamenext + r")*)" + + r")" + # end of "allfuncs" + r"(?P<trailing>\s*,)?" + # Some function lists have a trailing comma + _description) + + # Empty <DESC> elements are replaced with '..' + empty_description = '..' def _parse_see_also(self, content): """ @@ -248,52 +282,49 @@ class NumpyDocString(Mapping): func_name1, func_name2, :meth:`func_name`, func_name3 """ + items = [] def parse_item_name(text): - """Match ':role:`name`' or 'name'""" - m = self._name_rgx.match(text) - if m: - g = m.groups() - if g[1] is None: - return g[3], None - else: - return g[2], g[1] - raise ParseError("%s is not a item name" % text) + """Match ':role:`name`' or 'name'.""" + m = self._func_rgx.match(text) + if not m: + raise ParseError("%s is not a item name" % text) + role = m.group('role') + name = m.group('name') if role else m.group('name2') + return name, role, m.end() - def push_item(name, rest): - if not name: - return - name, role = parse_item_name(name) - items.append((name, list(rest), role)) - del rest[:] - - current_func = None rest = [] - for line in content: if not line.strip(): continue - m = self._name_rgx.match(line) - if m and line[m.end():].strip().startswith(':'): - push_item(current_func, rest) - current_func, line = line[:m.end()], line[m.end():] - rest = [line.split(':', 1)[1].strip()] - if not rest[0]: - rest = [] - elif not line.startswith(' '): - push_item(current_func, rest) - current_func = None - if ',' in line: - for func in line.split(','): - if func.strip(): - push_item(func, []) - elif line.strip(): - current_func = line - elif current_func is not None: + line_match = self._line_rgx.match(line) + description = None + if line_match: + description = line_match.group('desc') + if line_match.group('trailing'): + self._error_location( + 'Unexpected comma after function list at index %d of ' + 'line "%s"' % (line_match.end('trailing'), line), + error=False) + if not description and line.startswith(' '): rest.append(line.strip()) - push_item(current_func, rest) + elif line_match: + funcs = [] + text = line_match.group('allfuncs') + while True: + if not text.strip(): + break + name, role, match_end = parse_item_name(text) + funcs.append((name, role)) + text = text[match_end:].strip() + if text and text[0] == ',': + text = text[1:].strip() + rest = list(filter(None, [description])) + items.append((funcs, rest)) + else: + raise ParseError("%s is not a item name" % line) return items def _parse_index(self, section, content): @@ -350,6 +381,9 @@ class NumpyDocString(Mapping): if has_returns and has_yields: msg = 'Docstring contains both a Returns and Yields section.' raise ValueError(msg) + if not has_yields and 'Receives' in section_names: + msg = 'Docstring contains a Receives section but not Yields.' + raise ValueError(msg) for (section, content) in sections: if not section.startswith('..'): @@ -359,8 +393,8 @@ class NumpyDocString(Mapping): self._error_location("The section %s appears twice" % section) - if section in ('Parameters', 'Returns', 'Yields', 'Raises', - 'Warns', 'Other Parameters', 'Attributes', + if section in ('Parameters', 'Returns', 'Yields', 'Receives', + 'Raises', 'Warns', 'Other Parameters', 'Attributes', 'Methods'): self[section] = self._parse_param_list(content) elif section.startswith('.. index::'): @@ -440,24 +474,30 @@ class NumpyDocString(Mapping): return [] out = [] out += self._str_header("See Also") + out += [''] last_had_desc = True - for func, desc, role in self['See Also']: - if role: - link = ':%s:`%s`' % (role, func) - elif func_role: - link = ':%s:`%s`' % (func_role, func) - else: - link = "`%s`_" % func - if desc or last_had_desc: - out += [''] - out += [link] - else: - out[-1] += ", %s" % link + for funcs, desc in self['See Also']: + assert isinstance(funcs, list) + links = [] + for func, role in funcs: + if role: + link = ':%s:`%s`' % (role, func) + elif func_role: + link = ':%s:`%s`' % (func_role, func) + else: + link = "`%s`_" % func + links.append(link) + link = ', '.join(links) + out += [link] if desc: out += self._str_indent([' '.join(desc)]) last_had_desc = True else: last_had_desc = False + out += self._str_indent([self.empty_description]) + + if last_had_desc: + out += [''] out += [''] return out @@ -484,7 +524,7 @@ class NumpyDocString(Mapping): out += self._str_signature() out += self._str_summary() out += self._str_extended_summary() - for param_list in ('Parameters', 'Returns', 'Yields', + for param_list in ('Parameters', 'Returns', 'Yields', 'Receives', 'Other Parameters', 'Raises', 'Warns'): out += self._str_param_list(param_list) out += self._str_section('Warnings') @@ -593,18 +633,25 @@ class ClassDoc(NumpyDocString): NumpyDocString.__init__(self, doc) - if config.get('show_class_members', True): + _members = config.get('members', []) + if _members is ALL: + _members = None + _exclude = config.get('exclude-members', []) + + if config.get('show_class_members', True) and _exclude is not ALL: def splitlines_x(s): if not s: return [] else: return s.splitlines() - for field, items in [('Methods', self.methods), ('Attributes', self.properties)]: if not self[field]: doc_list = [] for name in sorted(items): + if (name in _exclude or + (_members and name not in _members)): + continue try: doc_item = pydoc.getdoc(getattr(self._cls, name)) doc_list.append( diff --git a/numpydoc/docscrape_sphinx.py b/numpydoc/docscrape_sphinx.py index 4cc95d8..9b23235 100644 --- a/numpydoc/docscrape_sphinx.py +++ b/numpydoc/docscrape_sphinx.py @@ -374,6 +374,7 @@ class SphinxDocString(NumpyDocString): 'parameters': self._str_param_list('Parameters'), 'returns': self._str_returns('Returns'), 'yields': self._str_returns('Yields'), + 'receives': self._str_returns('Receives'), 'other_parameters': self._str_param_list('Other Parameters'), 'raises': self._str_param_list('Raises'), 'warns': self._str_param_list('Warns'), diff --git a/numpydoc/numpydoc.py b/numpydoc/numpydoc.py index c8e676f..e25241d 100644 --- a/numpydoc/numpydoc.py +++ b/numpydoc/numpydoc.py @@ -27,8 +27,9 @@ try: except ImportError: from collections import Callable import hashlib +import itertools -from docutils.nodes import citation, Text, reference +from docutils.nodes import citation, Text, section, comment, reference import sphinx from sphinx.addnodes import pending_xref, desc_content, only @@ -73,18 +74,39 @@ def rename_references(app, what, name, obj, options, lines): sixu('.. [%s]') % new_r) -def _ascend(node, cls): - while node and not isinstance(node, cls): - node = node.parent - return node +def _is_cite_in_numpydoc_docstring(citation_node): + # Find DEDUPLICATION_TAG in comment as last node of sibling section + + # XXX: I failed to use citation_node.traverse to do this: + section_node = citation_node.parent + + def is_docstring_section(node): + return isinstance(node, (section, desc_content)) + + while not is_docstring_section(section_node): + section_node = section_node.parent + if section_node is None: + return False + + sibling_sections = itertools.chain(section_node.traverse(is_docstring_section, + include_self=True, + descend=False, + siblings=True)) + for sibling_section in sibling_sections: + if not sibling_section.children: + continue + last_child = sibling_section.children[-1] + if not isinstance(last_child, comment): + continue + if last_child.rawsource.strip() == DEDUPLICATION_TAG.strip(): + return True + return False def relabel_references(app, doc): # Change 'hash-ref' to 'ref' in label text for citation_node in doc.traverse(citation): - if _ascend(citation_node, desc_content) is None: - # no desc node in ancestry -> not in a docstring - # XXX: should we also somehow check it's in a References section? + if not _is_cite_in_numpydoc_docstring(citation_node): continue label_node = citation_node[0] prefix, _, new_label = label_node[0].astext().partition('-') @@ -132,6 +154,7 @@ def mangle_docstrings(app, what, name, obj, options, lines): app.config.numpydoc_show_inherited_class_members, 'class_members_toctree': app.config.numpydoc_class_members_toctree} + cfg.update(options or {}) u_NL = sixu('\n') if what == 'module': # Strip top title @@ -177,7 +200,7 @@ def mangle_signature(app, what, name, obj, options, sig, retann): if not hasattr(obj, '__doc__'): return - doc = get_doc_object(obj) + doc = get_doc_object(obj, config={'show_class_members': False}) sig = doc['Signature'] or getattr(obj, '__text_signature__', None) if sig: sig = re.sub(sixu("^[^(]*"), sixu(""), sig) diff --git a/numpydoc/templates/numpydoc_docstring.rst b/numpydoc/templates/numpydoc_docstring.rst index 1900db5..79ab1f8 100644 --- a/numpydoc/templates/numpydoc_docstring.rst +++ b/numpydoc/templates/numpydoc_docstring.rst @@ -4,6 +4,7 @@ {{parameters}} {{returns}} {{yields}} +{{receives}} {{other_parameters}} {{raises}} {{warns}}
numpy/numpydoc
40b3733b4bf4604ff7622b5eab592edcef750591
diff --git a/numpydoc/tests/test_docscrape.py b/numpydoc/tests/test_docscrape.py index 2085948..b4b7e03 100644 --- a/numpydoc/tests/test_docscrape.py +++ b/numpydoc/tests/test_docscrape.py @@ -150,6 +150,25 @@ int doc_yields = NumpyDocString(doc_yields_txt) +doc_sent_txt = """ +Test generator + +Yields +------ +a : int + The number of apples. + +Receives +-------- +b : int + The number of bananas. +c : int + The number of oranges. + +""" +doc_sent = NumpyDocString(doc_sent_txt) + + def test_signature(): assert doc['Signature'].startswith('numpy.multivariate_normal(') assert doc['Signature'].endswith('spam=None)') @@ -216,6 +235,38 @@ def test_yields(): assert desc[0].endswith(end) +def test_sent(): + section = doc_sent['Receives'] + assert len(section) == 2 + truth = [('b', 'int', 'bananas.'), + ('c', 'int', 'oranges.')] + for (arg, arg_type, desc), (arg_, arg_type_, end) in zip(section, truth): + assert arg == arg_ + assert arg_type == arg_type_ + assert desc[0].startswith('The number of') + assert desc[0].endswith(end) + + +def test_returnyield(): + doc_text = """ +Test having returns and yields. + +Returns +------- +int + The number of apples. + +Yields +------ +a : int + The number of apples. +b : int + The number of bananas. + +""" + assert_raises(ValueError, NumpyDocString, doc_text) + + def test_returnyield(): doc_text = """ Test having returns and yields. @@ -335,7 +386,7 @@ def line_by_line_compare(a, b): b = textwrap.dedent(b) a = [l.rstrip() for l in _strip_blank_lines(a).split('\n')] b = [l.rstrip() for l in _strip_blank_lines(b).split('\n')] - assert all(x == y for x, y in zip(a, b)) + assert all(x == y for x, y in zip(a, b)), str([[x, y] for x, y in zip(a, b) if x != y]) def test_str(): @@ -403,7 +454,7 @@ See Also -------- `some`_, `other`_, `funcs`_ - + .. `otherfunc`_ relationship @@ -468,6 +519,25 @@ int .. index:: """) +def test_receives_str(): + line_by_line_compare(str(doc_sent), +"""Test generator + +Yields +------ +a : int + The number of apples. + +Receives +-------- +b : int + The number of bananas. +c : int + The number of oranges. + +.. index:: """) + + def test_no_index_in_str(): assert "index" not in str(NumpyDocString("""Test idx @@ -553,7 +623,7 @@ of the one-dimensional normal distribution to higher dimensions. .. seealso:: :obj:`some`, :obj:`other`, :obj:`funcs` - + .. :obj:`otherfunc` relationship @@ -709,36 +779,46 @@ def test_see_also(): multiple lines func_f, func_g, :meth:`func_h`, func_j, func_k + func_f1, func_g1, :meth:`func_h1`, func_j1 + func_f2, func_g2, :meth:`func_h2`, func_j2 : description of multiple :obj:`baz.obj_q` :obj:`~baz.obj_r` :class:`class_j`: fubar foobar """) - assert len(doc6['See Also']) == 13 - for func, desc, role in doc6['See Also']: - if func in ('func_a', 'func_b', 'func_c', 'func_f', - 'func_g', 'func_h', 'func_j', 'func_k', 'baz.obj_q', - '~baz.obj_r'): - assert(not desc) - else: - assert(desc) - - if func == 'func_h': - assert role == 'meth' - elif func == 'baz.obj_q' or func == '~baz.obj_r': - assert role == 'obj' - elif func == 'class_j': - assert role == 'class' - else: - assert role is None + assert len(doc6['See Also']) == 10 + for funcs, desc in doc6['See Also']: + for func, role in funcs: + if func in ('func_a', 'func_b', 'func_c', 'func_f', + 'func_g', 'func_h', 'func_j', 'func_k', 'baz.obj_q', + 'func_f1', 'func_g1', 'func_h1', 'func_j1', + '~baz.obj_r'): + assert not desc, str([func, desc]) + elif func in ('func_f2', 'func_g2', 'func_h2', 'func_j2'): + assert desc, str([func, desc]) + else: + assert desc, str([func, desc]) + + if func == 'func_h': + assert role == 'meth' + elif func == 'baz.obj_q' or func == '~baz.obj_r': + assert role == 'obj' + elif func == 'class_j': + assert role == 'class' + elif func in ['func_h1', 'func_h2']: + assert role == 'meth' + else: + assert role is None, str([func, role]) - if func == 'func_d': - assert desc == ['some equivalent func'] - elif func == 'foo.func_e': - assert desc == ['some other func over', 'multiple lines'] - elif func == 'class_j': - assert desc == ['fubar', 'foobar'] + if func == 'func_d': + assert desc == ['some equivalent func'] + elif func == 'foo.func_e': + assert desc == ['some other func over', 'multiple lines'] + elif func == 'class_j': + assert desc == ['fubar', 'foobar'] + elif func in ['func_f2', 'func_g2', 'func_h2', 'func_j2']: + assert desc == ['description of multiple'], str([desc, ['description of multiple']]) def test_see_also_parse_error(): @@ -796,11 +876,13 @@ This should be ignored and warned about pass with warnings.catch_warnings(record=True) as w: + warnings.filterwarnings('always', '', UserWarning) NumpyDocString(doc_text) assert len(w) == 1 assert "Unknown section Mope" == str(w[0].message) with warnings.catch_warnings(record=True) as w: + warnings.filterwarnings('always', '', UserWarning) SphinxClassDoc(BadSection) assert len(w) == 1 assert('test_docscrape.test_unknown_section.<locals>.BadSection' @@ -1267,6 +1349,24 @@ def test_args_and_kwargs(): Keyword arguments """) +def test_autoclass(): + cfg=dict(show_class_members=True, + show_inherited_class_members=True) + doc = SphinxClassDoc(str, ''' +A top section before + +.. autoclass:: str + ''', config=cfg) + line_by_line_compare(str(doc), r''' +A top section before + +.. autoclass:: str + +.. rubric:: Methods + + + ''') + if __name__ == "__main__": import pytest diff --git a/numpydoc/tests/test_numpydoc.py b/numpydoc/tests/test_numpydoc.py new file mode 100644 index 0000000..3a0bd12 --- /dev/null +++ b/numpydoc/tests/test_numpydoc.py @@ -0,0 +1,56 @@ +# -*- encoding:utf-8 -*- +from __future__ import division, absolute_import, print_function + +from numpydoc.numpydoc import mangle_docstrings +from sphinx.ext.autodoc import ALL + +class MockConfig(): + numpydoc_use_plots = False + numpydoc_use_blockquotes = True + numpydoc_show_class_members = True + numpydoc_show_inherited_class_members = True + numpydoc_class_members_toctree = True + templates_path = [] + numpydoc_edit_link = False + numpydoc_citation_re = '[a-z0-9_.-]+' + +class MockBuilder(): + config = MockConfig() + +class MockApp(): + config = MockConfig() + builder = MockBuilder() + translator = None + + +app = MockApp() +app.builder.app = app + +def test_mangle_docstrings(): + s =''' +A top section before + +.. autoclass:: str + ''' + lines = s.split('\n') + doc = mangle_docstrings(MockApp(), 'class', 'str', str, {}, lines) + assert 'rpartition' in [x.strip() for x in lines] + + lines = s.split('\n') + doc = mangle_docstrings(MockApp(), 'class', 'str', str, {'members': ['upper']}, lines) + assert 'rpartition' not in [x.strip() for x in lines] + assert 'upper' in [x.strip() for x in lines] + + lines = s.split('\n') + doc = mangle_docstrings(MockApp(), 'class', 'str', str, {'exclude-members': ALL}, lines) + assert 'rpartition' not in [x.strip() for x in lines] + assert 'upper' not in [x.strip() for x in lines] + + lines = s.split('\n') + doc = mangle_docstrings(MockApp(), 'class', 'str', str, + {'exclude-members': ['upper']}, lines) + assert 'rpartition' in [x.strip() for x in lines] + assert 'upper' not in [x.strip() for x in lines] + +if __name__ == "__main__": + import pytest
multiple entries in a See Also section Observed in scipy.interpolate docs ``` See Also ------------ splev, splrep : FITPACK wrappers ``` The description text (the stuff after the colon) does not show up in the generated html docs. Moving the description to a separate line, ``` See Also ------------ splev, splrep FITPACK wrappers ``` does not help either
0.0
[ "numpydoc/tests/test_docscrape.py::test_sent", "numpydoc/tests/test_docscrape.py::test_str", "numpydoc/tests/test_docscrape.py::test_sphinx_str", "numpydoc/tests/test_docscrape.py::test_see_also", "numpydoc/tests/test_numpydoc.py::test_mangle_docstrings" ]
[ "numpydoc/tests/test_docscrape.py::test_signature", "numpydoc/tests/test_docscrape.py::test_summary", "numpydoc/tests/test_docscrape.py::test_extended_summary", "numpydoc/tests/test_docscrape.py::test_parameters", "numpydoc/tests/test_docscrape.py::test_other_parameters", "numpydoc/tests/test_docscrape.py::test_returns", "numpydoc/tests/test_docscrape.py::test_yields", "numpydoc/tests/test_docscrape.py::test_returnyield", "numpydoc/tests/test_docscrape.py::test_section_twice", "numpydoc/tests/test_docscrape.py::test_notes", "numpydoc/tests/test_docscrape.py::test_references", "numpydoc/tests/test_docscrape.py::test_examples", "numpydoc/tests/test_docscrape.py::test_index", "numpydoc/tests/test_docscrape.py::test_yield_str", "numpydoc/tests/test_docscrape.py::test_receives_str", "numpydoc/tests/test_docscrape.py::test_no_index_in_str", "numpydoc/tests/test_docscrape.py::test_sphinx_yields_str", "numpydoc/tests/test_docscrape.py::test_parameters_without_extended_description", "numpydoc/tests/test_docscrape.py::test_escape_stars", "numpydoc/tests/test_docscrape.py::test_empty_extended_summary", "numpydoc/tests/test_docscrape.py::test_raises", "numpydoc/tests/test_docscrape.py::test_warns", "numpydoc/tests/test_docscrape.py::test_see_also_parse_error", "numpydoc/tests/test_docscrape.py::test_see_also_print", "numpydoc/tests/test_docscrape.py::test_unknown_section", "numpydoc/tests/test_docscrape.py::test_empty_first_line", "numpydoc/tests/test_docscrape.py::test_no_summary", "numpydoc/tests/test_docscrape.py::test_unicode", "numpydoc/tests/test_docscrape.py::test_plot_examples", "numpydoc/tests/test_docscrape.py::test_use_blockquotes", "numpydoc/tests/test_docscrape.py::test_class_members", "numpydoc/tests/test_docscrape.py::test_duplicate_signature", "numpydoc/tests/test_docscrape.py::test_class_members_doc", "numpydoc/tests/test_docscrape.py::test_class_members_doc_sphinx", "numpydoc/tests/test_docscrape.py::test_templated_sections", "numpydoc/tests/test_docscrape.py::test_nonstandard_property", "numpydoc/tests/test_docscrape.py::test_args_and_kwargs", "numpydoc/tests/test_docscrape.py::test_autoclass" ]
2018-04-12 22:31:17+00:00
4,256
numpy__numpydoc-175
diff --git a/numpydoc/docscrape.py b/numpydoc/docscrape.py index 02afd88..32245a9 100644 --- a/numpydoc/docscrape.py +++ b/numpydoc/docscrape.py @@ -220,7 +220,7 @@ class NumpyDocString(Mapping): else: yield name, self._strip(data[2:]) - def _parse_param_list(self, content): + def _parse_param_list(self, content, single_element_is_type=False): r = Reader(content) params = [] while not r.eof(): @@ -228,7 +228,10 @@ class NumpyDocString(Mapping): if ' : ' in header: arg_name, arg_type = header.split(' : ')[:2] else: - arg_name, arg_type = header, '' + if single_element_is_type: + arg_name, arg_type = '', header + else: + arg_name, arg_type = header, '' desc = r.read_to_next_unindented_line() desc = dedent_lines(desc) @@ -393,10 +396,12 @@ class NumpyDocString(Mapping): self._error_location("The section %s appears twice" % section) - if section in ('Parameters', 'Returns', 'Yields', 'Receives', - 'Raises', 'Warns', 'Other Parameters', 'Attributes', + if section in ('Parameters', 'Other Parameters', 'Attributes', 'Methods'): self[section] = self._parse_param_list(content) + elif section in ('Returns', 'Yields', 'Raises', 'Warns', 'Receives'): + self[section] = self._parse_param_list( + content, single_element_is_type=True) elif section.startswith('.. index::'): self['index'] = self._parse_index(section, content) elif section == 'See Also': @@ -452,10 +457,12 @@ class NumpyDocString(Mapping): if self[name]: out += self._str_header(name) for param in self[name]: + parts = [] + if param.name: + parts.append(param.name) if param.type: - out += ['%s : %s' % (param.name, param.type)] - else: - out += [param.name] + parts.append(param.type) + out += [' : '.join(parts)] if param.desc and ''.join(param.desc).strip(): out += self._str_indent(param.desc) out += [''] @@ -637,7 +644,7 @@ class ClassDoc(NumpyDocString): if _members is ALL: _members = None _exclude = config.get('exclude-members', []) - + if config.get('show_class_members', True) and _exclude is not ALL: def splitlines_x(s): if not s: @@ -649,7 +656,7 @@ class ClassDoc(NumpyDocString): if not self[field]: doc_list = [] for name in sorted(items): - if (name in _exclude or + if (name in _exclude or (_members and name not in _members)): continue try: diff --git a/numpydoc/docscrape_sphinx.py b/numpydoc/docscrape_sphinx.py index 9b23235..aad64c7 100644 --- a/numpydoc/docscrape_sphinx.py +++ b/numpydoc/docscrape_sphinx.py @@ -70,19 +70,19 @@ class SphinxDocString(NumpyDocString): return self['Extended Summary'] + [''] def _str_returns(self, name='Returns'): - typed_fmt = '**%s** : %s' - untyped_fmt = '**%s**' + named_fmt = '**%s** : %s' + unnamed_fmt = '%s' out = [] if self[name]: out += self._str_field_list(name) out += [''] for param in self[name]: - if param.type: - out += self._str_indent([typed_fmt % (param.name.strip(), + if param.name: + out += self._str_indent([named_fmt % (param.name.strip(), param.type)]) else: - out += self._str_indent([untyped_fmt % param.name.strip()]) + out += self._str_indent([unnamed_fmt % param.type.strip()]) if not param.desc: out += self._str_indent(['..'], 8) else: @@ -209,12 +209,13 @@ class SphinxDocString(NumpyDocString): display_param, desc = self._process_param(param.name, param.desc, fake_autosummary) - + parts = [] + if display_param: + parts.append(display_param) if param.type: - out += self._str_indent(['%s : %s' % (display_param, - param.type)]) - else: - out += self._str_indent([display_param]) + parts.append(param.type) + out += self._str_indent([' : '.join(parts)]) + if desc and self.use_blockquotes: out += [''] elif not desc: @@ -376,8 +377,8 @@ class SphinxDocString(NumpyDocString): 'yields': self._str_returns('Yields'), 'receives': self._str_returns('Receives'), 'other_parameters': self._str_param_list('Other Parameters'), - 'raises': self._str_param_list('Raises'), - 'warns': self._str_param_list('Warns'), + 'raises': self._str_returns('Raises'), + 'warns': self._str_returns('Warns'), 'warnings': self._str_warnings(), 'see_also': self._str_see_also(func_role), 'notes': self._str_section('Notes'),
numpy/numpydoc
8f1ac50a7267e9e1ee66141fd71561c2ca2dc713
diff --git a/numpydoc/tests/test_docscrape.py b/numpydoc/tests/test_docscrape.py index b4b7e03..e5e3f1f 100644 --- a/numpydoc/tests/test_docscrape.py +++ b/numpydoc/tests/test_docscrape.py @@ -211,14 +211,14 @@ def test_returns(): assert desc[-1].endswith('distribution.') arg, arg_type, desc = doc['Returns'][1] - assert arg == 'list of str' - assert arg_type == '' + assert arg == '' + assert arg_type == 'list of str' assert desc[0].startswith('This is not a real') assert desc[-1].endswith('anonymous return values.') arg, arg_type, desc = doc['Returns'][2] - assert arg == 'no_description' - assert arg_type == '' + assert arg == '' + assert arg_type == 'no_description' assert not ''.join(desc).strip() @@ -227,7 +227,7 @@ def test_yields(): assert len(section) == 3 truth = [('a', 'int', 'apples.'), ('b', 'int', 'bananas.'), - ('int', '', 'unknowns.')] + ('', 'int', 'unknowns.')] for (arg, arg_type, desc), (arg_, arg_type_, end) in zip(section, truth): assert arg == arg_ assert arg_type == arg_type_ @@ -594,11 +594,11 @@ of the one-dimensional normal distribution to higher dimensions. In other words, each entry ``out[i,j,...,:]`` is an N-dimensional value drawn from the distribution. - **list of str** + list of str This is not a real return value. It exists to test anonymous return values. - **no_description** + no_description .. :Other Parameters: @@ -608,12 +608,12 @@ of the one-dimensional normal distribution to higher dimensions. :Raises: - **RuntimeError** + RuntimeError Some error :Warns: - **RuntimeWarning** + RuntimeWarning Some warning .. warning:: @@ -687,7 +687,7 @@ def test_sphinx_yields_str(): **b** : int The number of bananas. - **int** + int The number of unknowns. """) @@ -754,16 +754,18 @@ doc5 = NumpyDocString( def test_raises(): assert len(doc5['Raises']) == 1 - name, _, desc = doc5['Raises'][0] - assert name == 'LinAlgException' - assert desc == ['If array is singular.'] + param = doc5['Raises'][0] + assert param.name == '' + assert param.type == 'LinAlgException' + assert param.desc == ['If array is singular.'] def test_warns(): assert len(doc5['Warns']) == 1 - name, _, desc = doc5['Warns'][0] - assert name == 'SomeWarning' - assert desc == ['If needed'] + param = doc5['Warns'][0] + assert param.name == '' + assert param.type == 'SomeWarning' + assert param.desc == ['If needed'] def test_see_also(): @@ -995,7 +997,7 @@ def test_use_blockquotes(): GHI - **JKL** + JKL MNO ''')
Anonymous return values have their types populated in the name slot of the tuple. I noticed an inconsistency, when using numpydoc version 0.6.0 in python2.7 on Ubuntu. The parsed return section information returns different styles of tuple depending on if the return value is anoymous or not. Here is a minimal working example: ```python def mwe(): from numpydoc.docscrape import NumpyDocString docstr = ( 'Returns\n' '----------\n' 'int\n' ' can return an anoymous integer\n' 'out : ndarray\n' ' can return a named value\n' ) doc = NumpyDocString(docstr) returns = doc._parsed_data['Returns'] print(returns) ``` This results in ```python [(u'int', '', [u'can return an anoymous integer']), (u'out', u'ndarray', [u'can return a named value'])] ``` However judging by tests (due to lack of docs), I believe it was indented that each value in the returns list should be a tuple of `(arg, arg_type, arg_desc)`. Therefore we should see this instead: ```python [('', u'int', [u'can return an anoymous integer']), (u'out', u'ndarray', [u'can return a named value'])] ``` My current workaround is this: ```python for p_name, p_type, p_descr in returns: if not p_type: p_name = '' p_type = p_name ```
0.0
[ "numpydoc/tests/test_docscrape.py::test_returns", "numpydoc/tests/test_docscrape.py::test_yields", "numpydoc/tests/test_docscrape.py::test_sphinx_str", "numpydoc/tests/test_docscrape.py::test_sphinx_yields_str", "numpydoc/tests/test_docscrape.py::test_raises", "numpydoc/tests/test_docscrape.py::test_warns", "numpydoc/tests/test_docscrape.py::test_use_blockquotes" ]
[ "numpydoc/tests/test_docscrape.py::test_signature", "numpydoc/tests/test_docscrape.py::test_summary", "numpydoc/tests/test_docscrape.py::test_extended_summary", "numpydoc/tests/test_docscrape.py::test_parameters", "numpydoc/tests/test_docscrape.py::test_other_parameters", "numpydoc/tests/test_docscrape.py::test_sent", "numpydoc/tests/test_docscrape.py::test_returnyield", "numpydoc/tests/test_docscrape.py::test_section_twice", "numpydoc/tests/test_docscrape.py::test_notes", "numpydoc/tests/test_docscrape.py::test_references", "numpydoc/tests/test_docscrape.py::test_examples", "numpydoc/tests/test_docscrape.py::test_index", "numpydoc/tests/test_docscrape.py::test_str", "numpydoc/tests/test_docscrape.py::test_yield_str", "numpydoc/tests/test_docscrape.py::test_receives_str", "numpydoc/tests/test_docscrape.py::test_no_index_in_str", "numpydoc/tests/test_docscrape.py::test_parameters_without_extended_description", "numpydoc/tests/test_docscrape.py::test_escape_stars", "numpydoc/tests/test_docscrape.py::test_empty_extended_summary", "numpydoc/tests/test_docscrape.py::test_see_also", "numpydoc/tests/test_docscrape.py::test_see_also_parse_error", "numpydoc/tests/test_docscrape.py::test_see_also_print", "numpydoc/tests/test_docscrape.py::test_unknown_section", "numpydoc/tests/test_docscrape.py::test_empty_first_line", "numpydoc/tests/test_docscrape.py::test_no_summary", "numpydoc/tests/test_docscrape.py::test_unicode", "numpydoc/tests/test_docscrape.py::test_plot_examples", "numpydoc/tests/test_docscrape.py::test_class_members", "numpydoc/tests/test_docscrape.py::test_duplicate_signature", "numpydoc/tests/test_docscrape.py::test_class_members_doc", "numpydoc/tests/test_docscrape.py::test_class_members_doc_sphinx", "numpydoc/tests/test_docscrape.py::test_templated_sections", "numpydoc/tests/test_docscrape.py::test_nonstandard_property", "numpydoc/tests/test_docscrape.py::test_args_and_kwargs", "numpydoc/tests/test_docscrape.py::test_autoclass" ]
2018-05-02 22:37:28+00:00
4,257
numpy__numpydoc-269
diff --git a/doc/release_notes.rst b/doc/release_notes.rst index 25c6b63..a324bd1 100644 --- a/doc/release_notes.rst +++ b/doc/release_notes.rst @@ -71,3 +71,21 @@ Additional notes - https://github.com/numpy/numpydoc/issues/215#issuecomment-568261611 - https://github.com/readthedocs/sphinx_rtd_theme/pull/838 + +1.1.0 +----- + +Fixed bugs +~~~~~~~~~~ + +- BUG: Defer to autodoc for signatures `#221 <https://github.com/numpy/numpydoc/pull/221>`__ (`thequackdaddy <https://github.com/thequackdaddy>`__) + +Closed issues +~~~~~~~~~~~~~ + +- self included in list of params for method `#220 <https://github.com/numpy/numpydoc/issues/220>`__ + +Additional notes +~~~~~~~~~~~~~~~~ + +- Due to merging of `#221 <https://github.com/numpy/numpydoc/pull/221>`__, self and cls no longer will appear in method signatures. diff --git a/numpydoc/docscrape.py b/numpydoc/docscrape.py index ad0d99c..807e9bc 100644 --- a/numpydoc/docscrape.py +++ b/numpydoc/docscrape.py @@ -566,23 +566,6 @@ class FunctionDoc(NumpyDocString): doc = inspect.getdoc(func) or '' NumpyDocString.__init__(self, doc, config) - if not self['Signature'] and func is not None: - func, func_name = self.get_func() - try: - try: - signature = str(inspect.signature(func)) - except (AttributeError, ValueError): - # try to read signature, backward compat for older Python - if sys.version_info[0] >= 3: - argspec = inspect.getfullargspec(func) - else: - argspec = inspect.getargspec(func) - signature = inspect.formatargspec(*argspec) - signature = '%s%s' % (func_name, signature) - except TypeError: - signature = '%s()' % func_name - self['Signature'] = signature - def get_func(self): func_name = getattr(self._f, '__name__', self.__class__.__name__) if inspect.isclass(self._f): diff --git a/numpydoc/numpydoc.py b/numpydoc/numpydoc.py index 652eedc..93cd975 100644 --- a/numpydoc/numpydoc.py +++ b/numpydoc/numpydoc.py @@ -28,6 +28,7 @@ from docutils.nodes import citation, Text, section, comment, reference import sphinx from sphinx.addnodes import pending_xref, desc_content from sphinx.util import logging +from sphinx.errors import ExtensionError if sphinx.__version__ < '1.6.5': raise RuntimeError("Sphinx 1.6.5 or newer is required") @@ -203,12 +204,25 @@ def mangle_signature(app, what, name, obj, options, sig, retann): if not hasattr(obj, '__doc__'): return doc = get_doc_object(obj, config={'show_class_members': False}) - sig = doc['Signature'] or getattr(obj, '__text_signature__', None) + sig = (doc['Signature'] + or _clean_text_signature(getattr(obj, '__text_signature__', None))) if sig: sig = re.sub("^[^(]*", "", sig) return sig, '' +def _clean_text_signature(sig): + if sig is None: + return None + start_pattern = re.compile(r"^[^(]*\(") + start, end = start_pattern.search(sig).span() + start_sig = sig[start:end] + sig = sig[end:-1] + sig = re.sub(r'^\$(self|module|type)(,\s|$)','' , sig, count=1) + sig = re.sub(r'(^|(?<=,\s))/,\s\*', '*', sig, count=1) + return start_sig + sig + ')' + + def setup(app, get_doc_object_=get_doc_object): if not hasattr(app, 'add_config_value'): return # probably called by nose, better bail out @@ -218,7 +232,13 @@ def setup(app, get_doc_object_=get_doc_object): app.setup_extension('sphinx.ext.autosummary') - app.connect('builder-inited', update_config) + # Once we bump our Sphinx requirement higher (1.7 or 1.8?) + # we can just connect to config-inited + try: + app.connect('config-inited', update_config) + except ExtensionError: + app.connect('builder-inited', update_config) + app.connect('autodoc-process-docstring', mangle_docstrings) app.connect('autodoc-process-signature', mangle_signature) app.connect('doctree-read', relabel_references) @@ -244,17 +264,19 @@ def setup(app, get_doc_object_=get_doc_object): return metadata -def update_config(app): +def update_config(app, config=None): """Update the configuration with default values.""" + if config is None: # needed for testing and old Sphinx + config = app.config # Do not simply overwrite the `app.config.numpydoc_xref_aliases` # otherwise the next sphinx-build will compare the incoming values (without # our additions) to the old values (with our additions) and trigger # a full rebuild! - numpydoc_xref_aliases_complete = deepcopy(app.config.numpydoc_xref_aliases) + numpydoc_xref_aliases_complete = deepcopy(config.numpydoc_xref_aliases) for key, value in DEFAULT_LINKS.items(): if key not in numpydoc_xref_aliases_complete: numpydoc_xref_aliases_complete[key] = value - app.config.numpydoc_xref_aliases_complete = numpydoc_xref_aliases_complete + config.numpydoc_xref_aliases_complete = numpydoc_xref_aliases_complete # ------------------------------------------------------------------------------
numpy/numpydoc
24006306e1e7dd120bf4ff2a43bb3f4853fdddd3
diff --git a/numpydoc/tests/test_docscrape.py b/numpydoc/tests/test_docscrape.py index 1780ec4..2fb1fbd 100644 --- a/numpydoc/tests/test_docscrape.py +++ b/numpydoc/tests/test_docscrape.py @@ -699,7 +699,7 @@ def test_escape_stars(): pass fdoc = FunctionDoc(func=my_func) - assert fdoc['Signature'] == 'my_func(a, b, **kwargs)' + assert fdoc['Signature'] == '' doc4 = NumpyDocString( diff --git a/numpydoc/tests/test_full.py b/numpydoc/tests/test_full.py index b727cde..775036a 100644 --- a/numpydoc/tests/test_full.py +++ b/numpydoc/tests/test_full.py @@ -53,12 +53,13 @@ def test_MyClass(sphinx_app): html = fid.read() # ensure that no autodoc weirdness ($) occurs assert '$self' not in html + assert '/,' not in html assert '__init__' in html # inherited # escaped * chars should no longer be preceded by \'s, # if we see a \* in the output we know it's incorrect: assert r'\*' not in html # "self" should not be in the parameter list for the class: - assert 'self,' in html # XXX should be "not in", bug! + assert 'self,' not in html # check xref was embedded properly (dict should link using xref): assert 'stdtypes.html#dict' in html diff --git a/numpydoc/tests/test_numpydoc.py b/numpydoc/tests/test_numpydoc.py index 383ca18..77e7540 100644 --- a/numpydoc/tests/test_numpydoc.py +++ b/numpydoc/tests/test_numpydoc.py @@ -1,6 +1,6 @@ # -*- encoding:utf-8 -*- from copy import deepcopy -from numpydoc.numpydoc import mangle_docstrings +from numpydoc.numpydoc import mangle_docstrings, _clean_text_signature from numpydoc.xref import DEFAULT_LINKS from sphinx.ext.autodoc import ALL @@ -36,7 +36,7 @@ app.builder.app = app def test_mangle_docstrings(): - s =''' + s = ''' A top section before .. autoclass:: str @@ -64,6 +64,34 @@ A top section before assert 'upper' not in [x.strip() for x in lines] +def test_clean_text_signature(): + assert _clean_text_signature(None) is None + assert _clean_text_signature('func($self)') == 'func()' + assert (_clean_text_signature('func($self, *args, **kwargs)') + == 'func(*args, **kwargs)') + assert _clean_text_signature('($self)') == '()' + assert _clean_text_signature('()') == '()' + assert _clean_text_signature('func()') == 'func()' + assert (_clean_text_signature('func($self, /, *args, **kwargs)') + == 'func(*args, **kwargs)') + assert (_clean_text_signature('func($self, other, /, *args, **kwargs)') + == 'func(other, *args, **kwargs)') + assert _clean_text_signature('($module)') == '()' + assert _clean_text_signature('func($type)') == 'func()' + assert (_clean_text_signature('func($self, foo="hello world")') + == 'func(foo="hello world")') + assert (_clean_text_signature("func($self, foo='hello world')") + == "func(foo='hello world')") + assert (_clean_text_signature('func(foo="hello world")') + == 'func(foo="hello world")') + assert (_clean_text_signature('func(foo="$self")') + == 'func(foo="$self")') + assert (_clean_text_signature('func($self, foo="$self")') + == 'func(foo="$self")') + assert _clean_text_signature('func(self, other)') == 'func(self, other)' + assert _clean_text_signature('func($self, *args)') == 'func(*args)' + + if __name__ == "__main__": import pytest pytest.main()
"Handler <function mangle_docstrings at 0x7f64b5ba57b8> for event 'autodoc-process-docstring' threw an exception" We're starting to see this with the upgrade from 0.9.2 to 1.0 For example: https://github.com/yeatmanlab/pyAFQ/pull/270/checks?check_run_id=800934528#step:6:61 See also: https://github.com/yeatmanlab/pyAFQ/pull/271 Do we need to change something on our end?
0.0
[ "numpydoc/tests/test_docscrape.py::test_signature", "numpydoc/tests/test_docscrape.py::test_summary", "numpydoc/tests/test_docscrape.py::test_extended_summary", "numpydoc/tests/test_docscrape.py::test_parameters", "numpydoc/tests/test_docscrape.py::test_other_parameters", "numpydoc/tests/test_docscrape.py::test_returns", "numpydoc/tests/test_docscrape.py::test_yields", "numpydoc/tests/test_docscrape.py::test_sent", "numpydoc/tests/test_docscrape.py::test_returnyield", "numpydoc/tests/test_docscrape.py::test_section_twice", "numpydoc/tests/test_docscrape.py::test_notes", "numpydoc/tests/test_docscrape.py::test_references", "numpydoc/tests/test_docscrape.py::test_examples", "numpydoc/tests/test_docscrape.py::test_index", "numpydoc/tests/test_docscrape.py::test_str", "numpydoc/tests/test_docscrape.py::test_yield_str", "numpydoc/tests/test_docscrape.py::test_receives_str", "numpydoc/tests/test_docscrape.py::test_no_index_in_str", "numpydoc/tests/test_docscrape.py::test_sphinx_str", "numpydoc/tests/test_docscrape.py::test_sphinx_yields_str", "numpydoc/tests/test_docscrape.py::test_parameters_without_extended_description", "numpydoc/tests/test_docscrape.py::test_escape_stars", "numpydoc/tests/test_docscrape.py::test_empty_extended_summary", "numpydoc/tests/test_docscrape.py::test_raises", "numpydoc/tests/test_docscrape.py::test_warns", "numpydoc/tests/test_docscrape.py::test_see_also", "numpydoc/tests/test_docscrape.py::test_see_also_parse_error", "numpydoc/tests/test_docscrape.py::test_see_also_print", "numpydoc/tests/test_docscrape.py::test_see_also_trailing_comma_warning", "numpydoc/tests/test_docscrape.py::test_unknown_section", "numpydoc/tests/test_docscrape.py::test_empty_first_line", "numpydoc/tests/test_docscrape.py::test_no_summary", "numpydoc/tests/test_docscrape.py::test_unicode", "numpydoc/tests/test_docscrape.py::test_plot_examples", "numpydoc/tests/test_docscrape.py::test_use_blockquotes", "numpydoc/tests/test_docscrape.py::test_class_members", "numpydoc/tests/test_docscrape.py::test_duplicate_signature", "numpydoc/tests/test_docscrape.py::test_class_members_doc", "numpydoc/tests/test_docscrape.py::test_class_members_doc_sphinx", "numpydoc/tests/test_docscrape.py::test_class_attributes_as_member_list", "numpydoc/tests/test_docscrape.py::test_templated_sections", "numpydoc/tests/test_docscrape.py::test_nonstandard_property", "numpydoc/tests/test_docscrape.py::test_args_and_kwargs", "numpydoc/tests/test_docscrape.py::test_autoclass", "numpydoc/tests/test_docscrape.py::test_xref", "numpydoc/tests/test_full.py::test_MyClass", "numpydoc/tests/test_full.py::test_my_function", "numpydoc/tests/test_numpydoc.py::test_mangle_docstrings", "numpydoc/tests/test_numpydoc.py::test_clean_text_signature" ]
[]
2020-06-25 19:11:40+00:00
4,258
numpy__numpydoc-283
diff --git a/numpydoc/docscrape.py b/numpydoc/docscrape.py index 77de401..d79992c 100644 --- a/numpydoc/docscrape.py +++ b/numpydoc/docscrape.py @@ -284,6 +284,8 @@ class NumpyDocString(Mapping): """ + content = dedent_lines(content) + items = [] def parse_item_name(text):
numpy/numpydoc
fd17df0c96e107f7550b91e2680e76d2be796e0c
diff --git a/numpydoc/tests/test_docscrape.py b/numpydoc/tests/test_docscrape.py index 8b29704..2ab0218 100644 --- a/numpydoc/tests/test_docscrape.py +++ b/numpydoc/tests/test_docscrape.py @@ -17,6 +17,7 @@ from numpydoc.docscrape import ( ) from numpydoc.docscrape_sphinx import (SphinxDocString, SphinxClassDoc, SphinxFunctionDoc, get_doc_object) +import pytest from pytest import raises as assert_raises from pytest import warns as assert_warns @@ -766,11 +767,16 @@ def test_warns(): assert param.type == 'SomeWarning' assert param.desc == ['If needed'] - -def test_see_also(): +# see numpydoc/numpydoc #281 +# we want to correctly parse "See Also" both in docstrings both like +#"""foo +# and +#""" +#foo [email protected]('prefix', ['', '\n ']) +def test_see_also(prefix): doc6 = NumpyDocString( - """ - z(x,theta) + prefix + """z(x,theta) See Also --------
Failed See Also Parsing. ``` In [1]: from numpydoc.docscrape import NumpyDocString ...: from numpy import seterrobj ...: NumpyDocString("""seterrobj(errobj) ...: ...: Set the object that defines floating-point error handling. ...: ...: See Also ...: -------- ...: geterrobj, seterr, geterr, seterrcall, geterrcall ...: getbufsize, setbufsize""")['See Also'] Out[1]: [] In [2]: ``` ``` diff --git a/numpydoc/docscrape.py b/numpydoc/docscrape.py index 77de401..d79992c 100644 --- a/numpydoc/docscrape.py +++ b/numpydoc/docscrape.py @@ -284,6 +284,8 @@ class NumpyDocString(Mapping): """ + content = dedent_lines(content) items = [] def parse_item_name(text): ``` Might be enough, but it may also be the wrong place to put that: ``` In [1]: from numpydoc.docscrape import NumpyDocString ...: from numpy import seterrobj ...: NumpyDocString("""seterrobj(errobj) ...: ...: Set the object that defines floating-point error handling. ...: ...: See Also ...: -------- ...: geterrobj, seterr, geterr, seterrcall, geterrcall ...: getbufsize, setbufsize""")['See Also'] Out[1]: [([('geterrobj', None), ('seterr', None), ('geterr', None), ('seterrcall', None), ('geterrcall', None)], []), ([('getbufsize', None), ('setbufsize', None)], [])] ```
0.0
[ "numpydoc/tests/test_docscrape.py::test_see_also[]" ]
[ "numpydoc/tests/test_docscrape.py::test_signature", "numpydoc/tests/test_docscrape.py::test_summary", "numpydoc/tests/test_docscrape.py::test_extended_summary", "numpydoc/tests/test_docscrape.py::test_parameters", "numpydoc/tests/test_docscrape.py::test_other_parameters", "numpydoc/tests/test_docscrape.py::test_returns", "numpydoc/tests/test_docscrape.py::test_yields", "numpydoc/tests/test_docscrape.py::test_sent", "numpydoc/tests/test_docscrape.py::test_returnyield", "numpydoc/tests/test_docscrape.py::test_section_twice", "numpydoc/tests/test_docscrape.py::test_notes", "numpydoc/tests/test_docscrape.py::test_references", "numpydoc/tests/test_docscrape.py::test_examples", "numpydoc/tests/test_docscrape.py::test_index", "numpydoc/tests/test_docscrape.py::test_str", "numpydoc/tests/test_docscrape.py::test_yield_str", "numpydoc/tests/test_docscrape.py::test_receives_str", "numpydoc/tests/test_docscrape.py::test_no_index_in_str", "numpydoc/tests/test_docscrape.py::test_sphinx_str", "numpydoc/tests/test_docscrape.py::test_sphinx_yields_str", "numpydoc/tests/test_docscrape.py::test_parameters_without_extended_description", "numpydoc/tests/test_docscrape.py::test_escape_stars", "numpydoc/tests/test_docscrape.py::test_empty_extended_summary", "numpydoc/tests/test_docscrape.py::test_raises", "numpydoc/tests/test_docscrape.py::test_warns", "numpydoc/tests/test_docscrape.py::test_see_also[\\n", "numpydoc/tests/test_docscrape.py::test_see_also_parse_error", "numpydoc/tests/test_docscrape.py::test_see_also_print", "numpydoc/tests/test_docscrape.py::test_see_also_trailing_comma_warning", "numpydoc/tests/test_docscrape.py::test_unknown_section", "numpydoc/tests/test_docscrape.py::test_empty_first_line", "numpydoc/tests/test_docscrape.py::test_no_summary", "numpydoc/tests/test_docscrape.py::test_unicode", "numpydoc/tests/test_docscrape.py::test_plot_examples", "numpydoc/tests/test_docscrape.py::test_use_blockquotes", "numpydoc/tests/test_docscrape.py::test_class_members", "numpydoc/tests/test_docscrape.py::test_duplicate_signature", "numpydoc/tests/test_docscrape.py::test_class_members_doc", "numpydoc/tests/test_docscrape.py::test_class_members_doc_sphinx", "numpydoc/tests/test_docscrape.py::test_class_attributes_as_member_list", "numpydoc/tests/test_docscrape.py::test_templated_sections", "numpydoc/tests/test_docscrape.py::test_nonstandard_property", "numpydoc/tests/test_docscrape.py::test_args_and_kwargs", "numpydoc/tests/test_docscrape.py::test_autoclass", "numpydoc/tests/test_docscrape.py::test_xref" ]
2020-07-15 16:30:40+00:00
4,259
numpy__numpydoc-286
diff --git a/doc/install.rst b/doc/install.rst index ba799e3..46b26f8 100644 --- a/doc/install.rst +++ b/doc/install.rst @@ -63,15 +63,6 @@ numpydoc_xref_aliases : dict aliases/shortcuts used when specifying the types of parameters. The keys should not have any spaces. Together with the ``intersphinx`` extension, you can map to links in any documentation. - The default is an empty ``dict``. - - If you have the following ``intersphinx`` namespace configuration:: - - intersphinx_mapping = { - 'python': ('https://docs.python.org/3/', None), - 'numpy': ('https://docs.scipy.org/doc/numpy', None), - ... - } The default ``numpydoc_xref_aliases`` will supply some common ``Python`` standard library and ``NumPy`` names for you. Then for your module, a useful diff --git a/numpydoc/docscrape.py b/numpydoc/docscrape.py index d79992c..2b992d8 100644 --- a/numpydoc/docscrape.py +++ b/numpydoc/docscrape.py @@ -219,12 +219,14 @@ class NumpyDocString(Mapping): yield name, self._strip(data[2:]) def _parse_param_list(self, content, single_element_is_type=False): + content = dedent_lines(content) r = Reader(content) params = [] while not r.eof(): header = r.read().strip() - if ' : ' in header: - arg_name, arg_type = header.split(' : ', maxsplit=1) + if ' :' in header: + arg_name, arg_type = header.split(' :', maxsplit=1) + arg_name, arg_type = arg_name.strip(), arg_type.strip() else: if single_element_is_type: arg_name, arg_type = '', header diff --git a/numpydoc/xref.py b/numpydoc/xref.py index a4ceaf9..7c6612e 100644 --- a/numpydoc/xref.py +++ b/numpydoc/xref.py @@ -95,7 +95,9 @@ DEFAULT_LINKS = { def make_xref(param_type, xref_aliases, xref_ignore): - """Enclose str in a :obj: role. + """Parse and apply appropriate sphinx role(s) to `param_type`. + + The :obj: role is the default. Parameters ---------- @@ -110,7 +112,7 @@ def make_xref(param_type, xref_aliases, xref_ignore): Returns ------- out : str - Text with parts that may be wrapped in a + Text with fully-qualified names and terms that may be wrapped in a ``:obj:`` role. """ if param_type in xref_aliases:
numpy/numpydoc
4e86e815a855502eef1a796a5d3f217b08aaa79f
diff --git a/numpydoc/tests/test_docscrape.py b/numpydoc/tests/test_docscrape.py index 2ab0218..a0b6d2e 100644 --- a/numpydoc/tests/test_docscrape.py +++ b/numpydoc/tests/test_docscrape.py @@ -133,7 +133,11 @@ doc_txt = '''\ :refguide: random;distributions, random;gauss ''' -doc = NumpyDocString(doc_txt) + [email protected](params=['','\n '], ids=["flush", "newline_indented"]) +def doc(request): + return NumpyDocString(request.param+doc_txt) + doc_yields_txt = """ Test generator @@ -169,21 +173,21 @@ c : int doc_sent = NumpyDocString(doc_sent_txt) -def test_signature(): +def test_signature(doc): assert doc['Signature'].startswith('numpy.multivariate_normal(') assert doc['Signature'].endswith('spam=None)') -def test_summary(): +def test_summary(doc): assert doc['Summary'][0].startswith('Draw values') assert doc['Summary'][-1].endswith('covariance.') -def test_extended_summary(): +def test_extended_summary(doc): assert doc['Extended Summary'][0].startswith('The multivariate normal') -def test_parameters(): +def test_parameters(doc): assert len(doc['Parameters']) == 4 names = [n for n, _, _ in doc['Parameters']] assert all(a == b for a, b in zip(names, ['mean', 'cov', 'shape'])) @@ -205,7 +209,7 @@ def test_parameters(): assert desc[0].startswith('The type and size') -def test_other_parameters(): +def test_other_parameters(doc): assert len(doc['Other Parameters']) == 1 assert [n for n, _, _ in doc['Other Parameters']] == ['spam'] arg, arg_type, desc = doc['Other Parameters'][0] @@ -213,7 +217,8 @@ def test_other_parameters(): assert desc[0].startswith('A parrot off its mortal coil') -def test_returns(): + +def test_returns(doc): assert len(doc['Returns']) == 3 arg, arg_type, desc = doc['Returns'][0] assert arg == 'out' @@ -342,23 +347,23 @@ That should break... or 'function dummy_func' in str(e)) -def test_notes(): +def test_notes(doc): assert doc['Notes'][0].startswith('Instead') assert doc['Notes'][-1].endswith('definite.') assert len(doc['Notes']) == 17 -def test_references(): +def test_references(doc): assert doc['References'][0].startswith('..') assert doc['References'][-1].endswith('2001.') -def test_examples(): +def test_examples(doc): assert doc['Examples'][0].startswith('>>>') assert doc['Examples'][-1].endswith('True]') -def test_index(): +def test_index(doc): assert doc['index']['default'] == 'random' assert len(doc['index']) == 2 assert len(doc['index']['refguide']) == 2 @@ -382,7 +387,7 @@ def line_by_line_compare(a, b, n_lines=None): assert aa == bb -def test_str(): +def test_str(doc): # doc_txt has the order of Notes and See Also sections flipped. # This should be handled automatically, and so, one thing this test does # is to make sure that See Also precedes Notes in the output. @@ -921,6 +926,21 @@ doc7 = NumpyDocString(""" def test_empty_first_line(): assert doc7['Summary'][0].startswith('Doc starts') +doc8 = NumpyDocString(""" + + Parameters with colon and no types: + + Parameters + ---------- + + data : + some stuff, technically invalid + """) + + +def test_trailing_colon(): + assert doc8['Parameters'][0].name == 'data' + def test_no_summary(): str(SphinxDocString(""" diff --git a/numpydoc/tests/test_xref.py b/numpydoc/tests/test_xref.py index 31dfacd..5d16919 100644 --- a/numpydoc/tests/test_xref.py +++ b/numpydoc/tests/test_xref.py @@ -1,25 +1,15 @@ # -*- encoding:utf-8 -*- import pytest -from numpydoc.xref import make_xref - -xref_aliases = { - # python - 'sequence': ':term:`python:sequence`', - 'iterable': ':term:`python:iterable`', - 'string': 'str', - # numpy - 'array': 'numpy.ndarray', - 'dtype': 'numpy.dtype', - 'ndarray': 'numpy.ndarray', - 'matrix': 'numpy.matrix', - 'array-like': ':term:`numpy:array_like`', - 'array_like': ':term:`numpy:array_like`', -} +from numpydoc.xref import make_xref, DEFAULT_LINKS + +# Use the default numpydoc link mapping +xref_aliases = DEFAULT_LINKS + # Comes mainly from numpy data = r""" (...) array_like, float, optional -(...) :term:`numpy:array_like`, :obj:`float`, optional +(...) :term:`numpy:array_like`, :class:`python:float`, optional (2,) ndarray (2,) :obj:`ndarray <numpy.ndarray>` @@ -31,37 +21,37 @@ data = r""" (..., :obj:`M`, :obj:`N`) :term:`numpy:array_like` (float, float), optional -(:obj:`float`, :obj:`float`), optional +(:class:`python:float`, :class:`python:float`), optional 1-D array or sequence 1-D :obj:`array <numpy.ndarray>` or :term:`python:sequence` array of str or unicode-like -:obj:`array <numpy.ndarray>` of :obj:`str` or unicode-like +:obj:`array <numpy.ndarray>` of :class:`python:str` or unicode-like array_like of float -:term:`numpy:array_like` of :obj:`float` +:term:`numpy:array_like` of :class:`python:float` bool or callable -:obj:`bool` or :obj:`callable` +:ref:`bool <python:bltin-boolean-values>` or :func:`python:callable` int in [0, 255] -:obj:`int` in [0, 255] +:class:`python:int` in [0, 255] int or None, optional -:obj:`int` or :obj:`None`, optional +:class:`python:int` or :data:`python:None`, optional list of str or array_like -:obj:`list` of :obj:`str` or :term:`numpy:array_like` +:class:`python:list` of :class:`python:str` or :term:`numpy:array_like` sequence of array_like :term:`python:sequence` of :term:`numpy:array_like` str or pathlib.Path -:obj:`str` or :obj:`pathlib.Path` +:class:`python:str` or :obj:`pathlib.Path` {'', string}, optional -{'', :obj:`string <str>`}, optional +{'', :class:`python:str`}, optional {'C', 'F', 'A', or 'K'}, optional {'C', 'F', 'A', or 'K'}, optional @@ -70,16 +60,16 @@ str or pathlib.Path {'linear', 'lower', 'higher', 'midpoint', 'nearest'} {False, True, 'greedy', 'optimal'} -{:obj:`False`, :obj:`True`, 'greedy', 'optimal'} +{:data:`python:False`, :data:`python:True`, 'greedy', 'optimal'} {{'begin', 1}, {'end', 0}}, {string, int} -{{'begin', 1}, {'end', 0}}, {:obj:`string <str>`, :obj:`int`} +{{'begin', 1}, {'end', 0}}, {:class:`python:str`, :class:`python:int`} callable f'(x,*args) -:obj:`callable` f'(x,*args) +:func:`python:callable` f'(x,*args) callable ``fhess(x, *args)``, optional -:obj:`callable` ``fhess(x, *args)``, optional +:func:`python:callable` ``fhess(x, *args)``, optional spmatrix (format: ``csr``, ``bsr``, ``dia`` or coo``) :obj:`spmatrix` (format: ``csr``, ``bsr``, ``dia`` or coo``) @@ -88,28 +78,28 @@ spmatrix (format: ``csr``, ``bsr``, ``dia`` or coo``) :ref:`strftime <strftime-strptime-behavior>` callable or :ref:`strftime <strftime-strptime-behavior>` -:obj:`callable` or :ref:`strftime <strftime-strptime-behavior>` +:func:`python:callable` or :ref:`strftime <strftime-strptime-behavior>` callable or :ref:`strftime behavior <strftime-strptime-behavior>` -:obj:`callable` or :ref:`strftime behavior <strftime-strptime-behavior>` +:func:`python:callable` or :ref:`strftime behavior <strftime-strptime-behavior>` list(int) -:obj:`list`\(:obj:`int`) +:class:`python:list`\(:class:`python:int`) list[int] -:obj:`list`\[:obj:`int`] +:class:`python:list`\[:class:`python:int`] dict(str, int) -:obj:`dict`\(:obj:`str`, :obj:`int`) +:class:`python:dict`\(:class:`python:str`, :class:`python:int`) dict[str, int] -:obj:`dict`\[:obj:`str`, :obj:`int`] +:class:`python:dict`\[:class:`python:str`, :class:`python:int`] tuple(float, float) -:obj:`tuple`\(:obj:`float`, :obj:`float`) +:class:`python:tuple`\(:class:`python:float`, :class:`python:float`) dict[tuple(str, str), int] -:obj:`dict`\[:obj:`tuple`\(:obj:`str`, :obj:`str`), :obj:`int`] +:class:`python:dict`\[:class:`python:tuple`\(:class:`python:str`, :class:`python:str`), :class:`python:int`] """ # noqa: E501 xref_ignore = {'or', 'in', 'of', 'default', 'optional'}
Wrong number of Parameter for numpy array. ``` In [1]: from numpydoc.docscrape import NumpyDocString ...: from numpy import array ...: len(NumpyDocString(array.__doc__)['Parameters']) Out[1]: 1 ``` (should be 6) Again due to a dedent issue: ``` $ git diff diff --git a/numpydoc/docscrape.py b/numpydoc/docscrape.py index d79992c..3db20fe 100644 --- a/numpydoc/docscrape.py +++ b/numpydoc/docscrape.py @@ -219,6 +219,7 @@ class NumpyDocString(Mapping): yield name, self._strip(data[2:]) def _parse_param_list(self, content, single_element_is_type=False): + content = dedent_lines(content) r = Reader(content) params = [] while not r.eof(): ``` Fixes it. Not quite sure why it is not found in tests...
0.0
[ "numpydoc/tests/test_docscrape.py::test_trailing_colon" ]
[ "numpydoc/tests/test_docscrape.py::test_signature[flush]", "numpydoc/tests/test_docscrape.py::test_signature[newline_indented]", "numpydoc/tests/test_docscrape.py::test_summary[flush]", "numpydoc/tests/test_docscrape.py::test_summary[newline_indented]", "numpydoc/tests/test_docscrape.py::test_extended_summary[flush]", "numpydoc/tests/test_docscrape.py::test_extended_summary[newline_indented]", "numpydoc/tests/test_docscrape.py::test_parameters[flush]", "numpydoc/tests/test_docscrape.py::test_parameters[newline_indented]", "numpydoc/tests/test_docscrape.py::test_other_parameters[flush]", "numpydoc/tests/test_docscrape.py::test_other_parameters[newline_indented]", "numpydoc/tests/test_docscrape.py::test_returns[flush]", "numpydoc/tests/test_docscrape.py::test_returns[newline_indented]", "numpydoc/tests/test_docscrape.py::test_yields", "numpydoc/tests/test_docscrape.py::test_sent", "numpydoc/tests/test_docscrape.py::test_returnyield", "numpydoc/tests/test_docscrape.py::test_section_twice", "numpydoc/tests/test_docscrape.py::test_notes[flush]", "numpydoc/tests/test_docscrape.py::test_notes[newline_indented]", "numpydoc/tests/test_docscrape.py::test_references[flush]", "numpydoc/tests/test_docscrape.py::test_references[newline_indented]", "numpydoc/tests/test_docscrape.py::test_examples[flush]", "numpydoc/tests/test_docscrape.py::test_examples[newline_indented]", "numpydoc/tests/test_docscrape.py::test_index[flush]", "numpydoc/tests/test_docscrape.py::test_index[newline_indented]", "numpydoc/tests/test_docscrape.py::test_str[flush]", "numpydoc/tests/test_docscrape.py::test_str[newline_indented]", "numpydoc/tests/test_docscrape.py::test_yield_str", "numpydoc/tests/test_docscrape.py::test_receives_str", "numpydoc/tests/test_docscrape.py::test_no_index_in_str", "numpydoc/tests/test_docscrape.py::test_sphinx_str", "numpydoc/tests/test_docscrape.py::test_sphinx_yields_str", "numpydoc/tests/test_docscrape.py::test_parameters_without_extended_description", "numpydoc/tests/test_docscrape.py::test_escape_stars", "numpydoc/tests/test_docscrape.py::test_empty_extended_summary", "numpydoc/tests/test_docscrape.py::test_raises", "numpydoc/tests/test_docscrape.py::test_warns", "numpydoc/tests/test_docscrape.py::test_see_also[]", "numpydoc/tests/test_docscrape.py::test_see_also[\\n", "numpydoc/tests/test_docscrape.py::test_see_also_parse_error", "numpydoc/tests/test_docscrape.py::test_see_also_print", "numpydoc/tests/test_docscrape.py::test_see_also_trailing_comma_warning", "numpydoc/tests/test_docscrape.py::test_unknown_section", "numpydoc/tests/test_docscrape.py::test_empty_first_line", "numpydoc/tests/test_docscrape.py::test_no_summary", "numpydoc/tests/test_docscrape.py::test_unicode", "numpydoc/tests/test_docscrape.py::test_plot_examples", "numpydoc/tests/test_docscrape.py::test_use_blockquotes", "numpydoc/tests/test_docscrape.py::test_class_members", "numpydoc/tests/test_docscrape.py::test_duplicate_signature", "numpydoc/tests/test_docscrape.py::test_class_members_doc", "numpydoc/tests/test_docscrape.py::test_class_members_doc_sphinx", "numpydoc/tests/test_docscrape.py::test_class_attributes_as_member_list", "numpydoc/tests/test_docscrape.py::test_templated_sections", "numpydoc/tests/test_docscrape.py::test_nonstandard_property", "numpydoc/tests/test_docscrape.py::test_args_and_kwargs", "numpydoc/tests/test_docscrape.py::test_autoclass", "numpydoc/tests/test_docscrape.py::test_xref", "numpydoc/tests/test_xref.py::test_make_xref[(...)", "numpydoc/tests/test_xref.py::test_make_xref[(2,)", "numpydoc/tests/test_xref.py::test_make_xref[(...,M,N)", "numpydoc/tests/test_xref.py::test_make_xref[(...,", "numpydoc/tests/test_xref.py::test_make_xref[(float,", "numpydoc/tests/test_xref.py::test_make_xref[1-D", "numpydoc/tests/test_xref.py::test_make_xref[array", "numpydoc/tests/test_xref.py::test_make_xref[array_like", "numpydoc/tests/test_xref.py::test_make_xref[bool", "numpydoc/tests/test_xref.py::test_make_xref[int", "numpydoc/tests/test_xref.py::test_make_xref[list", "numpydoc/tests/test_xref.py::test_make_xref[sequence", "numpydoc/tests/test_xref.py::test_make_xref[str", "numpydoc/tests/test_xref.py::test_make_xref[{'',", "numpydoc/tests/test_xref.py::test_make_xref[{'C',", "numpydoc/tests/test_xref.py::test_make_xref[{'linear',", "numpydoc/tests/test_xref.py::test_make_xref[{False,", "numpydoc/tests/test_xref.py::test_make_xref[{{'begin',", "numpydoc/tests/test_xref.py::test_make_xref[callable", "numpydoc/tests/test_xref.py::test_make_xref[spmatrix", "numpydoc/tests/test_xref.py::test_make_xref[:ref:`strftime", "numpydoc/tests/test_xref.py::test_make_xref[list(int)-:class:`python:list`\\\\(:class:`python:int`)]", "numpydoc/tests/test_xref.py::test_make_xref[list[int]-:class:`python:list`\\\\[:class:`python:int`]]", "numpydoc/tests/test_xref.py::test_make_xref[dict(str,", "numpydoc/tests/test_xref.py::test_make_xref[dict[str,", "numpydoc/tests/test_xref.py::test_make_xref[tuple(float,", "numpydoc/tests/test_xref.py::test_make_xref[dict[tuple(str," ]
2020-07-18 01:24:40+00:00
4,260
numpy__numpydoc-347
diff --git a/numpydoc/validate.py b/numpydoc/validate.py index 91aca6b..3675737 100644 --- a/numpydoc/validate.py +++ b/numpydoc/validate.py @@ -564,6 +564,10 @@ def validate(obj_name): else: if doc.parameter_type(param)[-1] == ".": errs.append(error("PR05", param_name=param)) + # skip common_type_error checks when the param type is a set of + # options + if "{" in doc.parameter_type(param): + continue common_type_errors = [ ("integer", "int"), ("boolean", "bool"),
numpy/numpydoc
4ae1e00e72e522c126403c1814f0b99dc5978622
diff --git a/numpydoc/tests/test_validate.py b/numpydoc/tests/test_validate.py index ecbe703..60cebcd 100644 --- a/numpydoc/tests/test_validate.py +++ b/numpydoc/tests/test_validate.py @@ -458,6 +458,28 @@ class GoodDocStrings: """ pass + def valid_options_in_parameter_description_sets(self, bar): + """ + Ensure a PR06 error is not raised when type is member of a set. + + Literal keywords like 'integer' are valid when specified in a set of + valid options for a keyword parameter. + + Parameters + ---------- + bar : {'integer', 'boolean'} + The literal values of 'integer' and 'boolean' are part of an + options set and thus should not be subject to PR06 warnings. + + See Also + -------- + related : Something related. + + Examples + -------- + >>> result = 1 + 1 + """ + class BadGenericDocStrings: """Everything here has a bad docstring @@ -1089,6 +1111,7 @@ class TestValidator: "multiple_variables_on_one_line", "other_parameters", "warnings", + "valid_options_in_parameter_description_sets", ], ) def test_good_functions(self, capsys, func):
How to specify that parameter can equal the string 'integer'? Say I have the following: ```python def foo(bar: str) -> None: """ Parameters ---------- bar : {'integer', 'float'} Some description. """ if bar not in {'integer', 'float'}: raise ValueError('bar is neither "integer" nor "float"') ``` The parameter `bar` is a `str`, and can only take on the values `'integer'` and `'float'`. However, if I run `numpydoc` on it, it reports: ```console $ python -m numpydoc t.foo --validate t.foo:SS01:No summary found (a short summary in a single line should be present at the beginning of the docstring) t.foo:ES01:No extended summary found t.foo:PR06:Parameter "bar" type should use "int" instead of "integer" t.foo:SA01:See Also section not found t.foo:EX01:No examples section found ``` The first 2 and last 2 errors are expected, but the middle one (`PR06`) feels like a false positive. Noticed when trying to validate `pandas.to_numeric` (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_numeric.html), which has a parameter `downcast` which can be equal to the string `'integer'`
0.0
[ "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[valid_options_in_parameter_description_sets]" ]
[ "numpydoc/tests/test_validate.py::test_validate.BadExamples.indentation_is_not_a_multiple_of_four", "numpydoc/tests/test_validate.py::test_validate.BadExamples.missing_whitespace_after_comma", "numpydoc/tests/test_validate.py::test_validate.BadExamples.missing_whitespace_around_arithmetic_operator", "numpydoc/tests/test_validate.py::test_validate.BadGenericDocStrings.sections_in_wrong_order", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.contains", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.empty_returns", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.good_imports", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.head", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.head1", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.mode", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.multiple_variables_on_one_line", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.no_returns", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.other_parameters", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.plot", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.random_letters", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.sample", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.sample_values", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.summary_starts_with_number", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.swap", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.valid_options_in_parameter_description_sets", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.warnings", "numpydoc/tests/test_validate.py::TestValidator::test_one_liner", "numpydoc/tests/test_validate.py::TestValidator::test_good_class", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[plot]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[swap]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[sample]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[random_letters]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[sample_values]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[head]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[head1]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[summary_starts_with_number]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[contains]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[mode]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[good_imports]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[no_returns]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[empty_returns]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[multiple_variables_on_one_line]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[other_parameters]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[warnings]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_class", "numpydoc/tests/test_validate.py::TestValidator::test_bad_generic_functions[func]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_generic_functions[astype]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_generic_functions[astype1]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_generic_functions[astype2]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_generic_functions[astype3]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_generic_functions[plot]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_generic_functions[directives_without_two_colons]", "numpydoc/tests/test_validate.py::TestValidatorClass::test_raises_for_invalid_module_name[unknown_mod]", "numpydoc/tests/test_validate.py::TestValidatorClass::test_raises_for_invalid_module_name[unknown_mod.MyClass]", "numpydoc/tests/test_validate.py::TestValidatorClass::test_raises_for_invalid_attribute_name[datetime.BadClassName]", "numpydoc/tests/test_validate.py::TestValidatorClass::test_raises_for_invalid_attribute_name[datetime.bad_method_name]" ]
2022-01-06 20:36:11+00:00
4,261
numpy__numpydoc-422
diff --git a/doc/install.rst b/doc/install.rst index a0bc076..976ddd5 100644 --- a/doc/install.rst +++ b/doc/install.rst @@ -48,10 +48,6 @@ numpydoc_citation_re : str should be mangled to avoid conflicts due to duplication across the documentation. Defaults to ``[\w-]+``. -numpydoc_use_blockquotes : bool - Until version 0.8, parameter definitions were shown as blockquotes, rather - than in a definition list. If your styling requires blockquotes, switch - this config option to True. This option will be removed in version 0.10. numpydoc_attributes_as_param_list : bool Whether to format the Attributes section of a class page in the same way as the Parameter section. If it's False, the Attributes section will be diff --git a/numpydoc/docscrape_sphinx.py b/numpydoc/docscrape_sphinx.py index ee8e093..9a62cff 100644 --- a/numpydoc/docscrape_sphinx.py +++ b/numpydoc/docscrape_sphinx.py @@ -26,7 +26,6 @@ class SphinxDocString(NumpyDocString): def load_config(self, config): self.use_plots = config.get("use_plots", False) - self.use_blockquotes = config.get("use_blockquotes", False) self.class_members_toctree = config.get("class_members_toctree", True) self.attributes_as_param_list = config.get("attributes_as_param_list", True) self.xref_param_type = config.get("xref_param_type", False) @@ -84,8 +83,6 @@ class SphinxDocString(NumpyDocString): if not param.desc: out += self._str_indent([".."], 8) else: - if self.use_blockquotes: - out += [""] out += self._str_indent(param.desc, 8) out += [""] return out @@ -180,8 +177,7 @@ class SphinxDocString(NumpyDocString): """Generate RST for a listing of parameters or similar Parameter names are displayed as bold text, and descriptions - are in blockquotes. Descriptions may therefore contain block - markup as well. + are in definition lists. Parameters ---------- @@ -217,9 +213,7 @@ class SphinxDocString(NumpyDocString): parts.append(param_type) out += self._str_indent([" : ".join(parts)]) - if desc and self.use_blockquotes: - out += [""] - elif not desc: + if not desc: # empty definition desc = [".."] out += self._str_indent(desc, 8) diff --git a/numpydoc/numpydoc.py b/numpydoc/numpydoc.py index 8fa4f0a..509f053 100644 --- a/numpydoc/numpydoc.py +++ b/numpydoc/numpydoc.py @@ -171,7 +171,6 @@ def mangle_docstrings(app, what, name, obj, options, lines): cfg = { "use_plots": app.config.numpydoc_use_plots, - "use_blockquotes": app.config.numpydoc_use_blockquotes, "show_class_members": app.config.numpydoc_show_class_members, "show_inherited_class_members": show_inherited_class_members, "class_members_toctree": app.config.numpydoc_class_members_toctree, @@ -274,7 +273,6 @@ def setup(app, get_doc_object_=get_doc_object): app.connect("doctree-read", relabel_references) app.connect("doctree-resolved", clean_backrefs) app.add_config_value("numpydoc_use_plots", None, False) - app.add_config_value("numpydoc_use_blockquotes", None, False) app.add_config_value("numpydoc_show_class_members", True, True) app.add_config_value( "numpydoc_show_inherited_class_members", True, True, types=(bool, dict)
numpy/numpydoc
dcbfbc44ba01feddef62f294abf66581497f5828
diff --git a/numpydoc/tests/test_docscrape.py b/numpydoc/tests/test_docscrape.py index 01447a0..55ccf92 100644 --- a/numpydoc/tests/test_docscrape.py +++ b/numpydoc/tests/test_docscrape.py @@ -1059,52 +1059,6 @@ def test_plot_examples(): assert str(doc).count("plot::") == 1, str(doc) -def test_use_blockquotes(): - cfg = dict(use_blockquotes=True) - doc = SphinxDocString( - """ - Parameters - ---------- - abc : def - ghi - jkl - mno - - Returns - ------- - ABC : DEF - GHI - JKL - MNO - """, - config=cfg, - ) - line_by_line_compare( - str(doc), - """ - :Parameters: - - **abc** : def - - ghi - - **jkl** - - mno - - :Returns: - - **ABC** : DEF - - GHI - - JKL - - MNO - """, - ) - - def test_class_members(): class Dummy: """ diff --git a/numpydoc/tests/test_numpydoc.py b/numpydoc/tests/test_numpydoc.py index d414b1c..1629078 100644 --- a/numpydoc/tests/test_numpydoc.py +++ b/numpydoc/tests/test_numpydoc.py @@ -11,7 +11,6 @@ from sphinx.util import logging class MockConfig: numpydoc_use_plots = False - numpydoc_use_blockquotes = True numpydoc_show_class_members = True numpydoc_show_inherited_class_members = True numpydoc_class_members_toctree = True
Is numpydoc_use_blockquotes deprecated or not yet? On the documentation website for version 1.5.dev0: https://numpydoc.readthedocs.io/en/latest/install.html#configuration > numpydoc_use_blockquotes : bool > > Until version 0.8, parameter definitions were shown as blockquotes, rather than in a definition list. > If your styling requires blockquotes, switch this config option to True. > This option will be removed in version 0.10. And we are on version 1.4/1.5, so does this key still exists? Could you update the configuration documentation? 🙏
0.0
[ "numpydoc/tests/test_numpydoc.py::test_mangle_docstrings_basic", "numpydoc/tests/test_numpydoc.py::test_mangle_docstrings_inherited_class_members", "numpydoc/tests/test_numpydoc.py::test_mangle_docstring_validation_warnings[numpydoc_validation_checks0-expected_warn0-non_warnings0]", "numpydoc/tests/test_numpydoc.py::test_mangle_docstring_validation_warnings[numpydoc_validation_checks1-expected_warn1-non_warnings1]", "numpydoc/tests/test_numpydoc.py::test_mangle_docstring_validation_warnings[numpydoc_validation_checks2-expected_warn2-non_warnings2]", "numpydoc/tests/test_numpydoc.py::test_mangle_docstring_validation_exclude" ]
[ "numpydoc/tests/test_docscrape.py::test_signature[flush]", "numpydoc/tests/test_docscrape.py::test_signature[newline_indented]", "numpydoc/tests/test_docscrape.py::test_summary[flush]", "numpydoc/tests/test_docscrape.py::test_summary[newline_indented]", "numpydoc/tests/test_docscrape.py::test_extended_summary[flush]", "numpydoc/tests/test_docscrape.py::test_extended_summary[newline_indented]", "numpydoc/tests/test_docscrape.py::test_parameters[flush]", "numpydoc/tests/test_docscrape.py::test_parameters[newline_indented]", "numpydoc/tests/test_docscrape.py::test_other_parameters[flush]", "numpydoc/tests/test_docscrape.py::test_other_parameters[newline_indented]", "numpydoc/tests/test_docscrape.py::test_returns[flush]", "numpydoc/tests/test_docscrape.py::test_returns[newline_indented]", "numpydoc/tests/test_docscrape.py::test_yields", "numpydoc/tests/test_docscrape.py::test_sent", "numpydoc/tests/test_docscrape.py::test_returnyield", "numpydoc/tests/test_docscrape.py::test_section_twice", "numpydoc/tests/test_docscrape.py::test_notes[flush]", "numpydoc/tests/test_docscrape.py::test_notes[newline_indented]", "numpydoc/tests/test_docscrape.py::test_references[flush]", "numpydoc/tests/test_docscrape.py::test_references[newline_indented]", "numpydoc/tests/test_docscrape.py::test_examples[flush]", "numpydoc/tests/test_docscrape.py::test_examples[newline_indented]", "numpydoc/tests/test_docscrape.py::test_index[flush]", "numpydoc/tests/test_docscrape.py::test_index[newline_indented]", "numpydoc/tests/test_docscrape.py::test_str[flush]", "numpydoc/tests/test_docscrape.py::test_str[newline_indented]", "numpydoc/tests/test_docscrape.py::test_yield_str", "numpydoc/tests/test_docscrape.py::test_receives_str", "numpydoc/tests/test_docscrape.py::test_no_index_in_str", "numpydoc/tests/test_docscrape.py::test_sphinx_str", "numpydoc/tests/test_docscrape.py::test_sphinx_yields_str", "numpydoc/tests/test_docscrape.py::test_parameters_without_extended_description", "numpydoc/tests/test_docscrape.py::test_escape_stars", "numpydoc/tests/test_docscrape.py::test_empty_extended_summary", "numpydoc/tests/test_docscrape.py::test_raises", "numpydoc/tests/test_docscrape.py::test_warns", "numpydoc/tests/test_docscrape.py::test_see_also[]", "numpydoc/tests/test_docscrape.py::test_see_also[\\n", "numpydoc/tests/test_docscrape.py::test_see_also_parse_error", "numpydoc/tests/test_docscrape.py::test_see_also_print", "numpydoc/tests/test_docscrape.py::test_see_also_trailing_comma_warning", "numpydoc/tests/test_docscrape.py::test_unknown_section", "numpydoc/tests/test_docscrape.py::test_empty_first_line", "numpydoc/tests/test_docscrape.py::test_trailing_colon", "numpydoc/tests/test_docscrape.py::test_no_summary", "numpydoc/tests/test_docscrape.py::test_unicode", "numpydoc/tests/test_docscrape.py::test_plot_examples", "numpydoc/tests/test_docscrape.py::test_class_members", "numpydoc/tests/test_docscrape.py::test_duplicate_signature", "numpydoc/tests/test_docscrape.py::test_class_members_doc", "numpydoc/tests/test_docscrape.py::test_class_members_doc_sphinx", "numpydoc/tests/test_docscrape.py::test_class_attributes_as_member_list", "numpydoc/tests/test_docscrape.py::test_templated_sections", "numpydoc/tests/test_docscrape.py::test_nonstandard_property", "numpydoc/tests/test_docscrape.py::test_args_and_kwargs", "numpydoc/tests/test_docscrape.py::test_autoclass", "numpydoc/tests/test_docscrape.py::test_xref", "numpydoc/tests/test_docscrape.py::test__error_location_no_name_attr", "numpydoc/tests/test_numpydoc.py::test_clean_text_signature", "numpydoc/tests/test_numpydoc.py::test_update_config_invalid_validation_set", "numpydoc/tests/test_numpydoc.py::test_update_config_exclude_str" ]
2022-08-09 17:29:03+00:00
4,262
numpy__numpydoc-429
diff --git a/numpydoc/docscrape.py b/numpydoc/docscrape.py index 6bdaa84..9496f9d 100644 --- a/numpydoc/docscrape.py +++ b/numpydoc/docscrape.py @@ -226,10 +226,14 @@ class NumpyDocString(Mapping): params = [] while not r.eof(): header = r.read().strip() - if " :" in header: - arg_name, arg_type = header.split(" :", maxsplit=1) - arg_name, arg_type = arg_name.strip(), arg_type.strip() + if " : " in header: + arg_name, arg_type = header.split(" : ", maxsplit=1) else: + # NOTE: param line with single element should never have a + # a " :" before the description line, so this should probably + # warn. + if header.endswith(" :"): + header = header[:-2] if single_element_is_type: arg_name, arg_type = "", header else:
numpy/numpydoc
4ef89d4da0d494a5b7f6ecf1bd613599e50336bf
diff --git a/numpydoc/tests/test_docscrape.py b/numpydoc/tests/test_docscrape.py index 55ccf92..049d2a2 100644 --- a/numpydoc/tests/test_docscrape.py +++ b/numpydoc/tests/test_docscrape.py @@ -980,6 +980,21 @@ doc8 = NumpyDocString( ) +def test_returns_with_roles_no_names(): + """Make sure colons that are part of sphinx roles are not misinterpreted + as type separator in returns section. See gh-428.""" + docstring = NumpyDocString( + """ + Returns + ------- + str or :class:`NumpyDocString` + """ + ) + expected = "str or :class:`NumpyDocString`" # not "str or : class:... + assert docstring["Returns"][0].type == expected + assert expected in str(docstring) + + def test_trailing_colon(): assert doc8["Parameters"][0].name == "data"
Parsing `returns` section with several types and no name According to numpydoc [return value specification](https://numpydoc.readthedocs.io/en/latest/format.html#returns), the name for each return value may be optional. If the return value is omitted and the return type can take several types (if the actual type depends on user input, for example), then if the second type contains `" :"` as part of the type description (as in the following example) it is incorrectly identified as parameter type separator. This prevents sphinx recognition of the referenced type. ```python from numpydoc.docscrape import NumpyDocString docstr=""" Returns ------- str or :class:`NumpyDocString` """ print(NumpyDocString(docstr)) ``` Results with: ``` Returns ------- str or : class:`NumpyDocString` ``` I would expect getting the following result: ``` Returns ------- str or :class:`NumpyDocString` ``` The example is using version 1.4.0. I think this was changed in #286 . Thanks!
0.0
[ "numpydoc/tests/test_docscrape.py::test_returns_with_roles_no_names" ]
[ "numpydoc/tests/test_docscrape.py::test_signature[flush]", "numpydoc/tests/test_docscrape.py::test_signature[newline_indented]", "numpydoc/tests/test_docscrape.py::test_summary[flush]", "numpydoc/tests/test_docscrape.py::test_summary[newline_indented]", "numpydoc/tests/test_docscrape.py::test_extended_summary[flush]", "numpydoc/tests/test_docscrape.py::test_extended_summary[newline_indented]", "numpydoc/tests/test_docscrape.py::test_parameters[flush]", "numpydoc/tests/test_docscrape.py::test_parameters[newline_indented]", "numpydoc/tests/test_docscrape.py::test_other_parameters[flush]", "numpydoc/tests/test_docscrape.py::test_other_parameters[newline_indented]", "numpydoc/tests/test_docscrape.py::test_returns[flush]", "numpydoc/tests/test_docscrape.py::test_returns[newline_indented]", "numpydoc/tests/test_docscrape.py::test_yields", "numpydoc/tests/test_docscrape.py::test_sent", "numpydoc/tests/test_docscrape.py::test_returnyield", "numpydoc/tests/test_docscrape.py::test_section_twice", "numpydoc/tests/test_docscrape.py::test_notes[flush]", "numpydoc/tests/test_docscrape.py::test_notes[newline_indented]", "numpydoc/tests/test_docscrape.py::test_references[flush]", "numpydoc/tests/test_docscrape.py::test_references[newline_indented]", "numpydoc/tests/test_docscrape.py::test_examples[flush]", "numpydoc/tests/test_docscrape.py::test_examples[newline_indented]", "numpydoc/tests/test_docscrape.py::test_index[flush]", "numpydoc/tests/test_docscrape.py::test_index[newline_indented]", "numpydoc/tests/test_docscrape.py::test_str[flush]", "numpydoc/tests/test_docscrape.py::test_str[newline_indented]", "numpydoc/tests/test_docscrape.py::test_yield_str", "numpydoc/tests/test_docscrape.py::test_receives_str", "numpydoc/tests/test_docscrape.py::test_no_index_in_str", "numpydoc/tests/test_docscrape.py::test_sphinx_str", "numpydoc/tests/test_docscrape.py::test_sphinx_yields_str", "numpydoc/tests/test_docscrape.py::test_parameters_without_extended_description", "numpydoc/tests/test_docscrape.py::test_escape_stars", "numpydoc/tests/test_docscrape.py::test_empty_extended_summary", "numpydoc/tests/test_docscrape.py::test_raises", "numpydoc/tests/test_docscrape.py::test_warns", "numpydoc/tests/test_docscrape.py::test_see_also[]", "numpydoc/tests/test_docscrape.py::test_see_also[\\n", "numpydoc/tests/test_docscrape.py::test_see_also_parse_error", "numpydoc/tests/test_docscrape.py::test_see_also_print", "numpydoc/tests/test_docscrape.py::test_see_also_trailing_comma_warning", "numpydoc/tests/test_docscrape.py::test_unknown_section", "numpydoc/tests/test_docscrape.py::test_empty_first_line", "numpydoc/tests/test_docscrape.py::test_trailing_colon", "numpydoc/tests/test_docscrape.py::test_no_summary", "numpydoc/tests/test_docscrape.py::test_unicode", "numpydoc/tests/test_docscrape.py::test_plot_examples", "numpydoc/tests/test_docscrape.py::test_class_members", "numpydoc/tests/test_docscrape.py::test_duplicate_signature", "numpydoc/tests/test_docscrape.py::test_class_members_doc", "numpydoc/tests/test_docscrape.py::test_class_members_doc_sphinx", "numpydoc/tests/test_docscrape.py::test_class_attributes_as_member_list", "numpydoc/tests/test_docscrape.py::test_templated_sections", "numpydoc/tests/test_docscrape.py::test_nonstandard_property", "numpydoc/tests/test_docscrape.py::test_args_and_kwargs", "numpydoc/tests/test_docscrape.py::test_autoclass", "numpydoc/tests/test_docscrape.py::test_xref", "numpydoc/tests/test_docscrape.py::test__error_location_no_name_attr" ]
2022-09-16 00:56:29+00:00
4,263
numpy__numpydoc-433
diff --git a/.circleci/config.yml b/.circleci/config.yml index cc83b2a..b2269f4 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -2,32 +2,39 @@ version: 2 jobs: build_docs: docker: - - image: circleci/python:3.7-stretch + - image: "cimg/python:3.10" steps: - checkout - run: - name: Set BASH_ENV - command: | - echo "set -e" >> $BASH_ENV; - echo "export PATH=~/.local/bin:$PATH" >> $BASH_ENV; - sudo apt update - sudo apt install dvipng texlive-fonts-recommended texlive-latex-recommended texlive-latex-extra texlive-generic-extra latexmk texlive-xetex + name: Update apt-get + command: sudo apt-get update + - run: + name: Install TeX + command: sudo apt install dvipng texlive-fonts-recommended texlive-latex-recommended texlive-latex-extra latexmk texlive-xetex - restore_cache: keys: - pip-cache - run: name: Get dependencies and install command: | - pip install --user -q --upgrade pip setuptools - pip install --user -q --upgrade numpy matplotlib sphinx pydata-sphinx-theme - pip install --user -e . + python3 -m venv venv + source venv/bin/activate + python -m pip install --upgrade pip wheel setuptools + python -m pip install --upgrade -r requirements/doc.txt + python -m pip list - save_cache: key: pip-cache paths: - ~/.cache/pip - run: - name: make html + name: Install + command: | + source venv/bin/activate + pip install -e . + - run: + name: Build docs command: | + source venv/bin/activate make -C doc html - store_artifacts: path: doc/_build/html/ @@ -35,6 +42,7 @@ jobs: - run: name: make tinybuild command: | + source venv/bin/activate make -C numpydoc/tests/tinybuild html - store_artifacts: path: numpydoc/tests/tinybuild/_build/html/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 5bc6fa2..611379e 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -17,7 +17,7 @@ repos: - id: check-added-large-files - repo: https://github.com/psf/black - rev: 22.6.0 + rev: 22.8.0 hooks: - id: black @@ -34,7 +34,7 @@ repos: - id: blacken-docs - repo: https://github.com/asottile/pyupgrade - rev: v2.37.1 + rev: v2.38.2 hooks: - id: pyupgrade args: [--py37-plus] diff --git a/numpydoc/docscrape.py b/numpydoc/docscrape.py index 9496f9d..e5c07f5 100644 --- a/numpydoc/docscrape.py +++ b/numpydoc/docscrape.py @@ -12,6 +12,13 @@ import copy import sys +# TODO: Remove try-except when support for Python 3.7 is dropped +try: + from functools import cached_property +except ImportError: # cached_property added in Python 3.8 + cached_property = property + + def strip_blank_lines(l): "Remove leading and trailing blank lines from a list of lines" while l and not l[0].strip(): @@ -706,7 +713,7 @@ class ClassDoc(NumpyDocString): not name.startswith("_") and ( func is None - or isinstance(func, property) + or isinstance(func, (property, cached_property)) or inspect.isdatadescriptor(func) ) and self._is_show_member(name)
numpy/numpydoc
b138ea7758532a8b6950c4404570ab367c3919f4
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 437afca..24fe29c 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -26,7 +26,7 @@ jobs: - name: Setup environment run: | python -m pip install --upgrade pip wheel setuptools - python -m pip install -r requirements/test.txt -r doc/requirements.txt + python -m pip install -r requirements/test.txt -r requirements/doc.txt python -m pip install codecov python -m pip install ${{ matrix.sphinx-version }} python -m pip list @@ -116,7 +116,7 @@ jobs: - name: Setup environment run: | python -m pip install --upgrade pip wheel setuptools - python -m pip install --pre -r requirements/test.txt -r doc/requirements.txt + python -m pip install --pre -r requirements/test.txt -r requirements/doc.txt python -m pip install codecov python -m pip list diff --git a/numpydoc/tests/test_docscrape.py b/numpydoc/tests/test_docscrape.py index 049d2a2..227f872 100644 --- a/numpydoc/tests/test_docscrape.py +++ b/numpydoc/tests/test_docscrape.py @@ -1,6 +1,7 @@ from collections import namedtuple from copy import deepcopy import re +import sys import textwrap import warnings @@ -1624,6 +1625,26 @@ def test__error_location_no_name_attr(): nds._error_location(msg=msg) [email protected]( + sys.version_info < (3, 8), reason="cached_property was added in 3.8" +) +def test_class_docstring_cached_property(): + """Ensure that properties marked with the `cached_property` decorator + are listed in the Methods section. See gh-432.""" + from functools import cached_property + + class Foo: + _x = [1, 2, 3] + + @cached_property + def val(self): + return self._x + + class_docstring = get_doc_object(Foo) + assert len(class_docstring["Attributes"]) == 1 + assert class_docstring["Attributes"][0].name == "val" + + if __name__ == "__main__": import pytest
BUG: Numpydoc doesn't render attributes decorated with `cached_property` in the Attributes section Numpydoc doesn't render attributes decorated with `cached_property` in the `Attribute` section. I think it is due to this line: https://github.com/numpy/numpydoc/blob/b138ea7758532a8b6950c4404570ab367c3919f4/numpydoc/docscrape.py#L709 which can be changed to: ``` from functools import cached_property ... func is None or isinstance(func, property) or isinstance(func, cached_property) or inspect.isdatadescriptor(func) ``` to fix the issue. xref scipy/scipy#16002
0.0
[ "numpydoc/tests/test_docscrape.py::test_class_docstring_cached_property" ]
[ "numpydoc/tests/test_docscrape.py::test_signature[flush]", "numpydoc/tests/test_docscrape.py::test_signature[newline_indented]", "numpydoc/tests/test_docscrape.py::test_summary[flush]", "numpydoc/tests/test_docscrape.py::test_summary[newline_indented]", "numpydoc/tests/test_docscrape.py::test_extended_summary[flush]", "numpydoc/tests/test_docscrape.py::test_extended_summary[newline_indented]", "numpydoc/tests/test_docscrape.py::test_parameters[flush]", "numpydoc/tests/test_docscrape.py::test_parameters[newline_indented]", "numpydoc/tests/test_docscrape.py::test_other_parameters[flush]", "numpydoc/tests/test_docscrape.py::test_other_parameters[newline_indented]", "numpydoc/tests/test_docscrape.py::test_returns[flush]", "numpydoc/tests/test_docscrape.py::test_returns[newline_indented]", "numpydoc/tests/test_docscrape.py::test_yields", "numpydoc/tests/test_docscrape.py::test_sent", "numpydoc/tests/test_docscrape.py::test_returnyield", "numpydoc/tests/test_docscrape.py::test_section_twice", "numpydoc/tests/test_docscrape.py::test_notes[flush]", "numpydoc/tests/test_docscrape.py::test_notes[newline_indented]", "numpydoc/tests/test_docscrape.py::test_references[flush]", "numpydoc/tests/test_docscrape.py::test_references[newline_indented]", "numpydoc/tests/test_docscrape.py::test_examples[flush]", "numpydoc/tests/test_docscrape.py::test_examples[newline_indented]", "numpydoc/tests/test_docscrape.py::test_index[flush]", "numpydoc/tests/test_docscrape.py::test_index[newline_indented]", "numpydoc/tests/test_docscrape.py::test_str[flush]", "numpydoc/tests/test_docscrape.py::test_str[newline_indented]", "numpydoc/tests/test_docscrape.py::test_yield_str", "numpydoc/tests/test_docscrape.py::test_receives_str", "numpydoc/tests/test_docscrape.py::test_no_index_in_str", "numpydoc/tests/test_docscrape.py::test_sphinx_str", "numpydoc/tests/test_docscrape.py::test_sphinx_yields_str", "numpydoc/tests/test_docscrape.py::test_parameters_without_extended_description", "numpydoc/tests/test_docscrape.py::test_escape_stars", "numpydoc/tests/test_docscrape.py::test_empty_extended_summary", "numpydoc/tests/test_docscrape.py::test_raises", "numpydoc/tests/test_docscrape.py::test_warns", "numpydoc/tests/test_docscrape.py::test_see_also[]", "numpydoc/tests/test_docscrape.py::test_see_also[\\n", "numpydoc/tests/test_docscrape.py::test_see_also_parse_error", "numpydoc/tests/test_docscrape.py::test_see_also_print", "numpydoc/tests/test_docscrape.py::test_see_also_trailing_comma_warning", "numpydoc/tests/test_docscrape.py::test_unknown_section", "numpydoc/tests/test_docscrape.py::test_empty_first_line", "numpydoc/tests/test_docscrape.py::test_returns_with_roles_no_names", "numpydoc/tests/test_docscrape.py::test_trailing_colon", "numpydoc/tests/test_docscrape.py::test_no_summary", "numpydoc/tests/test_docscrape.py::test_unicode", "numpydoc/tests/test_docscrape.py::test_plot_examples", "numpydoc/tests/test_docscrape.py::test_class_members", "numpydoc/tests/test_docscrape.py::test_duplicate_signature", "numpydoc/tests/test_docscrape.py::test_class_members_doc", "numpydoc/tests/test_docscrape.py::test_class_members_doc_sphinx", "numpydoc/tests/test_docscrape.py::test_class_attributes_as_member_list", "numpydoc/tests/test_docscrape.py::test_templated_sections", "numpydoc/tests/test_docscrape.py::test_nonstandard_property", "numpydoc/tests/test_docscrape.py::test_args_and_kwargs", "numpydoc/tests/test_docscrape.py::test_autoclass", "numpydoc/tests/test_docscrape.py::test_xref", "numpydoc/tests/test_docscrape.py::test__error_location_no_name_attr" ]
2022-09-27 23:32:36+00:00
4,264
numpy__numpydoc-500
diff --git a/numpydoc/validate.py b/numpydoc/validate.py index 2cd1125..e98d385 100644 --- a/numpydoc/validate.py +++ b/numpydoc/validate.py @@ -280,7 +280,13 @@ class Validator: File name where the object is implemented (e.g. pandas/core/frame.py). """ try: - fname = inspect.getsourcefile(self.code_obj) + if isinstance(self.code_obj, property): + fname = inspect.getsourcefile(self.code_obj.fget) + elif isinstance(self.code_obj, functools.cached_property): + fname = inspect.getsourcefile(self.code_obj.func) + else: + fname = inspect.getsourcefile(self.code_obj) + except TypeError: # In some cases the object is something complex like a cython # object that can't be easily introspected. An it's better to @@ -295,7 +301,12 @@ class Validator: Number of line where the object is defined in its file. """ try: - sourcelines = inspect.getsourcelines(self.code_obj) + if isinstance(self.code_obj, property): + sourcelines = inspect.getsourcelines(self.code_obj.fget) + elif isinstance(self.code_obj, functools.cached_property): + sourcelines = inspect.getsourcelines(self.code_obj.func) + else: + sourcelines = inspect.getsourcelines(self.code_obj) # getsourcelines will return the line of the first decorator found for the # current function. We have to find the def declaration after that. def_line = next(
numpy/numpydoc
ecd24ab011634fd16cd7d811fd4adad3f305073c
diff --git a/numpydoc/tests/test_validate.py b/numpydoc/tests/test_validate.py index 5f76cd9..68040ad 100644 --- a/numpydoc/tests/test_validate.py +++ b/numpydoc/tests/test_validate.py @@ -1,7 +1,8 @@ import pytest import sys import warnings -from inspect import getsourcelines +from functools import cached_property +from inspect import getsourcelines, getsourcefile from numpydoc import validate import numpydoc.tests @@ -1541,8 +1542,12 @@ class DecoratorClass: """ Class and methods with decorators. - `DecoratorClass` has two decorators, `DecoratorClass.test_no_decorator` has no - decorator and `DecoratorClass.test_three_decorators` has three decorators. + * `DecoratorClass` has two decorators. + * `DecoratorClass.test_no_decorator` has no decorator. + * `DecoratorClass.test_property` has a `@property` decorator. + * `DecoratorClass.test_cached_property` has a `@cached_property` decorator. + * `DecoratorClass.test_three_decorators` has three decorators. + `Validator.source_file_def_line` should return the `def` or `class` line number, not the line of the first decorator. """ @@ -1551,6 +1556,16 @@ class DecoratorClass: """Test method without decorators.""" pass + @property + def test_property(self): + """Test property method.""" + pass + + @cached_property + def test_cached_property(self): + """Test property method.""" + pass + @decorator @decorator @decorator @@ -1577,7 +1592,7 @@ class TestValidatorClass: numpydoc.validate.Validator._load_obj(invalid_name) # inspect.getsourcelines does not return class decorators for Python 3.8. This was - # fixed starting with 3.9: https://github.com/python/cpython/issues/60060 + # fixed starting with 3.9: https://github.com/python/cpython/issues/60060. @pytest.mark.parametrize( ["decorated_obj", "def_line"], [ @@ -1590,6 +1605,14 @@ class TestValidatorClass: "numpydoc.tests.test_validate.DecoratorClass.test_no_decorator", getsourcelines(DecoratorClass.test_no_decorator)[-1], ], + [ + "numpydoc.tests.test_validate.DecoratorClass.test_property", + getsourcelines(DecoratorClass.test_property.fget)[-1] + 1, + ], + [ + "numpydoc.tests.test_validate.DecoratorClass.test_cached_property", + getsourcelines(DecoratorClass.test_cached_property.func)[-1] + 1, + ], [ "numpydoc.tests.test_validate.DecoratorClass.test_three_decorators", getsourcelines(DecoratorClass.test_three_decorators)[-1] + 3, @@ -1603,3 +1626,24 @@ class TestValidatorClass: ) ) assert doc.source_file_def_line == def_line + + @pytest.mark.parametrize( + ["property", "file_name"], + [ + [ + "numpydoc.tests.test_validate.DecoratorClass.test_property", + getsourcefile(DecoratorClass.test_property.fget), + ], + [ + "numpydoc.tests.test_validate.DecoratorClass.test_cached_property", + getsourcefile(DecoratorClass.test_cached_property.func), + ], + ], + ) + def test_source_file_name_with_properties(self, property, file_name): + doc = numpydoc.validate.Validator( + numpydoc.docscrape.get_doc_object( + numpydoc.validate.Validator._load_obj(property) + ) + ) + assert doc.source_file_name == file_name
`numpydoc ignore` inline comment not recognized when using decorators When using decorators, the `numpydoc ignore` inline comment does not seem to be recognized by either `numpydoc --validate` or the validation during Sphinx build. Here's a reprex, stored as `test.py`: ```python import functools def test_decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper @test_decorator def test_function(): # numpydoc ignore=PR02 """Test. Parameters ---------- x : int Test. """ print("test") ``` Using `python -m numpydoc --validate test.test_function` raises the warning `test.test_function:PR02:Unknown parameters {'x'}` when the decorator is used, but doesn't when the decorator is removed. Same thing when using validation during a Sphinx build. Interestingly, validation using `python -m numpydoc.hooks.validate_docstrings test.py` does not raise the PR02 warning, even when using the decorator.
0.0
[ "numpydoc/tests/test_validate.py::TestValidatorClass::test_source_file_def_line_with_decorators[numpydoc.tests.test_validate.DecoratorClass.test_property-1560]", "numpydoc/tests/test_validate.py::TestValidatorClass::test_source_file_def_line_with_decorators[numpydoc.tests.test_validate.DecoratorClass.test_cached_property-1565]", "numpydoc/tests/test_validate.py::TestValidatorClass::test_source_file_name_with_properties[numpydoc.tests.test_validate.DecoratorClass.test_property-/root/data/temp_dir/tmpt4x57kud/numpy__numpydoc__0.0/numpydoc/tests/test_validate.py]", "numpydoc/tests/test_validate.py::TestValidatorClass::test_source_file_name_with_properties[numpydoc.tests.test_validate.DecoratorClass.test_cached_property-/root/data/temp_dir/tmpt4x57kud/numpy__numpydoc__0.0/numpydoc/tests/test_validate.py]" ]
[ "numpydoc/tests/test_validate.py::test_validate.BadExamples.indentation_is_not_a_multiple_of_four", "numpydoc/tests/test_validate.py::test_validate.BadExamples.missing_whitespace_after_comma", "numpydoc/tests/test_validate.py::test_validate.BadExamples.missing_whitespace_around_arithmetic_operator", "numpydoc/tests/test_validate.py::test_validate.BadGenericDocStrings.sections_in_wrong_order", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.contains", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.empty_returns", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.good_imports", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.head", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.head1", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.mode", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.multiple_variables_on_one_line", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.no_returns", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.other_parameters", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.parameter_with_wrong_types_as_substrings", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.parameters_with_trailing_underscores", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.plot", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.random_letters", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.sample", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.sample_values", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.summary_starts_with_number", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.swap", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.valid_options_in_parameter_description_sets", "numpydoc/tests/test_validate.py::test_validate.GoodDocStrings.warnings", "numpydoc/tests/test_validate.py::test_utils_get_validation_checks[checks0-expected0]", "numpydoc/tests/test_validate.py::test_utils_get_validation_checks[checks1-expected1]", "numpydoc/tests/test_validate.py::test_utils_get_validation_checks[checks2-expected2]", "numpydoc/tests/test_validate.py::test_utils_get_validation_checks[checks3-expected3]", "numpydoc/tests/test_validate.py::test_utils_get_validation_checks[checks4-expected4]", "numpydoc/tests/test_validate.py::test_utils_get_validation_checks[checks5-expected5]", "numpydoc/tests/test_validate.py::test_get_validation_checks_validity[checks0]", "numpydoc/tests/test_validate.py::test_get_validation_checks_validity[checks1]", "numpydoc/tests/test_validate.py::test_get_validation_checks_validity[checks2]", "numpydoc/tests/test_validate.py::test_get_validation_checks_validity[checks3]", "numpydoc/tests/test_validate.py::test_no_file", "numpydoc/tests/test_validate.py::test_extract_ignore_validation_comments[class", "numpydoc/tests/test_validate.py::TestValidator::test_one_liner", "numpydoc/tests/test_validate.py::TestValidator::test_good_class", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[plot]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[swap]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[sample]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[random_letters]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[sample_values]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[head]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[head1]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[summary_starts_with_number]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[contains]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[mode]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[good_imports]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[no_returns]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[empty_returns]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[multiple_variables_on_one_line]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[other_parameters]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[warnings]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[valid_options_in_parameter_description_sets]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[parameters_with_trailing_underscores]", "numpydoc/tests/test_validate.py::TestValidator::test_good_functions[parameter_with_wrong_types_as_substrings]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_class", "numpydoc/tests/test_validate.py::TestValidator::test_bad_generic_functions[func]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_generic_functions[astype]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_generic_functions[astype1]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_generic_functions[astype2]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_generic_functions[astype3]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_generic_functions[plot]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_generic_functions[directives_without_two_colons]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadGenericDocStrings-unknown_section-msgs0]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadGenericDocStrings-sections_in_wrong_order-msgs1]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadGenericDocStrings-deprecation_in_wrong_order-msgs2]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadGenericDocStrings-directives_without_two_colons-msgs3]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadSeeAlso-no_desc-msgs4]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadSeeAlso-desc_no_period-msgs5]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadSeeAlso-desc_first_letter_lowercase-msgs6]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadSummaries-no_summary-msgs7]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadSummaries-heading_whitespaces-msgs8]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadSummaries-wrong_line-msgs9]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadSummaries-no_punctuation-msgs10]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadSummaries-no_capitalization-msgs11]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadSummaries-no_capitalization-msgs12]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadSummaries-multi_line-msgs13]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadSummaries-two_paragraph_multi_line-msgs14]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadParameters-no_type-msgs15]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadParameters-type_with_period-msgs16]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadParameters-no_description-msgs17]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadParameters-missing_params-msgs18]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadParameters-bad_colon_spacing-msgs19]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadParameters-no_description_period-msgs20]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadParameters-no_description_period_with_directive-msgs21]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadParameters-parameter_capitalization-msgs22]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadParameters-integer_parameter-msgs23]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadParameters-string_parameter-msgs24]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadParameters-boolean_parameter-msgs25]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadParameters-list_incorrect_parameter_type-msgs26]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadParameters-list_incorrect_parameter_type-msgs27]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadParameters-list_incorrect_parameter_type-msgs28]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadParameters-bad_parameter_spacing-msgs29]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadReturns-return_not_documented-msgs31]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadReturns-yield_not_documented-msgs32]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadReturns-no_description-msgs34]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadReturns-no_punctuation-msgs35]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadReturns-named_single_return-msgs36]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadReturns-no_capitalization-msgs37]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadReturns-no_period_multi-msgs38]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadGenericDocStrings-method_wo_docstrings-msgs39]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadGenericDocStrings-two_linebreaks_between_sections-msgs40]", "numpydoc/tests/test_validate.py::TestValidator::test_bad_docstrings[BadGenericDocStrings-linebreak_at_end_of_docstring-msgs41]", "numpydoc/tests/test_validate.py::TestValidatorClass::test_raises_for_invalid_module_name[unknown_mod]", "numpydoc/tests/test_validate.py::TestValidatorClass::test_raises_for_invalid_module_name[unknown_mod.MyClass]", "numpydoc/tests/test_validate.py::TestValidatorClass::test_raises_for_invalid_attribute_name[datetime.BadClassName]", "numpydoc/tests/test_validate.py::TestValidatorClass::test_raises_for_invalid_attribute_name[datetime.bad_method_name]", "numpydoc/tests/test_validate.py::TestValidatorClass::test_source_file_def_line_with_decorators[numpydoc.tests.test_validate.DecoratorClass-1541]", "numpydoc/tests/test_validate.py::TestValidatorClass::test_source_file_def_line_with_decorators[numpydoc.tests.test_validate.DecoratorClass.test_no_decorator-1555]", "numpydoc/tests/test_validate.py::TestValidatorClass::test_source_file_def_line_with_decorators[numpydoc.tests.test_validate.DecoratorClass.test_three_decorators-1572]" ]
2023-08-30 15:37:11+00:00
4,265
nutechsoftware__alarmdecoder-60
diff --git a/alarmdecoder/zonetracking.py b/alarmdecoder/zonetracking.py index 13be3c3..ae92eb7 100644 --- a/alarmdecoder/zonetracking.py +++ b/alarmdecoder/zonetracking.py @@ -189,7 +189,7 @@ class Zonetracker(object): if match is None: return - zone = match.group(1) + zone = int(match.group(1)) # Add new zones and clear expired ones. if zone in self._zones_faulted:
nutechsoftware/alarmdecoder
8a1a917dc04b60e03fa641f30000f5d8d23f94e6
diff --git a/test/test_zonetracking.py b/test/test_zonetracking.py index 6d8f087..0156871 100644 --- a/test/test_zonetracking.py +++ b/test/test_zonetracking.py @@ -76,7 +76,7 @@ class TestZonetracking(TestCase): msg = Message('[00000000000000100A--],0bf,[f707000600e5800c0c020000],"CHECK 1 "') self._zonetracker.update(msg) - self.assertEqual(self._zonetracker._zones['1'].status, Zone.CHECK) + self.assertEqual(self._zonetracker._zones[1].status, Zone.CHECK) def test_zone_restore_skip(self): panel_messages = [
Communicator failures not handled Messages such as this lead to failures when updating zones: ``` May 12 10:08:59 [00000001000000000A--],0fc,[f704009f10fc000008020000000000],"COMM. FAILURE " May 12 10:09:03 [00000001000000100A--],0bf,[f704009f10bf000208020000000000],"CHECK 103 LngRngRadio 0000" ``` ``` Traceback (most recent call last): File "/usr/local/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/local/lib/python3.8/site-packages/alarmdecoder/devices/base_device.py", line 148, in run self._device.read_line(timeout=self.READ_TIMEOUT) File "/usr/local/lib/python3.8/site-packages/alarmdecoder/devices/socket_device.py", line 356, in read_line self.on_read(data=ret) File "/usr/local/lib/python3.8/site-packages/alarmdecoder/event/event.py", line 84, in fire func(self.obj, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/alarmdecoder/decoder.py", line 1041, in _on_read self._handle_message(data) File "/usr/local/lib/python3.8/site-packages/alarmdecoder/decoder.py", line 439, in _handle_message msg = self._handle_keypad_message(data) File "/usr/local/lib/python3.8/site-packages/alarmdecoder/decoder.py", line 481, in _handle_keypad_message self._update_internal_states(msg) File "/usr/local/lib/python3.8/site-packages/alarmdecoder/decoder.py", line 632, in _update_internal_states self._update_zone_tracker(message) File "/usr/local/lib/python3.8/site-packages/alarmdecoder/decoder.py", line 1017, in _update_zone_tracker self._zonetracker.update(message) File "/usr/local/lib/python3.8/site-packages/alarmdecoder/zonetracking.py", line 209, in update self._zones_faulted.sort() TypeError: '<' not supported between instances of 'str' and 'int' ```
0.0
[ "test/test_zonetracking.py::TestZonetracking::test_ECP_failure" ]
[ "test/test_zonetracking.py::TestZonetracking::test_zone_restore_skip", "test/test_zonetracking.py::TestZonetracking::test_message_ready", "test/test_zonetracking.py::TestZonetracking::test_zone_fault", "test/test_zonetracking.py::TestZonetracking::test_zone_multi_zone_skip_restore", "test/test_zonetracking.py::TestZonetracking::test_zone_timeout_restore", "test/test_zonetracking.py::TestZonetracking::test_zone_out_of_order_fault", "test/test_zonetracking.py::TestZonetracking::test_zone_restore", "test/test_zonetracking.py::TestZonetracking::test_message_fault_text" ]
2021-05-31 23:12:39+00:00
4,266
nylas__nylas-python-318
diff --git a/CHANGELOG.md b/CHANGELOG.md index 8427d09..a9c651a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,10 @@ nylas-python Changelog ====================== +Unreleased +---------------- +* Add support for `view` parameter in `Threads.search()` + v5.14.1 ---------------- * Fix error when trying to iterate on list after calling count diff --git a/nylas/client/restful_model_collection.py b/nylas/client/restful_model_collection.py index 1ccb928..408e4e0 100644 --- a/nylas/client/restful_model_collection.py +++ b/nylas/client/restful_model_collection.py @@ -110,7 +110,9 @@ class RestfulModelCollection(object): def delete(self, id, data=None, **kwargs): return self.api._delete_resource(self.model_class, id, data=data, **kwargs) - def search(self, q, limit=None, offset=None): # pylint: disable=invalid-name + def search( + self, q, limit=None, offset=None, view=None + ): # pylint: disable=invalid-name from nylas.client.restful_models import ( Message, Thread, @@ -122,6 +124,8 @@ class RestfulModelCollection(object): kwargs["limit"] = limit if offset is not None: kwargs["offset"] = offset + if view is not None and self.model_class is Thread: + kwargs["view"] = view return self.api._get_resources(self.model_class, extra="search", **kwargs) else: raise Exception("Searching is only allowed on Thread and Message models")
nylas/nylas-python
f2bb44ec3f465ab93deadfc0249972eaa7b5df53
diff --git a/tests/conftest.py b/tests/conftest.py index 4eeeadd..8ead8d4 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1005,7 +1005,7 @@ def mock_thread_search_response(mocked_responses, api_url): mocked_responses.add( responses.GET, - api_url + "/threads/search?q=Helena", + re.compile(api_url + "/threads/search\?q=Helena.*"), body=response_body, status=200, content_type="application/json", diff --git a/tests/test_search.py b/tests/test_search.py index 52aa733..367d388 100644 --- a/tests/test_search.py +++ b/tests/test_search.py @@ -23,6 +23,20 @@ def test_search_messages_with_limit_offset(mocked_responses, api_client): assert request.path_url == "/messages/search?q=Pinot&limit=10&offset=0" [email protected]("mock_message_search_response") +def test_search_messages_with_view_should_not_appear(mocked_responses, api_client): + api_client.messages.search("Pinot", view="expanded") + request = mocked_responses.calls[0].request + assert request.path_url == "/messages/search?q=Pinot" + + [email protected]("mock_thread_search_response") +def test_search_messages_with_view_should_appear(mocked_responses, api_client): + api_client.threads.search("Helena", view="expanded") + request = mocked_responses.calls[0].request + assert request.path_url == "/threads/search?q=Helena&view=expanded" + + @pytest.mark.usefixtures("mock_message_search_response") def test_search_drafts(api_client): with pytest.raises(Exception):
RFE: Allow to control `threads.search` threads view ## Issue Overview Thanks for maintaining this damn awesome SDK! While implementing [email search functionality for Code Inbox](https://github.com/coder-inbox/code-inbox-server/blob/6ef01f0d207cbae10315a5f109646f5dc1bd34bd/src/nylas/router.py#L316) using this SDK, I encountered a limitation in the SDK. The current implementation allows searching for threads with no control over the `view` of the found threads, so there's no direct way to expand messages in searched threads. The following is the current signature of the `thread.search` function: ```python search(q, limit=None, offset=None) ``` As you can see, it is missing an important argument, namely `view` like `view=expanded`, that allows users to view details about the found messages in a particular thread. Currently, it returns the IDs of the found messages, `message_ids`. Here is an example: ```sh [{'id': 'akdfn6d3z1qnb4ms3bnsygtlb', 'cls': <class 'nylas.client.restful_models.Thread'>, 'api': <nylas.client.client.APIClient object at 0x7f4c1241f670>, 'draft_ids': [], 'message_ids': ['4th3z0d2h2pmus8kin6lqpcu7'], 'account_id': '48bkmeljel3rleswxmlzdgzqx', 'object': 'thread', 'participants': [{'email': '[email protected]', 'name': ''}, {'email': '[email protected]', 'name': 'The DEV Team'}], 'snippet': "We're partying...", 'subject': 'Weekly Wins – Open Source Spotlight & Hacktoberfest Highlights', 'last_message_timestamp': 1697220577, 'first_message_timestamp': 1697220577, 'last_message_received_timestamp': 1697220577, 'last_message_sent_timestamp': None, 'unread': True, 'starred': False, 'version': 0, '_labels': [{'display_name': 'Inbox', 'id': 'f0p7g3g1i5ikzge3h2pef2i3j', 'name': 'inbox'}, {'display_name': 'All Mail', 'id': '49n5iwureouzre0qc1he7u7ql', 'name': 'all'}, {'display_name': 'Category Updates', 'id': '3s46jis0l07vrq5xc334f4id9', 'name': 'updates'}], 'has_attachments': False, 'first_message_at': datetime.datetime(2023, 10, 13, 18, 9, 37), 'last_message_at': datetime.datetime(2023, 10, 13, 18, 9, 37), 'last_message_received_at': datetime.datetime(2023, 10, 13, 18, 9, 37)}] ``` But what is useful is the details of the messages in `_messages` in this array instead: ```sh [{'id': '89jw3cpqe0hpf8qbxtw0n9wpg', 'cls': <class 'nylas.client.restful_models.Thread'>, 'api': <nylas.client.client.APIClient object at 0x7f887b57a640>, 'account_id': '48bkmeljel3rleswxmlzdgzqx', 'object': 'thread', 'participants': [{'email': '[email protected]', 'name': ''}, {'email': '[email protected]', 'name': 'La Minute Culture Générale'}], 'snippet': 'Pouvez-vous dire...', 'last_message_timestamp': 1697289258, 'first_message_timestamp': 1697289258, 'last_message_received_timestamp': 1697289258, 'last_message_sent_timestamp': None, 'unread': True, 'starred': False, 'version': 0, '_labels': [{'display_name': 'Category Promotions', 'id': '38o9uy1kv5f9k0lw14zji3ehf', 'name': 'promotions'}, {'display_name': 'Inbox', 'id': 'f0p7g3g1i5ikzge3h2pef2i3j', 'name': 'inbox'}, {'display_name': 'All Mail', 'id': '49n5iwureouzre0qc1he7u7ql', 'name': 'all'}], '_messages': [{'account_id': '48bkmeljel3rleswxmlzdgzqx', 'bcc': [], 'cc': [], 'date': 1697289258, 'files': [], 'from': [{'email': '[email protected]', 'name': 'La Minute Culture Générale'}], 'id': '699vqk8pkci75zza719up4nc', 'labels': [{'display_name': 'Inbox', 'id': 'f0p7g3g1i5ikzge3h2pef2i3j', 'name': 'inbox'}, {'display_name': 'Category Promotions', 'id': '38o9uy1kv5f9k0lw14zji3ehf', 'name': 'promotions'}, {'display_name': 'All Mail', 'id': '49n5iwureouzre0qc1he7u7ql', 'name': 'all'}], 'object': 'message', 'reply_to': [], 'snippet': 'Pouvez-vous dire une phrase que vous pourriez dire naturellement à votre travail mais qui est incompréhensible pour tout le reste du monde ? La Minute Culture Générale • 130 k abonnés Amélior', 'starred': False, 'subject': 'Pouvez-vous dire une phrase que vous pourriez dire naturellement à votre travail mais qui est incompréhensible pour tout le reste du monde ?', 'thread_id': '89jw3cpqe0hpf8qbxtw0n9wpg', 'to': [{'email': '[email protected]', 'name': ''}], 'unread': True}], 'has_attachments': False, 'first_message_at': datetime.datetime(2023, 10, 14, 13, 14, 18), 'last_message_at': datetime.datetime(2023, 10, 14, 13, 14, 18), 'last_message_received_at': datetime.datetime(2023, 10, 14, 13, 14, 18)}] ``` I managed to work around this limitation by [manually constructing threads from the found emails](https://github.com/coder-inbox/code-inbox-server/blob/6ef01f0d207cbae10315a5f109646f5dc1bd34bd/src/nylas/router.py#L329-L342), but this workaround results in a performance issue and slow response times. https://github.com/nylas/nylas-python/assets/62179149/8923fbc6-6a20-4c3e-a79b-7323dbab8684 To improve the SDK's usability and performance, I propose adding a new argument to the `nylas.threads.search` function, namely `view`. ## Motivation ### Current Limitation This SDK provides a powerful and convenient way to search for emails using `nylas.messages.search`. However, when it comes to searching for threads, we need to retrieve a list of emails with details, manually identify related emails, and construct threads. This process is cumbersome and resource-intensive, especially when dealing with a large number of emails. ### Proposed Solution The proposed `view` argument to the `nylas.threads.search` method would simplify the process of searching for threads and message details. This new attribute would take a set of search parameters, execute the search on the Nylas API, and return a list of threads matching the criteria. This would significantly enhance the efficiency and usability of the SDK for platforms like Code Inbox. ## Benefits 1. **Usability**: Adding the `view` argument to the `nylas.threads.search` method would make it easier for developers to search for threads and emails details without needing to manually construct them from emails. 2. **Performance**: The SDK can optimize the process of searching for threads, resulting in faster response times and improved performance. 3. **Consistency**: This new argument would maintain consistency with the existing `threads.where(view="expanded")` method, making it more intuitive for developers already familiar with the SDK. ## Drawbacks 1. **API Changes**: Adding this method would require changes to the Nylas API, which might impact existing integrations. ## Conclusion The addition of the `view` argument to the `nylas.threads.search` method would enhance this SDK's capabilities and improve the performance of applications that rely on thread-based email processing. It aligns with the existing functionality of searching for emails and promotes consistency within the SDK. I'm open to feedback and discussions regarding the implementation of this feature. Please share your thoughts and concerns, and let's work together to make this damn SDK even more powerful and user-friendly. ## References - [Nylas search SDK Documentation](https://developer.nylas.com/docs/api/v2/#get-/threads/search) Thank you for considering this RFE. Your feedback and input are highly valued.
0.0
[ "tests/test_search.py::test_search_messages_with_view_should_not_appear", "tests/test_search.py::test_search_messages_with_view_should_appear" ]
[ "tests/test_search.py::test_search_threads", "tests/test_search.py::test_search_messages", "tests/test_search.py::test_search_messages_with_limit_offset", "tests/test_search.py::test_search_drafts" ]
2023-12-05 22:26:54+00:00
4,267
nylas__nylas-python-78
diff --git a/nylas/client/client.py b/nylas/client/client.py index 8278ae5..b41f782 100644 --- a/nylas/client/client.py +++ b/nylas/client/client.py @@ -143,13 +143,13 @@ class APIClient(json.JSONEncoder): if 'Authorization' in self.session.headers: del self.session.headers['Authorization'] - def authentication_url(self, redirect_uri, login_hint=''): + def authentication_url(self, redirect_uri, login_hint='', state=''): args = {'redirect_uri': redirect_uri, 'client_id': self.app_id or 'None', # 'None' for back-compat 'response_type': 'code', 'scope': 'email', 'login_hint': login_hint, - 'state': ''} + 'state': state} url = URLObject(self.authorize_url).add_query_params(args.items()) return str(url)
nylas/nylas-python
6a9b1e5c0774b2a198496daedb980b5bbc091d30
diff --git a/tests/test_client.py b/tests/test_client.py index 8a8590d..ea4831d 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -83,6 +83,12 @@ def test_client_authentication_url(api_client, api_url): expected2 = expected.set_query_param("login_hint", "hint") assert urls_equal(expected2, actual2) + actual3 = URLObject( + api_client.authentication_url("/redirect", state="confusion") + ) + expected3 = expected.set_query_param("state", "confusion") + assert urls_equal(expected3, actual3) + @responses.activate def test_client_token_for_code(api_client, api_url):
Allow users to pass `state` during authentication
0.0
[ "tests/test_client.py::test_client_authentication_url" ]
[ "tests/test_client.py::test_custom_client", "tests/test_client.py::test_client_error", "tests/test_client.py::test_client_access_token", "tests/test_client.py::test_client_app_secret", "tests/test_client.py::test_client_token_for_code", "tests/test_client.py::test_client_opensource_api", "tests/test_client.py::test_client_revoke_token", "tests/test_client.py::test_create_resources", "tests/test_client.py::test_call_resource_method" ]
2017-08-03 18:56:41+00:00
4,268
nylas__nylas-python-80
diff --git a/nylas/client/client.py b/nylas/client/client.py index ea9f2b4..d67109c 100644 --- a/nylas/client/client.py +++ b/nylas/client/client.py @@ -13,64 +13,61 @@ from nylas.client.restful_models import ( Account, APIAccount, SingletonAccount, Folder, Label, Draft ) -from nylas.client.errors import ( - APIClientError, ConnectionError, NotAuthorizedError, - InvalidRequestError, NotFoundError, MethodNotSupportedError, - ServerError, ServiceUnavailableError, ConflictError, - SendingQuotaExceededError, ServerTimeoutError, MessageRejectedError -) +from nylas.client.errors import APIClientError, ConnectionError, STATUS_MAP +try: + from json import JSONDecodeError +except ImportError: + JSONDecodeError = ValueError DEBUG = environ.get('NYLAS_CLIENT_DEBUG') API_SERVER = "https://api.nylas.com" def _validate(response): - status_code_to_exc = {400: InvalidRequestError, - 401: NotAuthorizedError, - 402: MessageRejectedError, - 403: NotAuthorizedError, - 404: NotFoundError, - 405: MethodNotSupportedError, - 409: ConflictError, - 429: SendingQuotaExceededError, - 500: ServerError, - 503: ServiceUnavailableError, - 504: ServerTimeoutError} - request = response.request - url = request.url - status_code = response.status_code - data = request.body - if DEBUG: # pragma: no cover - print("{} {} ({}) => {}: {}".format(request.method, url, data, - status_code, response.text)) - - try: - data = json.loads(data) if data else None - except (ValueError, TypeError): - pass - - if status_code == 200: + print("{method} {url} ({body}) => {status}: {text}".format( + method=response.request.method, + url=response.request.url, + data=response.request.body, + status=response.status_code, + text=response.text, + )) + + if response.ok: return response - elif status_code in status_code_to_exc: - cls = status_code_to_exc[status_code] - try: - response = json.loads(response.text) - kwargs = dict(url=url, status_code=status_code, - data=data) - for key in ['message', 'server_error']: - if key in response: - kwargs[key] = response[key] + # The rest of this function is logic for raising the correct exception + # from the `nylas.client.errors` module. In the future, it may be worth changing + # this function to just call `response.raise_for_status()`. + # http://docs.python-requests.org/en/master/api/#requests.Response.raise_for_status + try: + data = response.json() + json_content = True + except JSONDecodeError: + data = response.content + json_content = False + + kwargs = { + "url": response.request.url, + "status_code": response.status_code, + "data": data, + } + + if response.status_code in STATUS_MAP: + cls = STATUS_MAP[response.status_code] + if json_content: + if "message" in data: + kwargs["message"] = data["message"] + if "server_error" in data: + kwargs["server_error"] = data["server_error"] + raise cls(**kwargs) + else: + kwargs["message"] = "Malformed" raise cls(**kwargs) - - except (ValueError, TypeError): - raise cls(url=url, status_code=status_code, - data=data, message="Malformed") else: - raise APIClientError(url=url, status_code=status_code, - data=data, message="Unknown status code.") + kwargs["message"] = "Unknown status code." + raise APIClientError(**kwargs) def nylas_excepted(func): diff --git a/nylas/client/errors.py b/nylas/client/errors.py index d564154..29dc3f0 100644 --- a/nylas/client/errors.py +++ b/nylas/client/errors.py @@ -68,3 +68,18 @@ class ServerTimeoutError(APIClientError): class FileUploadError(APIClientError): pass + + +STATUS_MAP = { + 400: InvalidRequestError, + 401: NotAuthorizedError, + 402: MessageRejectedError, + 403: NotAuthorizedError, + 404: NotFoundError, + 405: MethodNotSupportedError, + 409: ConflictError, + 429: SendingQuotaExceededError, + 500: ServerError, + 503: ServiceUnavailableError, + 504: ServerTimeoutError, +}
nylas/nylas-python
726fad7765850a7d9d964c5412d86c6120ea3d9d
diff --git a/tests/conftest.py b/tests/conftest.py index af96ba9..e8b3efc 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -560,10 +560,13 @@ def mock_draft_saved_response(mocked_responses, api_url): } ], "unread": False, - "version": 0 + "version": 0, } - def request_callback(request): + def create_callback(_request): + return (200, {}, json.dumps(draft_json)) + + def update_callback(request): try: payload = json.loads(request.body) except ValueError: @@ -574,20 +577,21 @@ def mock_draft_saved_response(mocked_responses, api_url): } updated_draft_json = copy.copy(draft_json) updated_draft_json.update(stripped_payload) + updated_draft_json["version"] += 1 return (200, {}, json.dumps(updated_draft_json)) mocked_responses.add_callback( responses.POST, api_url + '/drafts/', content_type='application/json', - callback=request_callback, + callback=create_callback, ) mocked_responses.add_callback( responses.PUT, api_url + '/drafts/2h111aefv8pzwzfykrn7hercj', content_type='application/json', - callback=request_callback, + callback=update_callback, ) @@ -638,7 +642,6 @@ def mock_draft_sent_response(mocked_responses, api_url): def callback(request): payload = json.loads(request.body) assert payload['draft_id'] == '2h111aefv8pzwzfykrn7hercj' - assert payload['version'] == 0 return values.pop() mocked_responses.add_callback( diff --git a/tests/test_client.py b/tests/test_client.py index 2e7a75b..f7c2f97 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -185,3 +185,47 @@ def test_call_resource_method(mocked_responses, api_client, api_url): ) assert isinstance(contact, Contact) assert len(mocked_responses.calls) == 1 + + +def test_201_response(mocked_responses, api_client, api_url): + contact_data = { + "id": 1, + "name": "first", + "email": "[email protected]", + } + mocked_responses.add( + responses.POST, + api_url + "/contacts/", + content_type='application/json', + status=201, # This HTTP status still indicates success, + # even though it's not 200. + body=json.dumps(contact_data), + ) + contact = api_client.contacts.create() + contact.save() + assert len(mocked_responses.calls) == 1 + + +def test_301_response(mocked_responses, api_client, api_url): + contact_data = { + "id": 1, + "name": "first", + "email": "[email protected]", + } + mocked_responses.add( + responses.GET, + api_url + "/contacts/first", + status=301, + headers={"Location": api_url + "/contacts/1"} + ) + mocked_responses.add( + responses.GET, + api_url + "/contacts/1", + content_type='application/json', + status=200, + body=json.dumps(contact_data), + ) + contact = api_client.contacts.find("first") + assert contact["id"] == 1 + assert contact["name"] == "first" + assert len(mocked_responses.calls) == 2 diff --git a/tests/test_drafts.py b/tests/test_drafts.py index f8747c3..bfd84d7 100644 --- a/tests/test_drafts.py +++ b/tests/test_drafts.py @@ -62,3 +62,15 @@ def test_delete_draft(api_client): draft.save() # ... and delete it for real. draft.delete() + + [email protected]("mock_draft_saved_response") +def test_draft_version(api_client): + draft = api_client.drafts.create() + assert 'version' not in draft + draft.save() + assert draft['version'] == 0 + draft.update() + assert draft['version'] == 1 + draft.update() + assert draft['version'] == 2
Ensure draft versioning works Make sure that draft versions are updated correctly and automatically when creating and updating drafts.
0.0
[ "tests/test_client.py::test_201_response" ]
[ "tests/test_client.py::test_custom_client", "tests/test_client.py::test_client_error", "tests/test_client.py::test_client_access_token", "tests/test_client.py::test_client_app_secret", "tests/test_client.py::test_client_authentication_url", "tests/test_client.py::test_client_token_for_code", "tests/test_client.py::test_client_opensource_api", "tests/test_client.py::test_client_revoke_token", "tests/test_client.py::test_create_resources", "tests/test_client.py::test_call_resource_method", "tests/test_client.py::test_301_response", "tests/test_drafts.py::test_save_send_draft", "tests/test_drafts.py::test_draft_attachment", "tests/test_drafts.py::test_delete_draft", "tests/test_drafts.py::test_draft_version" ]
2017-08-03 19:19:57+00:00
4,269
nylas__nylas-python-81
diff --git a/nylas/client/client.py b/nylas/client/client.py index 91de992..d67109c 100644 --- a/nylas/client/client.py +++ b/nylas/client/client.py @@ -13,64 +13,61 @@ from nylas.client.restful_models import ( Account, APIAccount, SingletonAccount, Folder, Label, Draft ) -from nylas.client.errors import ( - APIClientError, ConnectionError, NotAuthorizedError, - InvalidRequestError, NotFoundError, MethodNotSupportedError, - ServerError, ServiceUnavailableError, ConflictError, - SendingQuotaExceededError, ServerTimeoutError, MessageRejectedError -) +from nylas.client.errors import APIClientError, ConnectionError, STATUS_MAP +try: + from json import JSONDecodeError +except ImportError: + JSONDecodeError = ValueError DEBUG = environ.get('NYLAS_CLIENT_DEBUG') API_SERVER = "https://api.nylas.com" def _validate(response): - status_code_to_exc = {400: InvalidRequestError, - 401: NotAuthorizedError, - 402: MessageRejectedError, - 403: NotAuthorizedError, - 404: NotFoundError, - 405: MethodNotSupportedError, - 409: ConflictError, - 429: SendingQuotaExceededError, - 500: ServerError, - 503: ServiceUnavailableError, - 504: ServerTimeoutError} - request = response.request - url = request.url - status_code = response.status_code - data = request.body - if DEBUG: # pragma: no cover - print("{} {} ({}) => {}: {}".format(request.method, url, data, - status_code, response.text)) - - try: - data = json.loads(data) if data else None - except (ValueError, TypeError): - pass - - if status_code == 200: + print("{method} {url} ({body}) => {status}: {text}".format( + method=response.request.method, + url=response.request.url, + data=response.request.body, + status=response.status_code, + text=response.text, + )) + + if response.ok: return response - elif status_code in status_code_to_exc: - cls = status_code_to_exc[status_code] - try: - response = json.loads(response.text) - kwargs = dict(url=url, status_code=status_code, - data=data) - for key in ['message', 'server_error']: - if key in response: - kwargs[key] = response[key] + # The rest of this function is logic for raising the correct exception + # from the `nylas.client.errors` module. In the future, it may be worth changing + # this function to just call `response.raise_for_status()`. + # http://docs.python-requests.org/en/master/api/#requests.Response.raise_for_status + try: + data = response.json() + json_content = True + except JSONDecodeError: + data = response.content + json_content = False + + kwargs = { + "url": response.request.url, + "status_code": response.status_code, + "data": data, + } + + if response.status_code in STATUS_MAP: + cls = STATUS_MAP[response.status_code] + if json_content: + if "message" in data: + kwargs["message"] = data["message"] + if "server_error" in data: + kwargs["server_error"] = data["server_error"] + raise cls(**kwargs) + else: + kwargs["message"] = "Malformed" raise cls(**kwargs) - - except (ValueError, TypeError): - raise cls(url=url, status_code=status_code, - data=data, message="Malformed") else: - raise APIClientError(url=url, status_code=status_code, - data=data, message="Unknown status code.") + kwargs["message"] = "Unknown status code." + raise APIClientError(**kwargs) def nylas_excepted(func): @@ -90,7 +87,7 @@ class APIClient(json.JSONEncoder): app_secret=environ.get('NYLAS_APP_SECRET'), access_token=environ.get('NYLAS_ACCESS_TOKEN'), api_server=API_SERVER): - if "://" not in api_server: + if not api_server.startswith("https://"): raise Exception("When overriding the Nylas API server address, you" " must include https://") self.api_server = api_server diff --git a/nylas/client/errors.py b/nylas/client/errors.py index d564154..29dc3f0 100644 --- a/nylas/client/errors.py +++ b/nylas/client/errors.py @@ -68,3 +68,18 @@ class ServerTimeoutError(APIClientError): class FileUploadError(APIClientError): pass + + +STATUS_MAP = { + 400: InvalidRequestError, + 401: NotAuthorizedError, + 402: MessageRejectedError, + 403: NotAuthorizedError, + 404: NotFoundError, + 405: MethodNotSupportedError, + 409: ConflictError, + 429: SendingQuotaExceededError, + 500: ServerError, + 503: ServiceUnavailableError, + 504: ServerTimeoutError, +}
nylas/nylas-python
16abdbf9963077d065e2c5ee6a0797ef5296341f
diff --git a/tests/conftest.py b/tests/conftest.py index 3bdd6ef..af96ba9 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -33,7 +33,7 @@ def message_body(): @pytest.fixture def api_url(): - return 'http://localhost:2222' + return 'https://localhost:2222' @pytest.fixture diff --git a/tests/test_client.py b/tests/test_client.py index 2adce17..f7c2f97 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -21,8 +21,8 @@ def urls_equal(url1, url2): def test_custom_client(): # Can specify API server - custom = APIClient(api_server="http://example.com") - assert custom.api_server == "http://example.com" + custom = APIClient(api_server="https://example.com") + assert custom.api_server == "https://example.com" # Must be a valid URL with pytest.raises(Exception) as exc: APIClient(api_server="invalid") @@ -185,3 +185,47 @@ def test_call_resource_method(mocked_responses, api_client, api_url): ) assert isinstance(contact, Contact) assert len(mocked_responses.calls) == 1 + + +def test_201_response(mocked_responses, api_client, api_url): + contact_data = { + "id": 1, + "name": "first", + "email": "[email protected]", + } + mocked_responses.add( + responses.POST, + api_url + "/contacts/", + content_type='application/json', + status=201, # This HTTP status still indicates success, + # even though it's not 200. + body=json.dumps(contact_data), + ) + contact = api_client.contacts.create() + contact.save() + assert len(mocked_responses.calls) == 1 + + +def test_301_response(mocked_responses, api_client, api_url): + contact_data = { + "id": 1, + "name": "first", + "email": "[email protected]", + } + mocked_responses.add( + responses.GET, + api_url + "/contacts/first", + status=301, + headers={"Location": api_url + "/contacts/1"} + ) + mocked_responses.add( + responses.GET, + api_url + "/contacts/1", + content_type='application/json', + status=200, + body=json.dumps(contact_data), + ) + contact = api_client.contacts.find("first") + assert contact["id"] == 1 + assert contact["name"] == "first" + assert len(mocked_responses.calls) == 2
Handle HTTP success status codes beyond 200 There are [many HTTP status codes that indicate different kinds of successful responses](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#2xx_Success). "200 OK" is the most widely used, but many RESTful APIs use "201 Created" in response to creating resources, and "204 No Content" in response to deleting resources. This project is hardcoded to only accept the 200 status code as success, which means that if the API ever returns a different, non-200 status code to indicate a successful response, the SDK will throw an exception. This project should work with success status codes beyond 200. When using the `requests` library, you can use [`response.ok`](http://docs.python-requests.org/en/master/api/#requests.Response.ok) to determine if the response was successful. You can also use [`response.raise_for_status()`](http://docs.python-requests.org/en/master/api/#requests.Response.raise_for_status) to raise an exception if necessary, rather than trying to determine if the request was successful and raising an exception if it wasn't.
0.0
[ "tests/test_client.py::test_201_response" ]
[ "tests/test_client.py::test_custom_client", "tests/test_client.py::test_client_error", "tests/test_client.py::test_client_access_token", "tests/test_client.py::test_client_app_secret", "tests/test_client.py::test_client_authentication_url", "tests/test_client.py::test_client_token_for_code", "tests/test_client.py::test_client_opensource_api", "tests/test_client.py::test_client_revoke_token", "tests/test_client.py::test_create_resources", "tests/test_client.py::test_call_resource_method", "tests/test_client.py::test_301_response" ]
2017-08-03 19:50:44+00:00
4,270
nylas__nylas-python-88
diff --git a/examples/webhooks/server.py b/examples/webhooks/server.py index 9d4b77d..4ccc8b3 100755 --- a/examples/webhooks/server.py +++ b/examples/webhooks/server.py @@ -129,7 +129,7 @@ def process_delta(delta): """ kwargs = { "type": delta["type"], - "date": datetime.datetime.fromtimestamp(delta["date"]), + "date": datetime.datetime.utcfromtimestamp(delta["date"]), "object_id": delta["object_data"]["id"], } print(" * {type} at {date} with ID {object_id}".format(**kwargs)) diff --git a/nylas/client/client.py b/nylas/client/client.py index aaf92d8..5ab5833 100644 --- a/nylas/client/client.py +++ b/nylas/client/client.py @@ -1,8 +1,13 @@ from __future__ import print_function import sys -import json from os import environ from base64 import b64encode +import json +try: + from json import JSONDecodeError +except ImportError: + JSONDecodeError = ValueError + import requests from urlobject import URLObject from six.moves.urllib.parse import urlencode @@ -14,10 +19,7 @@ from nylas.client.restful_models import ( Label, Draft ) from nylas.client.errors import APIClientError, ConnectionError, STATUS_MAP -try: - from json import JSONDecodeError -except ImportError: - JSONDecodeError = ValueError +from nylas.utils import convert_datetimes_to_timestamps DEBUG = environ.get('NYLAS_CLIENT_DEBUG') API_SERVER = "https://api.nylas.com" @@ -256,7 +258,10 @@ class APIClient(json.JSONEncoder): postfix ) - url = str(URLObject(url).add_query_params(filters.items())) + converted_filters = convert_datetimes_to_timestamps( + filters, cls.datetime_filter_attrs, + ) + url = str(URLObject(url).add_query_params(converted_filters.items())) response = self._get_http_session(cls.api_root).get(url) results = _validate(response).json() return [ @@ -280,7 +285,10 @@ class APIClient(json.JSONEncoder): url = "{}/a/{}/{}/{}{}".format(self.api_server, self.app_id, cls.collection_name, id, postfix) - url = str(URLObject(url).add_query_params(filters.items())) + converted_filters = convert_datetimes_to_timestamps( + filters, cls.datetime_filter_attrs, + ) + url = str(URLObject(url).add_query_params(converted_filters.items())) response = self._get_http_session(cls.api_root).get(url, headers=headers) return _validate(response) @@ -311,10 +319,10 @@ class APIClient(json.JSONEncoder): if cls == File: response = session.post(url, files=data) else: - data = json.dumps(data) + converted_data = convert_datetimes_to_timestamps(data, cls.datetime_attrs) headers = {'Content-Type': 'application/json'} headers.update(self.session.headers) - response = session.post(url, data=data, headers=headers) + response = session.post(url, json=converted_data, headers=headers) result = _validate(response).json() if cls.collection_name == 'send': @@ -332,10 +340,13 @@ class APIClient(json.JSONEncoder): if cls == File: response = session.post(url, files=data) else: - data = json.dumps(data) + converted_data = [ + convert_datetimes_to_timestamps(datum, cls.datetime_attrs) + for datum in data + ] headers = {'Content-Type': 'application/json'} headers.update(self.session.headers) - response = session.post(url, data=data, headers=headers) + response = session.post(url, json=converted_data, headers=headers) results = _validate(response).json() return [cls.create(self, **x) for x in results] @@ -363,7 +374,8 @@ class APIClient(json.JSONEncoder): session = self._get_http_session(cls.api_root) - response = session.put(url, json=data) + converted_data = convert_datetimes_to_timestamps(data, cls.datetime_attrs) + response = session.put(url, json=converted_data) result = _validate(response).json() return cls.create(self, **result) @@ -390,9 +402,10 @@ class APIClient(json.JSONEncoder): URLObject(self.api_server) .with_path(url_path) ) + converted_data = convert_datetimes_to_timestamps(data, cls.datetime_attrs) session = self._get_http_session(cls.api_root) - response = session.post(url, json=data) + response = session.post(url, json=converted_data) result = _validate(response).json() return cls.create(self, **result) diff --git a/nylas/client/restful_models.py b/nylas/client/restful_models.py index e73c100..1cb3bb9 100644 --- a/nylas/client/restful_models.py +++ b/nylas/client/restful_models.py @@ -1,5 +1,8 @@ +from datetime import datetime + from nylas.client.restful_model_collection import RestfulModelCollection from nylas.client.errors import FileUploadError +from nylas.utils import timestamp_from_dt from six import StringIO # pylint: disable=attribute-defined-outside-init @@ -7,6 +10,8 @@ from six import StringIO class NylasAPIObject(dict): attrs = [] + datetime_attrs = {} + datetime_filter_attrs = {} # The Nylas API holds most objects for an account directly under '/', # but some of them are under '/a' (mostly the account-management # and billing code). api_root is a tiny metaprogramming hack to let @@ -44,6 +49,9 @@ class NylasAPIObject(dict): attr = attr_name[1:] if attr in kwargs: obj[attr_name] = kwargs[attr] + for dt_attr, ts_attr in cls.datetime_attrs.items(): + if obj.get(ts_attr): + obj[dt_attr] = datetime.utcfromtimestamp(obj[ts_attr]) if 'id' not in kwargs: obj['id'] = None @@ -54,6 +62,9 @@ class NylasAPIObject(dict): for attr in self.cls.attrs: if hasattr(self, attr): dct[attr] = getattr(self, attr) + for dt_attr, ts_attr in self.cls.datetime_attrs.items(): + if self.get(dt_attr): + dct[ts_attr] = timestamp_from_dt(self[dt_attr]) return dct def child_collection(self, cls, **filters): @@ -83,6 +94,13 @@ class Message(NylasAPIObject): "account_id", "object", "snippet", "starred", "subject", "thread_id", "to", "unread", "starred", "_folder", "_labels", "headers"] + datetime_attrs = { + "received_at": "date", + } + datetime_filter_attrs = { + "received_before": "received_before", + "received_after": "received_after", + } collection_name = 'messages' def __init__(self, api): @@ -206,8 +224,21 @@ class Thread(NylasAPIObject): attrs = ["draft_ids", "id", "message_ids", "account_id", "object", "participants", "snippet", "subject", "subject_date", "last_message_timestamp", "first_message_timestamp", + "last_message_received_timestamp", "last_message_sent_timestamp", "unread", "starred", "version", "_folders", "_labels", "received_recent_date"] + datetime_attrs = { + "first_message_at": "first_message_timestamp", + "last_message_at": "last_message_timestamp", + "last_message_received_at": "last_message_received_timestamp", + "last_message_sent_at": "last_message_sent_timestamp", + } + datetime_filter_attrs = { + "last_message_before": "last_message_before", + "last_message_after": "last_message_after", + "started_before": "started_before", + "started_after": "started_after", + } collection_name = 'threads' def __init__(self, api): @@ -313,6 +344,9 @@ class Draft(Message): "account_id", "object", "subject", "thread_id", "to", "unread", "version", "file_ids", "reply_to_message_id", "reply_to", "starred", "snippet", "tracking"] + datetime_attrs = { + "last_modified_at": "date", + } collection_name = 'drafts' def __init__(self, api, thread_id=None): # pylint: disable=unused-argument @@ -407,6 +441,9 @@ class Event(NylasAPIObject): "read_only", "when", "busy", "participants", "calendar_id", "recurrence", "status", "master_event_id", "owner", "original_start_time", "object", "message_id"] + datetime_attrs = { + "original_start_at": "original_start_time", + } collection_name = 'events' def __init__(self, api): diff --git a/nylas/utils.py b/nylas/utils.py new file mode 100644 index 0000000..5c9b389 --- /dev/null +++ b/nylas/utils.py @@ -0,0 +1,32 @@ +from __future__ import division +from datetime import datetime + + +def timestamp_from_dt(dt, epoch=datetime(1970, 1, 1)): + """ + Convert a datetime to a timestamp. + https://stackoverflow.com/a/8778548/141395 + """ + delta = dt - epoch + # return delta.total_seconds() + return delta.seconds + delta.days * 86400 + + +def convert_datetimes_to_timestamps(data, datetime_attrs): + """ + Given a dictionary of data, and a dictionary of datetime attributes, + return a new dictionary that converts any datetime attributes that may + be present to their timestamped equivalent. + """ + if not data: + return data + + new_data = {} + for key, value in data.items(): + if key in datetime_attrs and isinstance(value, datetime): + new_key = datetime_attrs[key] + new_data[new_key] = timestamp_from_dt(value) + else: + new_data[key] = value + + return new_data diff --git a/pylintrc b/pylintrc index 20eed34..1f4681c 100644 --- a/pylintrc +++ b/pylintrc @@ -156,7 +156,7 @@ function-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ function-rgx=(([a-z][a-z0-9_]{2,50})|(_[a-z0-9_]*))$ # Good variable names which should always be accepted, separated by a comma -good-names=i,j,k,ex,Run,_,id +good-names=i,j,k,ex,Run,_,id,dt,db # Include a hint for the correct naming format with invalid-name include-naming-hint=no
nylas/nylas-python
aff310af49b2ed5deb9a70e0bf0cb824283f71fe
diff --git a/tests/conftest.py b/tests/conftest.py index e8b3efc..6a51745 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -264,7 +264,8 @@ def mock_messages(mocked_responses, api_url, account_id): } ], "starred": False, - "unread": True + "unread": True, + "date": 1265077342, }, { "id": "1238", "subject": "Test Message 2", @@ -278,7 +279,8 @@ def mock_messages(mocked_responses, api_url, account_id): } ], "starred": False, - "unread": True + "unread": True, + "date": 1265085342, }, { "id": "12", "subject": "Test Message 3", @@ -292,7 +294,8 @@ def mock_messages(mocked_responses, api_url, account_id): } ], "starred": False, - "unread": False + "unread": False, + "date": 1265093842, } ]) endpoint = re.compile(api_url + '/messages') @@ -369,7 +372,11 @@ def mock_threads(mocked_responses, api_url, account_id): "id": "abcd" }], "starred": True, - "unread": False + "unread": False, + "first_message_timestamp": 1451703845, + "last_message_timestamp": 1483326245, + "last_message_received_timestamp": 1483326245, + "last_message_sent_timestamp": 1483232461, } ]) endpoint = re.compile(api_url + '/threads') @@ -395,7 +402,11 @@ def mock_thread(mocked_responses, api_url, account_id): "id": "abcd" }], "starred": True, - "unread": False + "unread": False, + "first_message_timestamp": 1451703845, + "last_message_timestamp": 1483326245, + "last_message_received_timestamp": 1483326245, + "last_message_sent_timestamp": 1483232461, } response_body = json.dumps(base_thrd) @@ -451,7 +462,11 @@ def mock_labelled_thread(mocked_responses, api_url, account_id): "account_id": account_id, "object": "label" } - ] + ], + "first_message_timestamp": 1451703845, + "last_message_timestamp": 1483326245, + "last_message_received_timestamp": 1483326245, + "last_message_sent_timestamp": 1483232461, } response_body = json.dumps(base_thread) @@ -881,10 +896,17 @@ def mock_events(mocked_responses, api_url): "title": "Pool party", "location": "Local Community Pool", "participants": [ - "Alice", - "Bob", - "Claire", - "Dot", + { + "comment": None, + "email": "[email protected]", + "name": "Kelly Nylanaut", + "status": "noreply", + }, { + "comment": None, + "email": "[email protected]", + "name": "Sarah Nylanaut", + "status": "no", + }, ] } ]) diff --git a/tests/test_drafts.py b/tests/test_drafts.py index bfd84d7..7827254 100644 --- a/tests/test_drafts.py +++ b/tests/test_drafts.py @@ -1,9 +1,20 @@ +from datetime import datetime + import pytest from nylas.client.errors import InvalidRequestError +from nylas.utils import timestamp_from_dt # pylint: disable=len-as-condition [email protected]("mock_drafts") +def test_draft_attrs(api_client): + draft = api_client.drafts.first() + expected_modified = datetime(2015, 8, 4, 10, 34, 46) + assert draft.last_modified_at == expected_modified + assert draft.date == timestamp_from_dt(expected_modified) + + @pytest.mark.usefixtures( "mock_draft_saved_response", "mock_draft_sent_response" ) diff --git a/tests/test_messages.py b/tests/test_messages.py index 8a76136..6e76bf1 100644 --- a/tests/test_messages.py +++ b/tests/test_messages.py @@ -1,8 +1,11 @@ +from datetime import datetime import json + import six import pytest from urlobject import URLObject from nylas.client.restful_models import Message +from nylas.utils import timestamp_from_dt @pytest.mark.usefixtures("mock_messages") @@ -15,6 +18,14 @@ def test_messages(api_client): assert not message.starred [email protected]("mock_messages") +def test_message_attrs(api_client): + message = api_client.messages.first() + expected_received = datetime(2010, 2, 2, 2, 22, 22) + assert message.received_at == expected_received + assert message.date == timestamp_from_dt(expected_received) + + @pytest.mark.usefixtures("mock_account", "mock_messages", "mock_message") def test_message_stars(api_client): message = api_client.messages.first() @@ -89,3 +100,21 @@ def test_slice_messages(api_client): messages = api_client.messages[0:2] assert len(messages) == 3 assert all(isinstance(message, Message) for message in messages) + + [email protected]("mock_messages") +def test_filter_messages_dt(mocked_responses, api_client): + api_client.messages.where(received_before=datetime(2010, 6, 1)).all() + assert len(mocked_responses.calls) == 1 + request = mocked_responses.calls[0].request + url = URLObject(request.url) + assert url.query_dict["received_before"] == "1275350400" + + [email protected]("mock_messages") +def test_filter_messages_ts(mocked_responses, api_client): + api_client.messages.where(received_before=1275350400).all() + assert len(mocked_responses.calls) == 1 + request = mocked_responses.calls[0].request + url = URLObject(request.url) + assert url.query_dict["received_before"] == "1275350400" diff --git a/tests/test_threads.py b/tests/test_threads.py index 2abf27f..d59758d 100644 --- a/tests/test_threads.py +++ b/tests/test_threads.py @@ -1,5 +1,40 @@ +from datetime import datetime + import pytest +from urlobject import URLObject from nylas.client.restful_models import Message, Draft, Label +from nylas.utils import timestamp_from_dt + + [email protected]("mock_threads") +def test_thread_attrs(api_client): + thread = api_client.threads.first() + expected_first = datetime(2016, 1, 2, 3, 4, 5) + expected_last = datetime(2017, 1, 2, 3, 4, 5) + expected_last_received = datetime(2017, 1, 2, 3, 4, 5) + expected_last_sent = datetime(2017, 1, 1, 1, 1, 1) + + assert thread.first_message_timestamp == timestamp_from_dt(expected_first) + assert thread.first_message_at == expected_first + assert thread.last_message_timestamp == timestamp_from_dt(expected_last) + assert thread.last_message_at == expected_last + assert thread.last_message_received_timestamp == timestamp_from_dt(expected_last_received) + assert thread.last_message_received_at == expected_last_received + assert thread.last_message_sent_timestamp == timestamp_from_dt(expected_last_sent) + assert thread.last_message_sent_at == expected_last_sent + + +def test_update_thread_attrs(api_client): + thread = api_client.threads.create() + first = datetime(2017, 2, 3, 10, 0, 0) + second = datetime(2016, 10, 5, 14, 30, 0) + # timestamps and datetimes are handled totally separately + thread.last_message_at = first + thread.last_message_timestamp = timestamp_from_dt(second) + assert thread.last_message_at == first + assert thread.last_message_timestamp == timestamp_from_dt(second) + # but datetimes overwrite timestamps when serializing to JSON + assert thread.as_json()['last_message_timestamp'] == timestamp_from_dt(first) @pytest.mark.usefixtures("mock_threads") @@ -98,3 +133,21 @@ def test_thread_reply(api_client): assert isinstance(draft, Draft) assert draft.thread_id == thread.id assert draft.subject == thread.subject + + [email protected]("mock_threads") +def test_filter_threads_dt(mocked_responses, api_client): + api_client.threads.where(started_before=datetime(2010, 6, 1)).all() + assert len(mocked_responses.calls) == 1 + request = mocked_responses.calls[0].request + url = URLObject(request.url) + assert url.query_dict["started_before"] == "1275350400" + + [email protected]("mock_threads") +def test_filter_threads_ts(mocked_responses, api_client): + api_client.threads.where(started_before=1275350400).all() + assert len(mocked_responses.calls) == 1 + request = mocked_responses.calls[0].request + url = URLObject(request.url) + assert url.query_dict["started_before"] == "1275350400"
Filtering on booleans and datetimes fails When trying to filter on boolean fields, like `starred` or `unread`, the SDK converts the boolean object to a string, so `True` becomes "True" and `False` becomes "False". Both of these strings are treated as true by the backend. As a result, it's not possible to filter on boolean False for any boolean fields. ```python >>> client.threads.where(unread=True).all() # fetches `https://api.nylas.com/threads?unread=True&offset=0&limit=50` >>> client.threads.where(unread=False).all() # fetches `https://api.nylas.com/threads?unread=False&offset=0&limit=50` # same results either way ``` In addition, in Python it's common to use the [`datetime`](https://docs.python.org/3/library/datetime.html) module to refer to dates and times. There are several APIs that return datetimes, or accept datetimes as parameters (like `starts_before` when filtering events). The SDK _only_ accepts timestamps, and does not work with datetime objects at all. In fact, trying to pass a datetime object to the SDK results in an internal exception, like this: ```python >>> now datetime.datetime(2017, 8, 7, 16, 56, 36, 56763) >>> client.events.where(starts_before=now).all() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/singingwolfboy/clones/nylas-python/nylas/client/restful_model_collection.py", line 45, in all return self._range(self.filters['offset'], limit) File "/Users/singingwolfboy/clones/nylas-python/nylas/client/restful_model_collection.py", line 118, in _range to_fetch) File "/Users/singingwolfboy/clones/nylas-python/nylas/client/restful_model_collection.py", line 107, in _get_model_collection **filters) File "/Users/singingwolfboy/clones/nylas-python/nylas/client/client.py", line 76, in caught return func(*args, **kwargs) File "/Users/singingwolfboy/clones/nylas-python/nylas/client/client.py", line 259, in _get_resources url = str(URLObject(url).add_query_params(filters.items())) File "/Users/singingwolfboy/.virtualenvs/nylas-python/lib/python3.6/site-packages/urlobject/urlobject.py", line 464, in add_query_params return self.with_query(self.query.add_params(*args, **kwargs)) File "/Users/singingwolfboy/.virtualenvs/nylas-python/lib/python3.6/site-packages/urlobject/query_string.py", line 67, in add_params new = new.add_param(name, value) File "/Users/singingwolfboy/.virtualenvs/nylas-python/lib/python3.6/site-packages/urlobject/query_string.py", line 58, in add_param parameter = qs_encode(name) + '=' + qs_encode(value) File "/Users/singingwolfboy/.virtualenvs/nylas-python/lib/python3.6/site-packages/urlobject/query_string.py", line 138, in _qs_encode_py3 return urlparse.quote_plus(s) File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/parse.py", line 791, in quote_plus string = quote(string, safe + space, encoding, errors) File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/parse.py", line 775, in quote return quote_from_bytes(string, safe) File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/parse.py", line 800, in quote_from_bytes raise TypeError("quote_from_bytes() expected bytes") TypeError: quote_from_bytes() expected bytes ```
0.0
[ "tests/test_drafts.py::test_draft_attrs", "tests/test_drafts.py::test_save_send_draft", "tests/test_drafts.py::test_draft_attachment", "tests/test_drafts.py::test_delete_draft", "tests/test_drafts.py::test_draft_version", "tests/test_threads.py::test_update_thread_attrs" ]
[]
2017-08-07 20:57:19+00:00
4,271
oasis-open__cti-pattern-validator-10
diff --git a/.travis.yml b/.travis.yml index 896f07d..52cda7e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,10 +1,12 @@ sudo: false language: python python: + - "2.6" - "2.7" - "3.3" - "3.4" - "3.5" + - "3.6" install: - pip install -U pip setuptools - pip install tox-travis diff --git a/stix2patterns/validator.py b/stix2patterns/validator.py index b1563d9..79313c0 100644 --- a/stix2patterns/validator.py +++ b/stix2patterns/validator.py @@ -35,9 +35,15 @@ def run_validator(pattern): returned in a list. The test passed if the returned list is empty. ''' + start = '' if isinstance(pattern, six.string_types): + start = pattern[:2] pattern = InputStream(pattern) + if not start: + start = pattern.readline()[:2] + pattern.seek(0) + parseErrListener = STIXPatternErrorListener() lexer = STIXPatternLexer(pattern) @@ -54,6 +60,11 @@ def run_validator(pattern): parser.pattern() + # replace with easier-to-understand error message + if not (start[0] == '[' or start == '(['): + parseErrListener.err_strings[0] = "FAIL: Error found at line 1:0. " \ + "input is missing square brackets" + return parseErrListener.err_strings diff --git a/tox.ini b/tox.ini index c40db2f..164fcf3 100644 --- a/tox.ini +++ b/tox.ini @@ -1,5 +1,5 @@ [tox] -envlist = py27,py33,py34,py35,pycodestyle +envlist = py26,py27,py33,py34,py35,py36,pycodestyle [testenv] deps = pytest @@ -16,7 +16,9 @@ exclude=grammars [travis] python = + 2.6: py26 2.7: py27, pycodestyle 3.3: py33 3.4: py34 3.5: py35 + 3.6: py36
oasis-open/cti-pattern-validator
82956eaff8caf5af323b0c712550bfc5840fbd62
diff --git a/stix2patterns/test/test_validator.py b/stix2patterns/test/test_validator.py index 626b981..814517f 100644 --- a/stix2patterns/test/test_validator.py +++ b/stix2patterns/test/test_validator.py @@ -2,7 +2,6 @@ Test cases for stix2patterns/validator.py. ''' import os - import pytest from stix2patterns.validator import validate @@ -22,21 +21,33 @@ def test_spec_patterns(test_input): FAIL_CASES = [ - "file:size = 1280", # Does not use square brackets - "[file:hashes.MD5 = cead3f77f6cda6ec00f57d76c9a6879f]" # No quotes around string - "[file.size = 1280]", # Use period instead of colon - "[file:name MATCHES /.*\\.dll/]", # Quotes around regular expression - "[win-registry-key:key = 'hkey_local_machine\\\\foo\\\\bar'] WITHIN 5 HOURS", # SECONDS is the only valid time unit + ("file:size = 1280", # Does not use square brackets + "FAIL: Error found at line 1:0. input is missing square brackets"), + ("[file:size = ]", # Missing value + "FAIL: Error found at line 1:13. no viable alternative at input ']'"), + ("[file:hashes.MD5 = cead3f77f6cda6ec00f57d76c9a6879f]", # No quotes around string + "FAIL: Error found at line 1:19. no viable alternative at input 'cead3f77f6cda6ec00f57d76c9a6879f'"), + ("[file.size = 1280]", # Use period instead of colon + "FAIL: Error found at line 1:5. no viable alternative at input 'file.'"), + ("[file:name MATCHES /.*\\.dll/]", # Quotes around regular expression + "FAIL: Error found at line 1:19. mismatched input '/' expecting <INVALID>"), + ("[win-registry-key:key = 'hkey_local_machine\\\\foo\\\\bar'] WITHIN ]", # Missing Qualifier value + "FAIL: Error found at line 1:63. mismatched input ']' expecting {<INVALID>, <INVALID>}"), + ("[win-registry-key:key = 'hkey_local_machine\\\\foo\\\\bar'] WITHIN 5 HOURS]", # SECONDS is the only valid time unit + "FAIL: Error found at line 1:65. mismatched input 'HOURS' expecting <INVALID>"), + ("[network-traffic:dst_ref.value ISSUBSET ]", # Missing second Comparison operand + "FAIL: Error found at line 1:40. missing <INVALID> at ']'"), # TODO: add more failing test cases. ] [email protected]("test_input", FAIL_CASES) -def test_fail_patterns(test_input): [email protected]("test_input,test_output", FAIL_CASES) +def test_fail_patterns(test_input, test_output): ''' Validate that patterns fail as expected. ''' - pass_test = validate(test_input, print_errs=True) + pass_test, errors = validate(test_input, ret_errs=True, print_errs=True) + assert errors[0] == test_output assert pass_test is False
Unclear error message when missing brackets If the input is missing the surrounding '[' and ']' (ie. the input is just a Comparison Expression, not an Observation Expression or Pattern Expresion), the validator's error message is unhelpful: $ validate_patterns Enter a pattern to validate: file-object:hashes.md5 = '79054025255fb1a26e4bc422aef54eb4' FAIL: Error found at line 1:0. no viable alternative at input 'file-object' This message comes from the ANTLR library so it can't easily be changed, but perhaps the validator could check if the input starts with '[' or '([' and print a more user-friendly error message?
0.0
[ "stix2patterns/test/test_validator.py::test_fail_patterns[file:size" ]
[ "stix2patterns/test/test_validator.py::test_spec_patterns[[(file:name", "stix2patterns/test/test_validator.py::test_spec_patterns[[artifact:mime_type", "stix2patterns/test/test_validator.py::test_spec_patterns[[network-traffic:dst_ref.value", "stix2patterns/test/test_validator.py::test_pass_patterns[[network-connection:extended_properties[0].source_payload", "stix2patterns/test/test_validator.py::test_spec_patterns[[network-traffic:dst_ref.type", "stix2patterns/test/test_validator.py::test_spec_patterns[[file:extensions.windows-pebinary-ext.sections[*].entropy", "stix2patterns/test/test_validator.py::test_fail_patterns[[file:size", "stix2patterns/test/test_validator.py::test_spec_patterns[[file:hashes.\"SHA-256\"", "stix2patterns/test/test_validator.py::test_spec_patterns[[user-account:account_type", "stix2patterns/test/test_validator.py::test_fail_patterns[[file.size", "stix2patterns/test/test_validator.py::test_pass_patterns[[ipv4addr:value", "stix2patterns/test/test_validator.py::test_pass_patterns[[emailaddr:value", "stix2patterns/test/test_validator.py::test_spec_patterns[[domain-name:value", "stix2patterns/test/test_validator.py::test_pass_patterns[[file:size", "stix2patterns/test/test_validator.py::test_spec_patterns[[x-usb-device:usbdrive.serial_number", "stix2patterns/test/test_validator.py::test_fail_patterns[[win-registry-key:key", "stix2patterns/test/test_validator.py::test_pass_patterns[[file:file_name", "stix2patterns/test/test_validator.py::test_spec_patterns[[process:command_line", "stix2patterns/test/test_validator.py::test_pass_patterns[[file:extended_properties.ntfs-ext.sid", "stix2patterns/test/test_validator.py::test_spec_patterns[[file:name", "stix2patterns/test/test_validator.py::test_spec_patterns[[email-message:sender_ref.value", "stix2patterns/test/test_validator.py::test_spec_patterns[[file:mime_type", "stix2patterns/test/test_validator.py::test_fail_patterns[[network-traffic:dst_ref.value", "stix2patterns/test/test_validator.py::test_spec_patterns[[url:value", "stix2patterns/test/test_validator.py::test_fail_patterns[[file:hashes.MD5", "stix2patterns/test/test_validator.py::test_pass_patterns[[user-account:value", "stix2patterns/test/test_validator.py::test_spec_patterns[[x509-certificate:issuer", "stix2patterns/test/test_validator.py::test_spec_patterns[([file:name", "stix2patterns/test/test_validator.py::test_spec_patterns[[email-message:from_ref.value", "stix2patterns/test/test_validator.py::test_pass_patterns[[win-registry-key:key", "stix2patterns/test/test_validator.py::test_fail_patterns[[file:name", "stix2patterns/test/test_validator.py::test_spec_patterns[[windows-registry-key:key", "stix2patterns/test/test_validator.py::test_spec_patterns[[file:hashes.MD5", "stix2patterns/test/test_validator.py::test_pass_patterns[[file:file_system_properties.file_name" ]
2017-03-14 14:07:07+00:00
4,272
oasis-open__cti-pattern-validator-71
diff --git a/setup.py b/setup.py index 36453d8..2ab745d 100644 --- a/setup.py +++ b/setup.py @@ -42,6 +42,7 @@ setup( 'antlr4-python3-runtime~=4.8.0 ; python_version>="3"', 'six', 'typing ; python_version<"3.5" and python_version>="3"', + 'enum34 ; python_version<"3.4"', ], package_data={ 'stix2patterns.test.v20': ['spec_examples.txt'], diff --git a/stix2patterns/v21/validator.py b/stix2patterns/v21/validator.py index 12a1a38..11adaed 100644 --- a/stix2patterns/v21/validator.py +++ b/stix2patterns/v21/validator.py @@ -2,14 +2,69 @@ Validates a user entered pattern against STIXPattern grammar. """ +import enum + from antlr4 import CommonTokenStream, ParseTreeWalker from . import object_validator from ..exceptions import STIXPatternErrorListener from .grammars.STIXPatternLexer import STIXPatternLexer +from .grammars.STIXPatternListener import STIXPatternListener from .grammars.STIXPatternParser import STIXPatternParser from .inspector import InspectionListener +QualType = enum.Enum("QualType", "WITHIN REPEATS STARTSTOP") + + +class DuplicateQualifierTypeError(Exception): + """ + Instances represent finding multiple qualifiers of the same type directly + applied to an observation expression (i.e. not on some parenthesized group + of which the observation expression is a member). + """ + def __init__(self, qual_type): + """ + Initialize this exception instance. + + :param qual_type: The qualifier type which was found to be duplicated. + Must be a member of the QualType enum. + """ + message = "Duplicate qualifier type encountered: " + qual_type.name + + super(DuplicateQualifierTypeError, self).__init__(message) + + self.qual_type = qual_type + + +class ValidationListener(STIXPatternListener): + """ + Does some pattern validation via a parse tree traversal. + """ + def __init__(self): + self.__qual_types = None + + def __check_qualifier_type(self, qual_type): + if self.__qual_types is not None: + if qual_type in self.__qual_types: + raise DuplicateQualifierTypeError(qual_type) + else: + self.__qual_types.add(qual_type) + + def exitObservationExpressionSimple(self, ctx): + self.__qual_types = set() + + def exitObservationExpressionCompound(self, ctx): + self.__qual_types = None + + def exitObservationExpressionWithin(self, ctx): + self.__check_qualifier_type(QualType.WITHIN) + + def exitObservationExpressionRepeated(self, ctx): + self.__check_qualifier_type(QualType.REPEATS) + + def exitObservationExpressionStartStop(self, ctx): + self.__check_qualifier_type(QualType.STARTSTOP) + def run_validator(pattern, start): """ @@ -38,7 +93,6 @@ def run_validator(pattern, start): parser.literalNames[i] = parser.symbolicNames[i] tree = parser.pattern() - inspection_listener = InspectionListener() # replace with easier-to-understand error message if not (start[0] == '[' or start == '(['): @@ -47,6 +101,7 @@ def run_validator(pattern, start): # validate observed objects if len(parseErrListener.err_strings) == 0: + inspection_listener = InspectionListener() ParseTreeWalker.DEFAULT.walk(inspection_listener, tree) patt_data = inspection_listener.pattern_data() @@ -56,9 +111,9 @@ def run_validator(pattern, start): parseErrListener.err_strings.extend(obj_validator_results) # check qualifiers - qualifiers = [q.split()[0] for q in patt_data.qualifiers] - if len(qualifiers) != len(set(qualifiers)): - parseErrListener.err_strings.insert(0, "FAIL: The same qualifier is" - " used more than once") + try: + ParseTreeWalker.DEFAULT.walk(ValidationListener(), tree) + except DuplicateQualifierTypeError as e: + parseErrListener.err_strings.insert(0, "FAIL: " + e.args[0]) return parseErrListener.err_strings
oasis-open/cti-pattern-validator
45f81f0c5b9481054ba28aea2ecb372faee7fe2b
diff --git a/stix2patterns/test/v21/test_validator.py b/stix2patterns/test/v21/test_validator.py index d78fc75..26f9076 100644 --- a/stix2patterns/test/v21/test_validator.py +++ b/stix2patterns/test/v21/test_validator.py @@ -51,7 +51,13 @@ FAIL_CASES = [ ("[file:hashes.'SHA-256' = 'f00']", # Malformed hash value "FAIL: 'f00' is not a valid SHA-256 hash"), ("[win-registry-key:key = 'hkey_local_machine\\\\foo\\\\bar'] WITHIN 5 SECONDS WITHIN 6 SECONDS", - "FAIL: The same qualifier is used more than once"), + "FAIL: Duplicate qualifier type encountered: WITHIN"), + ("([win-registry-key:key = 'hkey_local_machine\\\\foo\\\\bar'] REPEATS 2 TIMES REPEATS 3 TIMES)", + "FAIL: Duplicate qualifier type encountered: REPEATS"), + ("[win-registry-key:key = 'hkey_local_machine\\\\foo\\\\bar'] " + "START t'2016-06-01T01:30:00.123Z' STOP t'2016-06-01T02:20:00.123Z' " + "START t'2016-06-01T01:30:00.123Z' STOP t'2016-06-01T02:20:00.123Z'", + "FAIL: Duplicate qualifier type encountered: STARTSTOP"), # TODO: add more failing test cases. ] @@ -89,6 +95,12 @@ PASS_CASES = [ "[foo:bar=1] REPEATS 9 TIMES", "[network-traffic:start = '2018-04-20T12:36:24.558Z']", "( [(network-traffic:dst_port IN(443,6443,8443) AND network-traffic:src_packets != 0) ])", # Misplaced whitespace + "([win-registry-key:key = 'hkey_local_machine\\\\foo\\\\bar']) WITHIN 5 SECONDS WITHIN 6 SECONDS", + "([win-registry-key:key = 'hkey_local_machine\\\\foo\\\\bar'] REPEATS 2 TIMES) REPEATS 2 TIMES", + "[network-traffic:src_port = 37020 AND user-account:user_id = 'root'] " + "START t'2016-06-01T01:30:00.123Z' STOP t'2016-06-01T02:20:00.123Z' OR " + "[ipv4-addr:value = '192.168.122.83'] " + "START t'2016-06-01T03:55:00.123Z' STOP t'2016-06-01T04:30:24.743Z'" ]
STIX 2.1 pattern validation failing on multiple START STOP qualifiers When running the following from a terminal: ``` validate-patterns -v 2.1 [network-traffic:src_port = 37020 AND user-account:user_id = 'root'] START t'2016-06-01T01:30:00.123Z' STOP t'2016-06-01T02:20:00.123Z' OR [ipv4-addr:value = '192.168.122.83'] START t'2016-06-01T03:55:00.123Z' STOP t'2016-06-01T04:30:24.743Z' ``` I get a failure: `FAIL: The same qualifier is used more than once` I thought STIX patterns supported multiple START STOP qualifiers since the qualifier affects only the observation that immediately precedes it. Am I wrong in this?
0.0
[ "stix2patterns/test/v21/test_validator.py::test_fail_patterns[[win-registry-key:key", "stix2patterns/test/v21/test_validator.py::test_fail_patterns[([win-registry-key:key", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[([win-registry-key:key", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[network-traffic:src_port" ]
[ "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[file:hashes.'SHA-256'", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[email-message:from_ref.value", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[([file:hashes.MD5", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[user-account:account_type", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[artifact:mime_type", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[file:name", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[file:extensions.'windows-pebinary-ext'.sections[*].entropy", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[file:mime_type", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[network-traffic:dst_ref.type", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[domain-name:value", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[url:value", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[x509-certificate:issuer", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[windows-registry-key:key", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[(file:name", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[email-message:sender_ref.value", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[x-usb-device:usbdrive.serial_number", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[process:command_line", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[network-traffic:dst_ref.value", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[([file:name", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[file:hashes.MD5", "stix2patterns/test/v21/test_validator.py::test_fail_patterns[file:size", "stix2patterns/test/v21/test_validator.py::test_fail_patterns[[file:size", "stix2patterns/test/v21/test_validator.py::test_fail_patterns[[file:hashes.MD5", "stix2patterns/test/v21/test_validator.py::test_fail_patterns[[file.size", "stix2patterns/test/v21/test_validator.py::test_fail_patterns[[file:name", "stix2patterns/test/v21/test_validator.py::test_fail_patterns[[network-traffic:dst_ref.value", "stix2patterns/test/v21/test_validator.py::test_fail_patterns[[x_whatever:detected", "stix2patterns/test/v21/test_validator.py::test_fail_patterns[[artifact:payload_bin", "stix2patterns/test/v21/test_validator.py::test_fail_patterns[[foo:bar=1]", "stix2patterns/test/v21/test_validator.py::test_fail_patterns[[file:hashes.'SHA-256'", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[file:size", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[file:file_name", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[file:extended_properties.'ntfs-ext'.sid", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[emailaddr:value", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[ipv4addr:value", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[user-account:value", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[file:file_system_properties.file_name", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[network-connection:extended_properties[0].source_payload", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[win-registry-key:key", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[x_whatever:detected", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[artifact:payload_bin", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[foo:bar=1]", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[network-traffic:start", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[(" ]
2020-02-21 14:47:45+00:00
4,273
oasis-open__cti-pattern-validator-79
diff --git a/stix2patterns/v20/object_validator.py b/stix2patterns/v20/object_validator.py index 235ee63..72f051c 100644 --- a/stix2patterns/v20/object_validator.py +++ b/stix2patterns/v20/object_validator.py @@ -1,4 +1,5 @@ import re +import stix2patterns.inspector HASHES_REGEX = { "MD5": (r"^[a-fA-F0-9]{32}$", "MD5"), @@ -25,14 +26,16 @@ def verify_object(patt_data): # iterate over observed objects for type_name, comp in patt_data.comparisons.items(): - for expression in comp: - if 'hashes' in expression[0]: - hash_type = str(expression[0][-1].upper().replace('-', ''). - replace("\'", "")) - hash_string = str(expression[2].replace("\'", "")) - if hash_type in HASHES_REGEX: - if not re.match(HASHES_REGEX[hash_type][0], hash_string): - error_list.append( - msg.format(hash_string, expression[0][-1]) - ) + for obj_path, op, value in comp: + if 'hashes' in obj_path: + hash_selector = obj_path[-1] + if hash_selector is not stix2patterns.inspector.INDEX_STAR: + hash_type = \ + hash_selector.upper().replace('-', '').replace("'", "") + hash_string = value.replace("'", "") + if hash_type in HASHES_REGEX: + if not re.match(HASHES_REGEX[hash_type][0], hash_string): + error_list.append( + msg.format(hash_string, hash_selector) + ) return error_list diff --git a/stix2patterns/v21/object_validator.py b/stix2patterns/v21/object_validator.py index 9920862..7558ba5 100644 --- a/stix2patterns/v21/object_validator.py +++ b/stix2patterns/v21/object_validator.py @@ -1,4 +1,5 @@ import re +import stix2patterns.inspector HASHES_REGEX = { "MD5": (r"^[a-fA-F0-9]{32}$", "MD5"), @@ -25,14 +26,16 @@ def verify_object(patt_data): # iterate over observed objects for type_name, comp in patt_data.comparisons.items(): - for expression in comp: - if 'hashes' in expression[0]: - hash_type = str(expression[0][-1].upper().replace('-', ''). - replace("\'", "")) - hash_string = str(expression[2].replace("\'", "")) - if hash_type in HASHES_REGEX: - if not re.match(HASHES_REGEX[hash_type][0], hash_string): - error_list.append( - msg.format(hash_string, expression[0][-1]) - ) + for obj_path, op, value in comp: + if 'hashes' in obj_path: + hash_selector = obj_path[-1] + if hash_selector is not stix2patterns.inspector.INDEX_STAR: + hash_type = \ + hash_selector.upper().replace('-', '').replace("'", "") + hash_string = value.replace("'", "") + if hash_type in HASHES_REGEX: + if not re.match(HASHES_REGEX[hash_type][0], hash_string): + error_list.append( + msg.format(hash_string, hash_selector) + ) return error_list
oasis-open/cti-pattern-validator
f819fc5c65785c950a2a65f2f8b78cc534ad8872
diff --git a/stix2patterns/test/v20/test_validator.py b/stix2patterns/test/v20/test_validator.py index 44e0eae..8ddfa65 100644 --- a/stix2patterns/test/v20/test_validator.py +++ b/stix2patterns/test/v20/test_validator.py @@ -87,6 +87,7 @@ PASS_CASES = [ "[foo:bar=1] REPEATS 9 TIMES", "[network-traffic:start = '2018-04-20T12:36:24.558Z']", "( [(network-traffic:dst_port IN(443,6443,8443) AND network-traffic:src_packets != 0) ])", # Misplaced whitespace + "[file:hashes[*] = '8665c8d477534008b3058b72e2dae8ae']", ] diff --git a/stix2patterns/test/v21/test_validator.py b/stix2patterns/test/v21/test_validator.py index 26f9076..d6e2ef5 100644 --- a/stix2patterns/test/v21/test_validator.py +++ b/stix2patterns/test/v21/test_validator.py @@ -100,7 +100,8 @@ PASS_CASES = [ "[network-traffic:src_port = 37020 AND user-account:user_id = 'root'] " "START t'2016-06-01T01:30:00.123Z' STOP t'2016-06-01T02:20:00.123Z' OR " "[ipv4-addr:value = '192.168.122.83'] " - "START t'2016-06-01T03:55:00.123Z' STOP t'2016-06-01T04:30:24.743Z'" + "START t'2016-06-01T03:55:00.123Z' STOP t'2016-06-01T04:30:24.743Z'", + "[file:hashes[*] = '8665c8d477534008b3058b72e2dae8ae']", ]
Validator raises/crashes on hashes type "wildcard subscription" Steps to reproduce ------------------ ``` $ validate-patterns -v 2.1 Enter a pattern to validate: [file:hashes[*] = '8665c8d477534008b3058b72e2dae8ae'] ``` Expected result --------------- Something like `FAIL: Error found at line 1:... hashes type does not support wildcard subscription` Actual result ------------- ``` Traceback (most recent call last): File "bin/validate-patterns", line 10, in <module> sys.exit(main()) File "lib/python3.6/site-packages/stix2patterns/validator.py", line 91, in main tests_passed, err_strings = validate(pattern, args.version, True) File "lib/python3.6/site-packages/stix2patterns/validator.py", line 47, in validate errs = run_validator(user_input, stix_version) File "lib/python3.6/site-packages/stix2patterns/validator.py", line 34, in run_validator return run_validator21(pattern, start) File "lib/python3.6/site-packages/stix2patterns/v21/validator.py", line 109, in run_validator obj_validator_results = object_validator.verify_object(patt_data) File "lib/python3.6/site-packages/stix2patterns/v21/object_validator.py", line 29, in verify_object hash_type = str(expression[0][-1].upper().replace('-', ''). AttributeError: 'object' object has no attribute 'upper' ```
0.0
[ "stix2patterns/test/v20/test_validator.py::test_pass_patterns[[file:hashes[*]", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[file:hashes[*]" ]
[ "stix2patterns/test/v20/test_validator.py::test_spec_patterns[[file:hashes.'SHA-256'", "stix2patterns/test/v20/test_validator.py::test_spec_patterns[[email-message:from_ref.value", "stix2patterns/test/v20/test_validator.py::test_spec_patterns[([file:hashes.MD5", "stix2patterns/test/v20/test_validator.py::test_spec_patterns[[user-account:account_type", "stix2patterns/test/v20/test_validator.py::test_spec_patterns[[artifact:mime_type", "stix2patterns/test/v20/test_validator.py::test_spec_patterns[[file:name", "stix2patterns/test/v20/test_validator.py::test_spec_patterns[[file:extensions.'windows-pebinary-ext'.sections[*].entropy", "stix2patterns/test/v20/test_validator.py::test_spec_patterns[[file:mime_type", "stix2patterns/test/v20/test_validator.py::test_spec_patterns[[network-traffic:dst_ref.type", "stix2patterns/test/v20/test_validator.py::test_spec_patterns[[domain-name:value", "stix2patterns/test/v20/test_validator.py::test_spec_patterns[[url:value", "stix2patterns/test/v20/test_validator.py::test_spec_patterns[[x509-certificate:issuer", "stix2patterns/test/v20/test_validator.py::test_spec_patterns[[windows-registry-key:key", "stix2patterns/test/v20/test_validator.py::test_spec_patterns[[(file:name", "stix2patterns/test/v20/test_validator.py::test_spec_patterns[[email-message:sender_ref.value", "stix2patterns/test/v20/test_validator.py::test_spec_patterns[[x-usb-device:usbdrive.serial_number", "stix2patterns/test/v20/test_validator.py::test_spec_patterns[[process:command_line", "stix2patterns/test/v20/test_validator.py::test_spec_patterns[[network-traffic:dst_ref.value", "stix2patterns/test/v20/test_validator.py::test_spec_patterns[([file:name", "stix2patterns/test/v20/test_validator.py::test_spec_patterns[[file:hashes.MD5", "stix2patterns/test/v20/test_validator.py::test_spec_patterns[(", "stix2patterns/test/v20/test_validator.py::test_fail_patterns[file:size", "stix2patterns/test/v20/test_validator.py::test_fail_patterns[[file:size", "stix2patterns/test/v20/test_validator.py::test_fail_patterns[[file:hashes.MD5", "stix2patterns/test/v20/test_validator.py::test_fail_patterns[[file.size", "stix2patterns/test/v20/test_validator.py::test_fail_patterns[[file:name", "stix2patterns/test/v20/test_validator.py::test_fail_patterns[[win-registry-key:key", "stix2patterns/test/v20/test_validator.py::test_fail_patterns[[network-traffic:dst_ref.value", "stix2patterns/test/v20/test_validator.py::test_fail_patterns[[x_whatever:detected", "stix2patterns/test/v20/test_validator.py::test_fail_patterns[[artifact:payload_bin", "stix2patterns/test/v20/test_validator.py::test_fail_patterns[[foo:bar=1]", "stix2patterns/test/v20/test_validator.py::test_fail_patterns[[file:hashes.'SHA-256'", "stix2patterns/test/v20/test_validator.py::test_pass_patterns[[file:size", "stix2patterns/test/v20/test_validator.py::test_pass_patterns[[file:file_name", "stix2patterns/test/v20/test_validator.py::test_pass_patterns[[file:extended_properties.'ntfs-ext'.sid", "stix2patterns/test/v20/test_validator.py::test_pass_patterns[[emailaddr:value", "stix2patterns/test/v20/test_validator.py::test_pass_patterns[[ipv4addr:value", "stix2patterns/test/v20/test_validator.py::test_pass_patterns[[user-account:value", "stix2patterns/test/v20/test_validator.py::test_pass_patterns[[file:file_system_properties.file_name", "stix2patterns/test/v20/test_validator.py::test_pass_patterns[[network-connection:extended_properties[0].source_payload", "stix2patterns/test/v20/test_validator.py::test_pass_patterns[[win-registry-key:key", "stix2patterns/test/v20/test_validator.py::test_pass_patterns[[x_whatever:detected", "stix2patterns/test/v20/test_validator.py::test_pass_patterns[[artifact:payload_bin", "stix2patterns/test/v20/test_validator.py::test_pass_patterns[[foo:bar=1]", "stix2patterns/test/v20/test_validator.py::test_pass_patterns[[network-traffic:start", "stix2patterns/test/v20/test_validator.py::test_pass_patterns[(", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[file:hashes.'SHA-256'", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[email-message:from_ref.value", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[([file:hashes.MD5", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[user-account:account_type", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[artifact:mime_type", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[file:name", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[file:extensions.'windows-pebinary-ext'.sections[*].entropy", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[file:mime_type", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[network-traffic:dst_ref.type", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[domain-name:value", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[url:value", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[x509-certificate:issuer", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[windows-registry-key:key", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[(file:name", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[email-message:sender_ref.value", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[x-usb-device:usbdrive.serial_number", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[process:command_line", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[network-traffic:dst_ref.value", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[([file:name", "stix2patterns/test/v21/test_validator.py::test_spec_patterns[[file:hashes.MD5", "stix2patterns/test/v21/test_validator.py::test_fail_patterns[file:size", "stix2patterns/test/v21/test_validator.py::test_fail_patterns[[file:size", "stix2patterns/test/v21/test_validator.py::test_fail_patterns[[file:hashes.MD5", "stix2patterns/test/v21/test_validator.py::test_fail_patterns[[file.size", "stix2patterns/test/v21/test_validator.py::test_fail_patterns[[file:name", "stix2patterns/test/v21/test_validator.py::test_fail_patterns[[win-registry-key:key", "stix2patterns/test/v21/test_validator.py::test_fail_patterns[[network-traffic:dst_ref.value", "stix2patterns/test/v21/test_validator.py::test_fail_patterns[[x_whatever:detected", "stix2patterns/test/v21/test_validator.py::test_fail_patterns[[artifact:payload_bin", "stix2patterns/test/v21/test_validator.py::test_fail_patterns[[foo:bar=1]", "stix2patterns/test/v21/test_validator.py::test_fail_patterns[[file:hashes.'SHA-256'", "stix2patterns/test/v21/test_validator.py::test_fail_patterns[([win-registry-key:key", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[file:size", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[file:file_name", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[file:extended_properties.'ntfs-ext'.sid", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[emailaddr:value", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[ipv4addr:value", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[user-account:value", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[file:file_system_properties.file_name", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[network-connection:extended_properties[0].source_payload", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[win-registry-key:key", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[x_whatever:detected", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[artifact:payload_bin", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[foo:bar=1]", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[network-traffic:start", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[(", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[([win-registry-key:key", "stix2patterns/test/v21/test_validator.py::test_pass_patterns[[network-traffic:src_port" ]
2020-07-09 20:10:52+00:00
4,274
oasis-open__cti-pattern-validator-81
diff --git a/stix2patterns/helpers.py b/stix2patterns/helpers.py index 1cd284c..177890d 100644 --- a/stix2patterns/helpers.py +++ b/stix2patterns/helpers.py @@ -1,22 +1,29 @@ -import string +import six -def leading_characters(s, length): +def brackets_check(pattern): """ - Returns non-whitespace leading characters + Check whether the pattern is missing square brackets, in a way which does + not require the usual parsing. This is a light hack to provide an improved + error message in this particular case. - :param str s: The string to process - :param int length: The number of characters to return - :return: The non-whitespace leading characters - :rtype: str or None + :param pattern: A STIX pattern string + :return: True if the pattern had its brackets; False if not """ - if s is None: - return None + if isinstance(pattern, six.string_types): - stripped = [] - for char in s: - if char not in string.whitespace: - stripped.append(char) + # There can be an arbitrary number of open parens first... skip over + # those + for c in pattern: + if c != "(" and not c.isspace(): + break - upper_bound = min(length, len(stripped)) - return ''.join(stripped[:upper_bound]) + if c == "[": + result = True + else: + result = False + + else: + result = False + + return result diff --git a/stix2patterns/v20/object_validator.py b/stix2patterns/v20/object_validator.py index 72f051c..d92d34a 100644 --- a/stix2patterns/v20/object_validator.py +++ b/stix2patterns/v20/object_validator.py @@ -1,4 +1,5 @@ import re + import stix2patterns.inspector HASHES_REGEX = { diff --git a/stix2patterns/v20/validator.py b/stix2patterns/v20/validator.py index b1cf78a..8520cea 100644 --- a/stix2patterns/v20/validator.py +++ b/stix2patterns/v20/validator.py @@ -11,7 +11,7 @@ from .grammars.STIXPatternParser import STIXPatternParser from .inspector import InspectionListener -def run_validator(pattern, start): +def run_validator(pattern): """ Validates a pattern against the STIX Pattern grammar. Error messages are returned in a list. The test passed if the returned list is empty. @@ -40,11 +40,6 @@ def run_validator(pattern, start): tree = parser.pattern() inspection_listener = InspectionListener() - # replace with easier-to-understand error message - if not (start[0] == '[' or start == '(['): - parseErrListener.err_strings.insert(0, "FAIL: Error found at line 1:0. " - "input is missing square brackets") - # validate observed objects if len(parseErrListener.err_strings) == 0: ParseTreeWalker.DEFAULT.walk(inspection_listener, tree) diff --git a/stix2patterns/v21/object_validator.py b/stix2patterns/v21/object_validator.py index 7558ba5..145d957 100644 --- a/stix2patterns/v21/object_validator.py +++ b/stix2patterns/v21/object_validator.py @@ -1,4 +1,5 @@ import re + import stix2patterns.inspector HASHES_REGEX = { diff --git a/stix2patterns/v21/validator.py b/stix2patterns/v21/validator.py index 11adaed..ac284f0 100644 --- a/stix2patterns/v21/validator.py +++ b/stix2patterns/v21/validator.py @@ -66,7 +66,7 @@ class ValidationListener(STIXPatternListener): self.__check_qualifier_type(QualType.STARTSTOP) -def run_validator(pattern, start): +def run_validator(pattern): """ Validates a pattern against the STIX Pattern grammar. Error messages are returned in a list. The test passed if the returned list is empty. @@ -94,11 +94,6 @@ def run_validator(pattern, start): tree = parser.pattern() - # replace with easier-to-understand error message - if not (start[0] == '[' or start == '(['): - parseErrListener.err_strings.insert(0, "FAIL: Error found at line 1:0. " - "input is missing square brackets") - # validate observed objects if len(parseErrListener.err_strings) == 0: inspection_listener = InspectionListener() diff --git a/stix2patterns/validator.py b/stix2patterns/validator.py index 45e1634..48dea76 100644 --- a/stix2patterns/validator.py +++ b/stix2patterns/validator.py @@ -11,7 +11,7 @@ import six from . import DEFAULT_VERSION from .exceptions import STIXPatternErrorListener # noqa: F401 -from .helpers import leading_characters +from .helpers import brackets_check from .v20.validator import run_validator as run_validator20 from .v21.validator import run_validator as run_validator21 @@ -21,19 +21,26 @@ def run_validator(pattern, stix_version=DEFAULT_VERSION): Validates a pattern against the STIX Pattern grammar. Error messages are returned in a list. The test passed if the returned list is empty. """ - start = '' if isinstance(pattern, six.string_types): - start = leading_characters(pattern, 2) + pattern_str = pattern pattern = InputStream(pattern) - if not start: - start = leading_characters(pattern.readline(), 2) + else: + pattern_str = pattern.readline() pattern.seek(0) if stix_version == '2.1': - return run_validator21(pattern, start) + err_messages = run_validator21(pattern) else: - return run_validator20(pattern, start) + err_messages = run_validator20(pattern) + + if not brackets_check(pattern_str): + err_messages.insert( + 0, + "FAIL: Error found at line 1:0. input is missing square brackets" + ) + + return err_messages def validate(user_input, stix_version=DEFAULT_VERSION, ret_errs=False, print_errs=False):
oasis-open/cti-pattern-validator
2dafa44d3ea37faefaaa92e703f2ac481485de31
diff --git a/stix2patterns/test/test_helpers.py b/stix2patterns/test/test_helpers.py index 06c621e..7e15846 100644 --- a/stix2patterns/test/test_helpers.py +++ b/stix2patterns/test/test_helpers.py @@ -1,14 +1,33 @@ """ Test cases for stix2patterns/helpers.py. """ +import pytest -from stix2patterns.helpers import leading_characters +from stix2patterns.helpers import brackets_check -def test_leading_characters(): [email protected]( + "value", [ + '[file:size = 1280]', + ' [file:size = 1280]', + '( [file:size = 1280])', + '( ( [file:size = 1280]) )', + '(( ( ( [file:size = 1280])) ))', + '[', + ], +) +def test_brackets_check(value): + assert brackets_check(value) - assert leading_characters('[file:size = 1280]', 2) == '[f' - assert leading_characters(' [file:size = 1280]', 2) == '[f' - assert leading_characters('( [file:size = 1280])', 2) == '([' - assert leading_characters('[', 2) == '[' - assert leading_characters(None, 2) is None + [email protected]( + "value", [ + None, + "file:size = 1280", + "(file:size = 1280)", + " ( file:size = 1280 ) ", + " (( (( file:size = 1280 ) )) ) ", + ] +) +def test_brackets_check_fail(value): + assert not brackets_check(None)
Brackets check doesn't account for arbitrary nested parentheses There is code to add a simpler error message in one particular case: when the user has forgotten square brackets around the pattern. But it is *too* specific: it requires that patterns start with either `[` or `([`: https://github.com/oasis-open/cti-pattern-validator/blob/2dafa44d3ea37faefaaa92e703f2ac481485de31/stix2patterns/v21/validator.py#L98 Patterns can have arbitrarily nested structure, so the pattern can start with an arbitrary number of open parentheses. The check needs to be generalized.
0.0
[ "stix2patterns/test/test_helpers.py::test_brackets_check[[file:size", "stix2patterns/test/test_helpers.py::test_brackets_check[", "stix2patterns/test/test_helpers.py::test_brackets_check[(", "stix2patterns/test/test_helpers.py::test_brackets_check[((", "stix2patterns/test/test_helpers.py::test_brackets_check[[]", "stix2patterns/test/test_helpers.py::test_brackets_check_fail[None]", "stix2patterns/test/test_helpers.py::test_brackets_check_fail[file:size", "stix2patterns/test/test_helpers.py::test_brackets_check_fail[(file:size", "stix2patterns/test/test_helpers.py::test_brackets_check_fail[" ]
[]
2020-09-15 21:11:27+00:00
4,275
oasis-open__cti-python-stix2-10
diff --git a/stix2/common.py b/stix2/common.py index 29cbf62..c8c243d 100644 --- a/stix2/common.py +++ b/stix2/common.py @@ -2,7 +2,7 @@ from .other import ExternalReference, GranularMarking from .properties import (BooleanProperty, ListProperty, ReferenceProperty, - TimestampProperty) + StringProperty, TimestampProperty) from .utils import NOW COMMON_PROPERTIES = { @@ -11,6 +11,7 @@ COMMON_PROPERTIES = { 'modified': TimestampProperty(default=lambda: NOW), 'external_references': ListProperty(ExternalReference), 'revoked': BooleanProperty(), + 'labels': ListProperty(StringProperty), 'created_by_ref': ReferenceProperty(type="identity"), 'object_marking_refs': ListProperty(ReferenceProperty(type="marking-definition")), 'granular_markings': ListProperty(GranularMarking), diff --git a/stix2/sdo.py b/stix2/sdo.py index 693b750..a2f0062 100644 --- a/stix2/sdo.py +++ b/stix2/sdo.py @@ -57,7 +57,6 @@ class Identity(_STIXBase): _properties.update({ 'type': TypeProperty(_type), 'id': IDProperty(_type), - 'labels': ListProperty(StringProperty), 'name': StringProperty(required=True), 'description': StringProperty(), 'identity_class': StringProperty(required=True),
oasis-open/cti-python-stix2
85b5a1971b0f36c3acaa0d3da734329bdd8ebe0b
diff --git a/stix2/test/test_attack_pattern.py b/stix2/test/test_attack_pattern.py index c0891a5..618875e 100644 --- a/stix2/test/test_attack_pattern.py +++ b/stix2/test/test_attack_pattern.py @@ -67,4 +67,15 @@ def test_parse_attack_pattern(data): assert ap.external_references[0].source_name == 'capec' assert ap.name == "Spear Phishing" + +def test_attack_pattern_invalid_labels(): + with pytest.raises(stix2.exceptions.InvalidValueError): + stix2.AttackPattern( + id="attack-pattern--0c7b5b88-8ff7-4a4d-aa9d-feb398cd0061", + created="2016-05-12T08:17:27Z", + modified="2016-05-12T08:17:27Z", + name="Spear Phishing", + labels=1 + ) + # TODO: Add other examples
is labels optional Hi, As an exercise I'm starting a similar Scala library for STIX 2.1, at: [scalastix]( https://github.com/workingDog/scalastix) According to the specs and as part of the common properties, labels is optional. However, there are SDOs (e.g. Indicator) where it is required. Is this correct? labels are optional but not when required! I see that labels are not part of the python COMMON_PROPERTIES. Should I do the same?
0.0
[ "stix2/test/test_attack_pattern.py::test_attack_pattern_invalid_labels" ]
[ "stix2/test/test_attack_pattern.py::test_attack_pattern_example", "stix2/test/test_attack_pattern.py::test_parse_attack_pattern[{\\n", "stix2/test/test_attack_pattern.py::test_parse_attack_pattern[data1]" ]
2017-05-15 15:03:14+00:00
4,276
oasis-open__cti-python-stix2-127
diff --git a/stix2/base.py b/stix2/base.py index 76b07b8..fc13094 100644 --- a/stix2/base.py +++ b/stix2/base.py @@ -161,9 +161,12 @@ class _STIXBase(collections.Mapping): ", ".join(["{0!s}={1!r}".format(k, v) for k, v in props])) def __deepcopy__(self, memo): - # Assumption: we can ignore the memo argument, because no object will ever contain the same sub-object multiple times. + # Assume: we can ignore the memo argument, because no object will ever contain the same sub-object multiple times. new_inner = copy.deepcopy(self._inner, memo) cls = type(self) + if isinstance(self, _Observable): + # Assume: valid references in the original object are still valid in the new version + new_inner['_valid_refs'] = {'*': '*'} return cls(**new_inner) def properties_populated(self): @@ -221,6 +224,9 @@ class _Observable(_STIXBase): super(_Observable, self).__init__(**kwargs) def _check_ref(self, ref, prop, prop_name): + if '*' in self._STIXBase__valid_refs: + return # don't check if refs are valid + if ref not in self._STIXBase__valid_refs: raise InvalidObjRefError(self.__class__, prop_name, "'%s' is not a valid object in local scope" % ref)
oasis-open/cti-python-stix2
b1a020bb38d74c407ac125b1e032850acfe7a880
diff --git a/stix2/test/test_observed_data.py b/stix2/test/test_observed_data.py index 3029b68..30c3cab 100644 --- a/stix2/test/test_observed_data.py +++ b/stix2/test/test_observed_data.py @@ -1162,3 +1162,25 @@ def test_x509_certificate_example(): assert x509.type == "x509-certificate" assert x509.issuer == "C=ZA, ST=Western Cape, L=Cape Town, O=Thawte Consulting cc, OU=Certification Services Division, CN=Thawte Server CA/[email protected]" # noqa assert x509.subject == "C=US, ST=Maryland, L=Pasadena, O=Brent Baccala, OU=FreeSoft, CN=www.freesoft.org/[email protected]" # noqa + + +def test_new_version_with_related_objects(): + data = stix2.ObservedData( + first_observed="2016-03-12T12:00:00Z", + last_observed="2016-03-12T12:00:00Z", + number_observed=1, + objects={ + 'src_ip': { + 'type': 'ipv4-addr', + 'value': '127.0.0.1/32' + }, + 'domain': { + 'type': 'domain-name', + 'value': 'example.com', + 'resolves_to_refs': ['src_ip'] + } + } + ) + new_version = data.new_version(last_observed="2017-12-12T12:00:00Z") + assert new_version.last_observed.year == 2017 + assert new_version.objects['domain'].resolves_to_refs[0] == 'src_ip'
Fail to create new version of ObservedData if it has related objects If you try to generate a new version of an ObservedData which contains related objects (like domain-name -> ipv4) you obtain a fatal error Example: `from stix2 import ObservedData` `from datetime import datetime` `data = ObservedData(first_observed=datetime.now(),last_observed=datetime.now(),number_observed=1,objects={'src_ip': {'type':'ipv4-addr','value':'127.0.0.1/32'}, 'domain':{'type':'domain-name','value':'example.com','resolves_to_refs':['src_ip']}})` `new_version = data.new_version(last_observed=datetime.now())` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.6/site-packages/stix2/base.py", line 175, in new_version return _new_version(self, **kwargs) File "/usr/local/lib/python3.6/site-packages/stix2/utils.py", line 212, in new_version new_obj_inner = copy.deepcopy(data._inner) File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/copy.py", line 150, in deepcopy y = copier(x, memo) File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/copy.py", line 240, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/copy.py", line 150, in deepcopy y = copier(x, memo) File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/copy.py", line 240, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/copy.py", line 161, in deepcopy y = copier(memo) File "/usr/local/lib/python3.6/site-packages/stix2/base.py", line 167, in __deepcopy__ return cls(**new_inner) File "/usr/local/lib/python3.6/site-packages/stix2/base.py", line 221, in __init__ super(_Observable, self).__init__(**kwargs) File "/usr/local/lib/python3.6/site-packages/stix2/base.py", line 128, in __init__ self._check_property(prop_name, prop_metadata, setting_kwargs) File "/usr/local/lib/python3.6/site-packages/stix2/base.py", line 251, in _check_property self._check_ref(ref, prop, prop_name) File "/usr/local/lib/python3.6/site-packages/stix2/base.py", line 225, in _check_ref raise InvalidObjRefError(self.__class__, prop_name, "'%s' is not a valid object in local scope" % ref)` The error appears also if you use an incremental value as index in objects dictionary
0.0
[ "stix2/test/test_observed_data.py::test_new_version_with_related_objects" ]
[ "stix2/test/test_observed_data.py::test_observed_data_example", "stix2/test/test_observed_data.py::test_observed_data_example_with_refs", "stix2/test/test_observed_data.py::test_observed_data_example_with_bad_refs", "stix2/test/test_observed_data.py::test_observed_data_example_with_non_dictionary", "stix2/test/test_observed_data.py::test_observed_data_example_with_empty_dictionary", "stix2/test/test_observed_data.py::test_parse_observed_data[{\\n", "stix2/test/test_observed_data.py::test_parse_observed_data[data1]", "stix2/test/test_observed_data.py::test_parse_artifact_valid[\"0\":", "stix2/test/test_observed_data.py::test_parse_artifact_invalid[\"0\":", "stix2/test/test_observed_data.py::test_artifact_example_dependency_error", "stix2/test/test_observed_data.py::test_parse_autonomous_system_valid[\"0\":", "stix2/test/test_observed_data.py::test_parse_email_address[{\\n", "stix2/test/test_observed_data.py::test_parse_email_message[\\n", "stix2/test/test_observed_data.py::test_parse_email_message_not_multipart[\\n", "stix2/test/test_observed_data.py::test_parse_file_archive[\"0\":", "stix2/test/test_observed_data.py::test_parse_email_message_with_at_least_one_error[\\n", "stix2/test/test_observed_data.py::test_parse_basic_tcp_traffic[\\n", "stix2/test/test_observed_data.py::test_parse_basic_tcp_traffic_with_error[\\n", "stix2/test/test_observed_data.py::test_observed_data_with_process_example", "stix2/test/test_observed_data.py::test_artifact_example", "stix2/test/test_observed_data.py::test_artifact_mutual_exclusion_error", "stix2/test/test_observed_data.py::test_directory_example", "stix2/test/test_observed_data.py::test_directory_example_ref_error", "stix2/test/test_observed_data.py::test_domain_name_example", "stix2/test/test_observed_data.py::test_domain_name_example_invalid_ref_type", "stix2/test/test_observed_data.py::test_file_example", "stix2/test/test_observed_data.py::test_file_example_with_NTFSExt", "stix2/test/test_observed_data.py::test_file_example_with_empty_NTFSExt", "stix2/test/test_observed_data.py::test_file_example_with_PDFExt", "stix2/test/test_observed_data.py::test_file_example_with_PDFExt_Object", "stix2/test/test_observed_data.py::test_file_example_with_RasterImageExt_Object", "stix2/test/test_observed_data.py::test_file_example_with_WindowsPEBinaryExt", "stix2/test/test_observed_data.py::test_file_example_encryption_error", "stix2/test/test_observed_data.py::test_ip4_address_example", "stix2/test/test_observed_data.py::test_ip4_address_example_cidr", "stix2/test/test_observed_data.py::test_ip6_address_example", "stix2/test/test_observed_data.py::test_mac_address_example", "stix2/test/test_observed_data.py::test_network_traffic_example", "stix2/test/test_observed_data.py::test_network_traffic_http_request_example", "stix2/test/test_observed_data.py::test_network_traffic_icmp_example", "stix2/test/test_observed_data.py::test_network_traffic_socket_example", "stix2/test/test_observed_data.py::test_network_traffic_tcp_example", "stix2/test/test_observed_data.py::test_mutex_example", "stix2/test/test_observed_data.py::test_process_example", "stix2/test/test_observed_data.py::test_process_example_empty_error", "stix2/test/test_observed_data.py::test_process_example_empty_with_extensions", "stix2/test/test_observed_data.py::test_process_example_windows_process_ext", "stix2/test/test_observed_data.py::test_process_example_windows_process_ext_empty", "stix2/test/test_observed_data.py::test_process_example_extensions_empty", "stix2/test/test_observed_data.py::test_process_example_with_WindowsProcessExt_Object", "stix2/test/test_observed_data.py::test_process_example_with_WindowsServiceExt", "stix2/test/test_observed_data.py::test_process_example_with_WindowsProcessServiceExt", "stix2/test/test_observed_data.py::test_software_example", "stix2/test/test_observed_data.py::test_url_example", "stix2/test/test_observed_data.py::test_user_account_example", "stix2/test/test_observed_data.py::test_user_account_unix_account_ext_example", "stix2/test/test_observed_data.py::test_windows_registry_key_example", "stix2/test/test_observed_data.py::test_x509_certificate_example" ]
2018-02-19 20:07:31+00:00
4,277
oasis-open__cti-python-stix2-133
diff --git a/stix2/markings/granular_markings.py b/stix2/markings/granular_markings.py index be5d258..7c227d9 100644 --- a/stix2/markings/granular_markings.py +++ b/stix2/markings/granular_markings.py @@ -116,9 +116,9 @@ def remove_markings(obj, marking, selectors): granular_markings = utils.compress_markings(granular_markings) if granular_markings: - return new_version(obj, granular_markings=granular_markings) + return new_version(obj, granular_markings=granular_markings, allow_custom=True) else: - return new_version(obj, granular_markings=None) + return new_version(obj, granular_markings=None, allow_custom=True) def add_markings(obj, marking, selectors): @@ -152,7 +152,7 @@ def add_markings(obj, marking, selectors): granular_marking = utils.expand_markings(granular_marking) granular_marking = utils.compress_markings(granular_marking) - return new_version(obj, granular_markings=granular_marking) + return new_version(obj, granular_markings=granular_marking, allow_custom=True) def clear_markings(obj, selectors): @@ -207,9 +207,9 @@ def clear_markings(obj, selectors): granular_markings = utils.compress_markings(granular_markings) if granular_markings: - return new_version(obj, granular_markings=granular_markings) + return new_version(obj, granular_markings=granular_markings, allow_custom=True) else: - return new_version(obj, granular_markings=None) + return new_version(obj, granular_markings=None, allow_custom=True) def is_marked(obj, marking=None, selectors=None, inherited=False, descendants=False): diff --git a/stix2/markings/object_markings.py b/stix2/markings/object_markings.py index c0375c3..a169fe3 100644 --- a/stix2/markings/object_markings.py +++ b/stix2/markings/object_markings.py @@ -37,7 +37,7 @@ def add_markings(obj, marking): object_markings = set(obj.get("object_marking_refs", []) + marking) - return new_version(obj, object_marking_refs=list(object_markings)) + return new_version(obj, object_marking_refs=list(object_markings), allow_custom=True) def remove_markings(obj, marking): @@ -69,9 +69,9 @@ def remove_markings(obj, marking): new_markings = [x for x in object_markings if x not in marking] if new_markings: - return new_version(obj, object_marking_refs=new_markings) + return new_version(obj, object_marking_refs=new_markings, allow_custom=True) else: - return new_version(obj, object_marking_refs=None) + return new_version(obj, object_marking_refs=None, allow_custom=True) def set_markings(obj, marking): @@ -103,7 +103,7 @@ def clear_markings(obj): A new version of the given SDO or SRO with object_marking_refs cleared. """ - return new_version(obj, object_marking_refs=None) + return new_version(obj, object_marking_refs=None, allow_custom=True) def is_marked(obj, marking=None): diff --git a/stix2/utils.py b/stix2/utils.py index 73337d0..37ff166 100644 --- a/stix2/utils.py +++ b/stix2/utils.py @@ -251,7 +251,7 @@ def revoke(data): if data.get("revoked"): raise RevokeError("revoke") - return new_version(data, revoked=True) + return new_version(data, revoked=True, allow_custom=True) def get_class_hierarchy_names(obj):
oasis-open/cti-python-stix2
4a9c38e0b50415f4733072fc76eb8ebd0749c84b
diff --git a/stix2/test/test_custom.py b/stix2/test/test_custom.py index 7c1832b..76ad61b 100644 --- a/stix2/test/test_custom.py +++ b/stix2/test/test_custom.py @@ -2,7 +2,14 @@ import pytest import stix2 -from .constants import FAKE_TIME +from .constants import FAKE_TIME, MARKING_DEFINITION_ID + +IDENTITY_CUSTOM_PROP = stix2.Identity( + name="John Smith", + identity_class="individual", + x_foo="bar", + allow_custom=True, +) def test_identity_custom_property(): @@ -82,18 +89,38 @@ def test_parse_identity_custom_property(data): def test_custom_property_in_bundled_object(): - identity = stix2.Identity( - name="John Smith", - identity_class="individual", - x_foo="bar", - allow_custom=True, - ) - bundle = stix2.Bundle(identity, allow_custom=True) + bundle = stix2.Bundle(IDENTITY_CUSTOM_PROP, allow_custom=True) assert bundle.objects[0].x_foo == "bar" assert '"x_foo": "bar"' in str(bundle) +def test_identity_custom_property_revoke(): + identity = IDENTITY_CUSTOM_PROP.revoke() + assert identity.x_foo == "bar" + + +def test_identity_custom_property_edit_markings(): + marking_obj = stix2.MarkingDefinition( + id=MARKING_DEFINITION_ID, + definition_type="statement", + definition=stix2.StatementMarking(statement="Copyright 2016, Example Corp") + ) + marking_obj2 = stix2.MarkingDefinition( + id=MARKING_DEFINITION_ID, + definition_type="statement", + definition=stix2.StatementMarking(statement="Another one") + ) + + # None of the following should throw exceptions + identity = IDENTITY_CUSTOM_PROP.add_markings(marking_obj) + identity2 = identity.add_markings(marking_obj2, ['x_foo']) + identity2.remove_markings(marking_obj.id) + identity2.remove_markings(marking_obj2.id, ['x_foo']) + identity2.clear_markings() + identity2.clear_markings('x_foo') + + def test_custom_marking_no_init_1(): @stix2.CustomMarking('x-new-obj', [ ('property1', stix2.properties.StringProperty(required=True)),
Calling add_markings on a existing STIX object with custom properties causes an exception Here is the stack trace: Traceback (most recent call last): ``` File "/Users/rpiazza/projects/capec-attack/capec2stix/capec2stix.py", line 197, in <module> main() File "/Users/rpiazza/projects/capec-attack/capec2stix/capec2stix.py", line 189, in main tlos = convert2stix(attack_pattern_catalog, marking_def.id, ident.id) File "/Users/rpiazza/projects/capec-attack/capec2stix/capec2stix.py", line 170, in convert2stix return convert_attack_pattern(attack_pattern_catalog.Attack_Patterns.Attack_Pattern[0], marking_def_id, ident_id) File "/Users/rpiazza/projects/capec-attack/capec2stix/capec2stix.py", line 158, in convert_attack_pattern ap.add_markings(marking_def_id) File "/Users/rpiazza/py-envs/python3.5/lib/python3.5/site-packages/stix2/markings/__init__.py", line 143, in add_markings return object_markings.add_markings(obj, marking) File "/Users/rpiazza/py-envs/python3.5/lib/python3.5/site-packages/stix2/markings/object_markings.py", line 40, in add_markings return new_version(obj, object_marking_refs=list(object_markings)) File "/Users/rpiazza/py-envs/python3.5/lib/python3.5/site-packages/stix2/utils.py", line 234, in new_version return cls(**{k: v for k, v in new_obj_inner.items() if v is not None}) File "/Users/rpiazza/py-envs/python3.5/lib/python3.5/site-packages/stix2/base.py", line 111, in __init__ raise ExtraPropertiesError(cls, extra_kwargs) stix2.exceptions.ExtraPropertiesError: Unexpected properties for AttackPattern: (x_capec_abstraction, x_capec_consequences, x_capec_example_instances, x_capec_likelihood_of_attack, x_capec_prerequisites, x_capec_skills_required, x_capec_typical_severity, x_resources_required). ```
0.0
[ "stix2/test/test_custom.py::test_identity_custom_property_revoke", "stix2/test/test_custom.py::test_identity_custom_property_edit_markings" ]
[ "stix2/test/test_custom.py::test_identity_custom_property", "stix2/test/test_custom.py::test_identity_custom_property_invalid", "stix2/test/test_custom.py::test_identity_custom_property_allowed", "stix2/test/test_custom.py::test_parse_identity_custom_property[{\\n", "stix2/test/test_custom.py::test_custom_property_in_bundled_object", "stix2/test/test_custom.py::test_custom_object_raises_exception", "stix2/test/test_custom.py::test_custom_object_type", "stix2/test/test_custom.py::test_parse_custom_object_type", "stix2/test/test_custom.py::test_parse_unregistered_custom_object_type", "stix2/test/test_custom.py::test_custom_observable_object_1", "stix2/test/test_custom.py::test_custom_observable_object_2", "stix2/test/test_custom.py::test_custom_observable_object_3", "stix2/test/test_custom.py::test_custom_observable_raises_exception", "stix2/test/test_custom.py::test_custom_observable_object_invalid_ref_property", "stix2/test/test_custom.py::test_custom_observable_object_invalid_refs_property", "stix2/test/test_custom.py::test_custom_observable_object_invalid_refs_list_property", "stix2/test/test_custom.py::test_custom_observable_object_invalid_valid_refs", "stix2/test/test_custom.py::test_custom_no_properties_raises_exception", "stix2/test/test_custom.py::test_custom_wrong_properties_arg_raises_exception", "stix2/test/test_custom.py::test_parse_unregistered_custom_observable_object", "stix2/test/test_custom.py::test_parse_invalid_custom_observable_object", "stix2/test/test_custom.py::test_observable_custom_property", "stix2/test/test_custom.py::test_observable_custom_property_invalid", "stix2/test/test_custom.py::test_observable_custom_property_allowed", "stix2/test/test_custom.py::test_custom_extension_raises_exception", "stix2/test/test_custom.py::test_custom_extension", "stix2/test/test_custom.py::test_custom_extension_wrong_observable_type", "stix2/test/test_custom.py::test_custom_extension_invalid_observable", "stix2/test/test_custom.py::test_custom_extension_no_properties", "stix2/test/test_custom.py::test_custom_extension_empty_properties", "stix2/test/test_custom.py::test_parse_observable_with_custom_extension", "stix2/test/test_custom.py::test_parse_observable_with_unregistered_custom_extension", "stix2/test/test_custom.py::test_register_custom_object" ]
2018-03-02 16:37:42+00:00
4,278
oasis-open__cti-python-stix2-145
diff --git a/stix2/datastore/filesystem.py b/stix2/datastore/filesystem.py index 26d0c58..b525932 100644 --- a/stix2/datastore/filesystem.py +++ b/stix2/datastore/filesystem.py @@ -301,11 +301,27 @@ class FileSystemSource(DataSource): for path in include_paths: for root, dirs, files in os.walk(path): for file_ in files: + if not file_.endswith(".json"): + # skip non '.json' files as more likely to be random non-STIX files + continue + if not id_ or id_ == file_.split(".")[0]: # have to load into memory regardless to evaluate other filters - stix_obj = json.load(open(os.path.join(root, file_))) - if stix_obj.get('type', '') == 'bundle': - stix_obj = stix_obj['objects'][0] + try: + stix_obj = json.load(open(os.path.join(root, file_))) + + if stix_obj["type"] == "bundle": + stix_obj = stix_obj["objects"][0] + + # naive STIX type checking + stix_obj["type"] + stix_obj["id"] + + except (ValueError, KeyError): # likely not a JSON file + print("filesytem TypeError raised") + raise TypeError("STIX JSON object at '{0}' could either not be parsed to " + "JSON or was not valid STIX JSON".format(os.path.join(root, file_))) + # check against other filters, add if match all_data.extend(apply_common_filters([stix_obj], query))
oasis-open/cti-python-stix2
33cfc4bb2786e6da0960bdaf9c8d19e4daebd938
diff --git a/stix2/test/test_filesystem.py b/stix2/test/test_filesystem.py index 020fee5..f59136e 100644 --- a/stix2/test/test_filesystem.py +++ b/stix2/test/test_filesystem.py @@ -1,3 +1,4 @@ +import json import os import shutil @@ -45,6 +46,41 @@ def fs_sink(): shutil.rmtree(os.path.join(FS_PATH, "campaign"), True) [email protected] +def bad_json_files(): + # create erroneous JSON files for tests to make sure handled gracefully + + with open(os.path.join(FS_PATH, "intrusion-set", "intrusion-set--test-non-json.txt"), "w+") as f: + f.write("Im not a JSON file") + + with open(os.path.join(FS_PATH, "intrusion-set", "intrusion-set--test-bad-json.json"), "w+") as f: + f.write("Im not a JSON formatted file") + + yield True # dummy yield so can have teardown + + os.remove(os.path.join(FS_PATH, "intrusion-set", "intrusion-set--test-non-json.txt")) + os.remove(os.path.join(FS_PATH, "intrusion-set", "intrusion-set--test-bad-json.json")) + + [email protected] +def bad_stix_files(): + # create erroneous STIX JSON files for tests to make sure handled correctly + + # bad STIX object + stix_obj = { + "id": "intrusion-set--test-bad-stix", + "spec_version": "2.0" + # no "type" field + } + + with open(os.path.join(FS_PATH, "intrusion-set", "intrusion-set--test-non-stix.json"), "w+") as f: + f.write(json.dumps(stix_obj)) + + yield True # dummy yield so can have teardown + + os.remove(os.path.join(FS_PATH, "intrusion-set", "intrusion-set--test-non-stix.json")) + + @pytest.fixture(scope='module') def rel_fs_store(): cam = Campaign(id=CAMPAIGN_ID, **CAMPAIGN_KWARGS) @@ -76,6 +112,26 @@ def test_filesystem_sink_nonexistent_folder(): assert "for STIX data does not exist" in str(excinfo) +def test_filesystem_source_bad_json_file(fs_source, bad_json_files): + # this tests the handling of two bad json files + # - one file should just be skipped (silently) as its a ".txt" extension + # - one file should be parsed and raise Exception bc its not JSON + try: + fs_source.get("intrusion-set--test-bad-json") + except TypeError as e: + assert "intrusion-set--test-bad-json" in str(e) + assert "could either not be parsed to JSON or was not valid STIX JSON" in str(e) + + +def test_filesystem_source_bad_stix_file(fs_source, bad_stix_files): + # this tests handling of bad STIX json object + try: + fs_source.get("intrusion-set--test-non-stix") + except TypeError as e: + assert "intrusion-set--test-non-stix" in str(e) + assert "could either not be parsed to JSON or was not valid STIX JSON" in str(e) + + def test_filesytem_source_get_object(fs_source): # get object mal = fs_source.get("malware--6b616fc1-1505-48e3-8b2c-0d19337bff38")
Rundown status of existing issue: FileSystem query bug Bug: When querying FileSystem, it came back with JSON parse error. Specifically had to use a filter with “type” field to work. @mbastian1135 was trying to reproduce this, but having problems
0.0
[ "stix2/test/test_filesystem.py::test_filesystem_source_bad_json_file" ]
[ "stix2/test/test_filesystem.py::test_filesystem_source_nonexistent_folder", "stix2/test/test_filesystem.py::test_filesystem_sink_nonexistent_folder", "stix2/test/test_filesystem.py::test_filesystem_source_bad_stix_file", "stix2/test/test_filesystem.py::test_filesytem_source_get_object", "stix2/test/test_filesystem.py::test_filesytem_source_get_nonexistent_object", "stix2/test/test_filesystem.py::test_filesytem_source_all_versions", "stix2/test/test_filesystem.py::test_filesytem_source_query_single", "stix2/test/test_filesystem.py::test_filesytem_source_query_multiple", "stix2/test/test_filesystem.py::test_filesystem_sink_add_python_stix_object", "stix2/test/test_filesystem.py::test_filesystem_sink_add_stix_object_dict", "stix2/test/test_filesystem.py::test_filesystem_sink_add_stix_bundle_dict", "stix2/test/test_filesystem.py::test_filesystem_sink_add_json_stix_object", "stix2/test/test_filesystem.py::test_filesystem_sink_json_stix_bundle", "stix2/test/test_filesystem.py::test_filesystem_sink_add_objects_list", "stix2/test/test_filesystem.py::test_filesystem_store_get_stored_as_bundle", "stix2/test/test_filesystem.py::test_filesystem_store_get_stored_as_object", "stix2/test/test_filesystem.py::test_filesystem_store_all_versions", "stix2/test/test_filesystem.py::test_filesystem_store_query", "stix2/test/test_filesystem.py::test_filesystem_store_query_single_filter", "stix2/test/test_filesystem.py::test_filesystem_store_empty_query", "stix2/test/test_filesystem.py::test_filesystem_store_query_multiple_filters", "stix2/test/test_filesystem.py::test_filesystem_store_query_dont_include_type_folder", "stix2/test/test_filesystem.py::test_filesystem_store_add", "stix2/test/test_filesystem.py::test_filesystem_store_add_as_bundle", "stix2/test/test_filesystem.py::test_filesystem_add_bundle_object", "stix2/test/test_filesystem.py::test_filesystem_store_add_invalid_object", "stix2/test/test_filesystem.py::test_filesystem_object_with_custom_property", "stix2/test/test_filesystem.py::test_filesystem_object_with_custom_property_in_bundle", "stix2/test/test_filesystem.py::test_relationships", "stix2/test/test_filesystem.py::test_relationships_by_type", "stix2/test/test_filesystem.py::test_relationships_by_source", "stix2/test/test_filesystem.py::test_relationships_by_target", "stix2/test/test_filesystem.py::test_relationships_by_target_and_type", "stix2/test/test_filesystem.py::test_relationships_by_target_and_source", "stix2/test/test_filesystem.py::test_related_to", "stix2/test/test_filesystem.py::test_related_to_by_source", "stix2/test/test_filesystem.py::test_related_to_by_target" ]
2018-03-21 14:32:58+00:00
4,279
oasis-open__cti-python-stix2-164
diff --git a/stix2/base.py b/stix2/base.py index 898f489..3219007 100644 --- a/stix2/base.py +++ b/stix2/base.py @@ -6,9 +6,9 @@ import datetime as dt import simplejson as json -from .exceptions import (AtLeastOnePropertyError, DependentPropertiesError, - ExtraPropertiesError, ImmutableError, - InvalidObjRefError, InvalidValueError, +from .exceptions import (AtLeastOnePropertyError, CustomContentError, + DependentPropertiesError, ExtraPropertiesError, + ImmutableError, InvalidObjRefError, InvalidValueError, MissingPropertiesError, MutuallyExclusivePropertiesError) from .markings.utils import validate @@ -61,6 +61,8 @@ class _STIXBase(collections.Mapping): try: kwargs[prop_name] = prop.clean(kwargs[prop_name]) except ValueError as exc: + if self.__allow_custom and isinstance(exc, CustomContentError): + return raise InvalidValueError(self.__class__, prop_name, reason=str(exc)) # interproperty constraint methods @@ -97,6 +99,7 @@ class _STIXBase(collections.Mapping): def __init__(self, allow_custom=False, **kwargs): cls = self.__class__ + self.__allow_custom = allow_custom # Use the same timestamp for any auto-generated datetimes self.__now = get_timestamp() diff --git a/stix2/exceptions.py b/stix2/exceptions.py index 841a8e9..79c5a81 100644 --- a/stix2/exceptions.py +++ b/stix2/exceptions.py @@ -163,6 +163,13 @@ class ParseError(STIXError, ValueError): super(ParseError, self).__init__(msg) +class CustomContentError(STIXError, ValueError): + """Custom STIX Content (SDO, Observable, Extension, etc.) detected.""" + + def __init__(self, msg): + super(CustomContentError, self).__init__(msg) + + class InvalidSelectorError(STIXError, AssertionError): """Granular Marking selector violation. The selector must resolve into an existing STIX object property.""" diff --git a/stix2/v20/observables.py b/stix2/v20/observables.py index 39a8f19..f6bac2b 100644 --- a/stix2/v20/observables.py +++ b/stix2/v20/observables.py @@ -8,8 +8,8 @@ Observable and do not have a ``_type`` attribute. from collections import OrderedDict from ..base import _Extension, _Observable, _STIXBase -from ..exceptions import (AtLeastOnePropertyError, DependentPropertiesError, - ParseError) +from ..exceptions import (AtLeastOnePropertyError, CustomContentError, + DependentPropertiesError, ParseError) from ..properties import (BinaryProperty, BooleanProperty, DictionaryProperty, EmbeddedObjectProperty, EnumProperty, FloatProperty, HashesProperty, HexProperty, IntegerProperty, @@ -67,7 +67,7 @@ class ExtensionsProperty(DictionaryProperty): else: raise ValueError("Cannot determine extension type.") else: - raise ValueError("The key used in the extensions dictionary is not an extension type name") + raise CustomContentError("Can't parse unknown extension type: {}".format(key)) else: raise ValueError("The enclosing type '%s' has no extensions defined" % self.enclosing_type) return dictified @@ -923,15 +923,23 @@ def parse_observable(data, _valid_refs=None, allow_custom=False): try: obj_class = OBJ_MAP_OBSERVABLE[obj['type']] except KeyError: - raise ParseError("Can't parse unknown observable type '%s'! For custom observables, " - "use the CustomObservable decorator." % obj['type']) + if allow_custom: + # flag allows for unknown custom objects too, but will not + # be parsed into STIX observable object, just returned as is + return obj + raise CustomContentError("Can't parse unknown observable type '%s'! For custom observables, " + "use the CustomObservable decorator." % obj['type']) if 'extensions' in obj and obj['type'] in EXT_MAP: for name, ext in obj['extensions'].items(): - if name not in EXT_MAP[obj['type']]: - raise ParseError("Can't parse Unknown extension type '%s' for observable type '%s'!" % (name, obj['type'])) - ext_class = EXT_MAP[obj['type']][name] - obj['extensions'][name] = ext_class(allow_custom=allow_custom, **obj['extensions'][name]) + try: + ext_class = EXT_MAP[obj['type']][name] + except KeyError: + if not allow_custom: + raise CustomContentError("Can't parse unknown extension type '%s'" + "for observable type '%s'!" % (name, obj['type'])) + else: # extension was found + obj['extensions'][name] = ext_class(allow_custom=allow_custom, **obj['extensions'][name]) return obj_class(allow_custom=allow_custom, **obj)
oasis-open/cti-python-stix2
2d689815d743611a8f3ccd48ce5e2d1ec70695e5
diff --git a/stix2/test/test_custom.py b/stix2/test/test_custom.py index a14503f..f9bb875 100644 --- a/stix2/test/test_custom.py +++ b/stix2/test/test_custom.py @@ -363,6 +363,7 @@ def test_parse_custom_observable_object(): }""" nt = stix2.parse_observable(nt_string, []) + assert isinstance(nt, stix2.core._STIXBase) assert nt.property1 == 'something' @@ -372,10 +373,46 @@ def test_parse_unregistered_custom_observable_object(): "property1": "something" }""" - with pytest.raises(stix2.exceptions.ParseError) as excinfo: + with pytest.raises(stix2.exceptions.CustomContentError) as excinfo: stix2.parse_observable(nt_string) assert "Can't parse unknown observable type" in str(excinfo.value) + parsed_custom = stix2.parse_observable(nt_string, allow_custom=True) + assert parsed_custom['property1'] == 'something' + with pytest.raises(AttributeError) as excinfo: + assert parsed_custom.property1 == 'something' + assert not isinstance(parsed_custom, stix2.core._STIXBase) + + +def test_parse_unregistered_custom_observable_object_with_no_type(): + nt_string = """{ + "property1": "something" + }""" + + with pytest.raises(stix2.exceptions.ParseError) as excinfo: + stix2.parse_observable(nt_string, allow_custom=True) + assert "Can't parse observable with no 'type' property" in str(excinfo.value) + + +def test_parse_observed_data_with_custom_observable(): + input_str = """{ + "type": "observed-data", + "id": "observed-data--dc20c4ca-a2a3-4090-a5d5-9558c3af4758", + "created": "2016-04-06T19:58:16.000Z", + "modified": "2016-04-06T19:58:16.000Z", + "first_observed": "2015-12-21T19:00:00Z", + "last_observed": "2015-12-21T19:00:00Z", + "number_observed": 1, + "objects": { + "0": { + "type": "x-foobar-observable", + "property1": "something" + } + } + }""" + parsed = stix2.parse(input_str, allow_custom=True) + assert parsed.objects['0']['property1'] == 'something' + def test_parse_invalid_custom_observable_object(): nt_string = """{ @@ -591,7 +628,11 @@ def test_parse_observable_with_unregistered_custom_extension(): with pytest.raises(ValueError) as excinfo: stix2.parse_observable(input_str) - assert "Can't parse Unknown extension type" in str(excinfo.value) + assert "Can't parse unknown extension type" in str(excinfo.value) + + parsed_ob = stix2.parse_observable(input_str, allow_custom=True) + assert parsed_ob['extensions']['x-foobar-ext']['property1'] == 'foo' + assert not isinstance(parsed_ob['extensions']['x-foobar-ext'], stix2.core._STIXBase) def test_register_custom_object():
Allow generic custom objects for Cyber Observables The recent changes made to the library allows parsing generic custom objects, but `parse_observable()` does not have the feature implemented. https://github.com/oasis-open/cti-python-stix2/blob/master/stix2/v20/observables.py#L903 It also looks like we are **not** using `allow_custom` when we call it. https://github.com/oasis-open/cti-python-stix2/blob/master/stix2/v20/observables.py#L36
0.0
[ "stix2/test/test_custom.py::test_parse_unregistered_custom_observable_object", "stix2/test/test_custom.py::test_parse_observed_data_with_custom_observable", "stix2/test/test_custom.py::test_parse_observable_with_unregistered_custom_extension" ]
[ "stix2/test/test_custom.py::test_identity_custom_property", "stix2/test/test_custom.py::test_identity_custom_property_invalid", "stix2/test/test_custom.py::test_identity_custom_property_allowed", "stix2/test/test_custom.py::test_parse_identity_custom_property[{\\n", "stix2/test/test_custom.py::test_custom_property_in_bundled_object", "stix2/test/test_custom.py::test_identity_custom_property_revoke", "stix2/test/test_custom.py::test_identity_custom_property_edit_markings", "stix2/test/test_custom.py::test_custom_object_raises_exception", "stix2/test/test_custom.py::test_custom_object_type", "stix2/test/test_custom.py::test_parse_custom_object_type", "stix2/test/test_custom.py::test_parse_unregistered_custom_object_type", "stix2/test/test_custom.py::test_parse_unregistered_custom_object_type_w_allow_custom", "stix2/test/test_custom.py::test_custom_observable_object_1", "stix2/test/test_custom.py::test_custom_observable_object_2", "stix2/test/test_custom.py::test_custom_observable_object_3", "stix2/test/test_custom.py::test_custom_observable_raises_exception", "stix2/test/test_custom.py::test_custom_observable_object_invalid_ref_property", "stix2/test/test_custom.py::test_custom_observable_object_invalid_refs_property", "stix2/test/test_custom.py::test_custom_observable_object_invalid_refs_list_property", "stix2/test/test_custom.py::test_custom_observable_object_invalid_valid_refs", "stix2/test/test_custom.py::test_custom_no_properties_raises_exception", "stix2/test/test_custom.py::test_custom_wrong_properties_arg_raises_exception", "stix2/test/test_custom.py::test_parse_unregistered_custom_observable_object_with_no_type", "stix2/test/test_custom.py::test_parse_invalid_custom_observable_object", "stix2/test/test_custom.py::test_observable_custom_property", "stix2/test/test_custom.py::test_observable_custom_property_invalid", "stix2/test/test_custom.py::test_observable_custom_property_allowed", "stix2/test/test_custom.py::test_custom_extension_raises_exception", "stix2/test/test_custom.py::test_custom_extension", "stix2/test/test_custom.py::test_custom_extension_wrong_observable_type", "stix2/test/test_custom.py::test_custom_extension_invalid_observable", "stix2/test/test_custom.py::test_custom_extension_no_properties", "stix2/test/test_custom.py::test_custom_extension_empty_properties", "stix2/test/test_custom.py::test_custom_extension_dict_properties", "stix2/test/test_custom.py::test_parse_observable_with_custom_extension", "stix2/test/test_custom.py::test_register_custom_object", "stix2/test/test_custom.py::test_extension_property_location" ]
2018-04-12 20:43:25+00:00
4,280
oasis-open__cti-python-stix2-165
diff --git a/stix2/base.py b/stix2/base.py index 898f489..3219007 100644 --- a/stix2/base.py +++ b/stix2/base.py @@ -6,9 +6,9 @@ import datetime as dt import simplejson as json -from .exceptions import (AtLeastOnePropertyError, DependentPropertiesError, - ExtraPropertiesError, ImmutableError, - InvalidObjRefError, InvalidValueError, +from .exceptions import (AtLeastOnePropertyError, CustomContentError, + DependentPropertiesError, ExtraPropertiesError, + ImmutableError, InvalidObjRefError, InvalidValueError, MissingPropertiesError, MutuallyExclusivePropertiesError) from .markings.utils import validate @@ -61,6 +61,8 @@ class _STIXBase(collections.Mapping): try: kwargs[prop_name] = prop.clean(kwargs[prop_name]) except ValueError as exc: + if self.__allow_custom and isinstance(exc, CustomContentError): + return raise InvalidValueError(self.__class__, prop_name, reason=str(exc)) # interproperty constraint methods @@ -97,6 +99,7 @@ class _STIXBase(collections.Mapping): def __init__(self, allow_custom=False, **kwargs): cls = self.__class__ + self.__allow_custom = allow_custom # Use the same timestamp for any auto-generated datetimes self.__now = get_timestamp() diff --git a/stix2/exceptions.py b/stix2/exceptions.py index 841a8e9..79c5a81 100644 --- a/stix2/exceptions.py +++ b/stix2/exceptions.py @@ -163,6 +163,13 @@ class ParseError(STIXError, ValueError): super(ParseError, self).__init__(msg) +class CustomContentError(STIXError, ValueError): + """Custom STIX Content (SDO, Observable, Extension, etc.) detected.""" + + def __init__(self, msg): + super(CustomContentError, self).__init__(msg) + + class InvalidSelectorError(STIXError, AssertionError): """Granular Marking selector violation. The selector must resolve into an existing STIX object property.""" diff --git a/stix2/properties.py b/stix2/properties.py index ca7f04c..41841b6 100644 --- a/stix2/properties.py +++ b/stix2/properties.py @@ -129,6 +129,8 @@ class ListProperty(Property): # constructor again result.append(valid) continue + elif type(self.contained) is DictionaryProperty: + obj_type = dict else: obj_type = self.contained diff --git a/stix2/utils.py b/stix2/utils.py index 9febd78..4ef3d23 100644 --- a/stix2/utils.py +++ b/stix2/utils.py @@ -166,7 +166,7 @@ def get_dict(data): def find_property_index(obj, properties, tuple_to_find): """Recursively find the property in the object model, return the index according to the _properties OrderedDict. If it's a list look for - individual objects. + individual objects. Returns and integer indicating its location """ from .base import _STIXBase try: @@ -183,6 +183,11 @@ def find_property_index(obj, properties, tuple_to_find): tuple_to_find) if val is not None: return val + elif isinstance(item, dict): + for idx, val in enumerate(sorted(item)): + if (tuple_to_find[0] == val and + item.get(val) == tuple_to_find[1]): + return idx elif isinstance(pv, dict): if pv.get(tuple_to_find[0]) is not None: try: diff --git a/stix2/v20/observables.py b/stix2/v20/observables.py index 39a8f19..f6bac2b 100644 --- a/stix2/v20/observables.py +++ b/stix2/v20/observables.py @@ -8,8 +8,8 @@ Observable and do not have a ``_type`` attribute. from collections import OrderedDict from ..base import _Extension, _Observable, _STIXBase -from ..exceptions import (AtLeastOnePropertyError, DependentPropertiesError, - ParseError) +from ..exceptions import (AtLeastOnePropertyError, CustomContentError, + DependentPropertiesError, ParseError) from ..properties import (BinaryProperty, BooleanProperty, DictionaryProperty, EmbeddedObjectProperty, EnumProperty, FloatProperty, HashesProperty, HexProperty, IntegerProperty, @@ -67,7 +67,7 @@ class ExtensionsProperty(DictionaryProperty): else: raise ValueError("Cannot determine extension type.") else: - raise ValueError("The key used in the extensions dictionary is not an extension type name") + raise CustomContentError("Can't parse unknown extension type: {}".format(key)) else: raise ValueError("The enclosing type '%s' has no extensions defined" % self.enclosing_type) return dictified @@ -923,15 +923,23 @@ def parse_observable(data, _valid_refs=None, allow_custom=False): try: obj_class = OBJ_MAP_OBSERVABLE[obj['type']] except KeyError: - raise ParseError("Can't parse unknown observable type '%s'! For custom observables, " - "use the CustomObservable decorator." % obj['type']) + if allow_custom: + # flag allows for unknown custom objects too, but will not + # be parsed into STIX observable object, just returned as is + return obj + raise CustomContentError("Can't parse unknown observable type '%s'! For custom observables, " + "use the CustomObservable decorator." % obj['type']) if 'extensions' in obj and obj['type'] in EXT_MAP: for name, ext in obj['extensions'].items(): - if name not in EXT_MAP[obj['type']]: - raise ParseError("Can't parse Unknown extension type '%s' for observable type '%s'!" % (name, obj['type'])) - ext_class = EXT_MAP[obj['type']][name] - obj['extensions'][name] = ext_class(allow_custom=allow_custom, **obj['extensions'][name]) + try: + ext_class = EXT_MAP[obj['type']][name] + except KeyError: + if not allow_custom: + raise CustomContentError("Can't parse unknown extension type '%s'" + "for observable type '%s'!" % (name, obj['type'])) + else: # extension was found + obj['extensions'][name] = ext_class(allow_custom=allow_custom, **obj['extensions'][name]) return obj_class(allow_custom=allow_custom, **obj)
oasis-open/cti-python-stix2
2d689815d743611a8f3ccd48ce5e2d1ec70695e5
diff --git a/stix2/test/test_custom.py b/stix2/test/test_custom.py index a14503f..56e578f 100644 --- a/stix2/test/test_custom.py +++ b/stix2/test/test_custom.py @@ -363,6 +363,7 @@ def test_parse_custom_observable_object(): }""" nt = stix2.parse_observable(nt_string, []) + assert isinstance(nt, stix2.core._STIXBase) assert nt.property1 == 'something' @@ -372,10 +373,46 @@ def test_parse_unregistered_custom_observable_object(): "property1": "something" }""" - with pytest.raises(stix2.exceptions.ParseError) as excinfo: + with pytest.raises(stix2.exceptions.CustomContentError) as excinfo: stix2.parse_observable(nt_string) assert "Can't parse unknown observable type" in str(excinfo.value) + parsed_custom = stix2.parse_observable(nt_string, allow_custom=True) + assert parsed_custom['property1'] == 'something' + with pytest.raises(AttributeError) as excinfo: + assert parsed_custom.property1 == 'something' + assert not isinstance(parsed_custom, stix2.core._STIXBase) + + +def test_parse_unregistered_custom_observable_object_with_no_type(): + nt_string = """{ + "property1": "something" + }""" + + with pytest.raises(stix2.exceptions.ParseError) as excinfo: + stix2.parse_observable(nt_string, allow_custom=True) + assert "Can't parse observable with no 'type' property" in str(excinfo.value) + + +def test_parse_observed_data_with_custom_observable(): + input_str = """{ + "type": "observed-data", + "id": "observed-data--dc20c4ca-a2a3-4090-a5d5-9558c3af4758", + "created": "2016-04-06T19:58:16.000Z", + "modified": "2016-04-06T19:58:16.000Z", + "first_observed": "2015-12-21T19:00:00Z", + "last_observed": "2015-12-21T19:00:00Z", + "number_observed": 1, + "objects": { + "0": { + "type": "x-foobar-observable", + "property1": "something" + } + } + }""" + parsed = stix2.parse(input_str, allow_custom=True) + assert parsed.objects['0']['property1'] == 'something' + def test_parse_invalid_custom_observable_object(): nt_string = """{ @@ -479,6 +516,27 @@ def test_custom_extension_wrong_observable_type(): assert 'Cannot determine extension type' in excinfo.value.reason [email protected]("data", [ + """{ + "keys": [ + { + "test123": 123, + "test345": "aaaa" + } + ] +}""", +]) +def test_custom_extension_with_list_and_dict_properties_observable_type(data): + @stix2.observables.CustomExtension(stix2.UserAccount, 'some-extension', [ + ('keys', stix2.properties.ListProperty(stix2.properties.DictionaryProperty, required=True)) + ]) + class SomeCustomExtension: + pass + + example = SomeCustomExtension(keys=[{'test123': 123, 'test345': 'aaaa'}]) + assert data == str(example) + + def test_custom_extension_invalid_observable(): # These extensions are being applied to improperly-created Observables. # The Observable classes should have been created with the CustomObservable decorator. @@ -591,7 +649,11 @@ def test_parse_observable_with_unregistered_custom_extension(): with pytest.raises(ValueError) as excinfo: stix2.parse_observable(input_str) - assert "Can't parse Unknown extension type" in str(excinfo.value) + assert "Can't parse unknown extension type" in str(excinfo.value) + + parsed_ob = stix2.parse_observable(input_str, allow_custom=True) + assert parsed_ob['extensions']['x-foobar-ext']['property1'] == 'foo' + assert not isinstance(parsed_ob['extensions']['x-foobar-ext'], stix2.core._STIXBase) def test_register_custom_object(): diff --git a/stix2/test/test_properties.py b/stix2/test/test_properties.py index 34edc96..16ff06a 100644 --- a/stix2/test/test_properties.py +++ b/stix2/test/test_properties.py @@ -1,6 +1,6 @@ import pytest -from stix2 import EmailMIMEComponent, ExtensionsProperty, TCPExt +from stix2 import CustomObject, EmailMIMEComponent, ExtensionsProperty, TCPExt from stix2.exceptions import AtLeastOnePropertyError, DictionaryKeyError from stix2.properties import (BinaryProperty, BooleanProperty, DictionaryProperty, EmbeddedObjectProperty, @@ -266,6 +266,17 @@ def test_dictionary_property_invalid(d): assert str(excinfo.value) == d[1] +def test_property_list_of_dictionary(): + @CustomObject('x-new-obj', [ + ('property1', ListProperty(DictionaryProperty(), required=True)), + ]) + class NewObj(): + pass + + test_obj = NewObj(property1=[{'foo': 'bar'}]) + assert test_obj.property1[0]['foo'] == 'bar' + + @pytest.mark.parametrize("value", [ {"sha256": "6db12788c37247f2316052e142f42f4b259d6561751e5f401a1ae2a6df9c674b"}, [('MD5', '2dfb1bcc980200c6706feee399d41b3f'), ('RIPEMD-160', 'b3a8cd8a27c90af79b3c81754f267780f443dfef')],
Create an Extension with Dict annidate inside List Hi, I'm trying to create a CyberObservable Extension for UserAccount which have to contain a DictionaryProperty() inside a ListProperty(). It is possible? Because when I try to create an extension like this one ``` @CustomExtension(UserAccount, 'ssh_keys', { keys': ListProperty(DictionaryProperty(), required=True) }) class SSHKeysExtension: pass ``` and use it with example = SSHKeysExtension(keys=[{'test123':123, 'test345','aaaa'}]) I obtain a lot of strange errors (the library seems to interpreter the dict as parameters for __init__()
0.0
[ "stix2/test/test_custom.py::test_parse_unregistered_custom_observable_object", "stix2/test/test_custom.py::test_parse_observed_data_with_custom_observable", "stix2/test/test_custom.py::test_parse_observable_with_unregistered_custom_extension" ]
[ "stix2/test/test_custom.py::test_identity_custom_property", "stix2/test/test_custom.py::test_identity_custom_property_invalid", "stix2/test/test_custom.py::test_identity_custom_property_allowed", "stix2/test/test_custom.py::test_parse_identity_custom_property[{\\n", "stix2/test/test_custom.py::test_custom_property_in_bundled_object", "stix2/test/test_custom.py::test_identity_custom_property_revoke", "stix2/test/test_custom.py::test_identity_custom_property_edit_markings", "stix2/test/test_custom.py::test_custom_object_raises_exception", "stix2/test/test_custom.py::test_custom_object_type", "stix2/test/test_custom.py::test_parse_custom_object_type", "stix2/test/test_custom.py::test_parse_unregistered_custom_object_type", "stix2/test/test_custom.py::test_parse_unregistered_custom_object_type_w_allow_custom", "stix2/test/test_custom.py::test_custom_observable_object_1", "stix2/test/test_custom.py::test_custom_observable_object_2", "stix2/test/test_custom.py::test_custom_observable_object_3", "stix2/test/test_custom.py::test_custom_observable_raises_exception", "stix2/test/test_custom.py::test_custom_observable_object_invalid_ref_property", "stix2/test/test_custom.py::test_custom_observable_object_invalid_refs_property", "stix2/test/test_custom.py::test_custom_observable_object_invalid_refs_list_property", "stix2/test/test_custom.py::test_custom_observable_object_invalid_valid_refs", "stix2/test/test_custom.py::test_custom_no_properties_raises_exception", "stix2/test/test_custom.py::test_custom_wrong_properties_arg_raises_exception", "stix2/test/test_custom.py::test_parse_unregistered_custom_observable_object_with_no_type", "stix2/test/test_custom.py::test_parse_invalid_custom_observable_object", "stix2/test/test_custom.py::test_observable_custom_property", "stix2/test/test_custom.py::test_observable_custom_property_invalid", "stix2/test/test_custom.py::test_observable_custom_property_allowed", "stix2/test/test_custom.py::test_custom_extension_raises_exception", "stix2/test/test_custom.py::test_custom_extension", "stix2/test/test_custom.py::test_custom_extension_wrong_observable_type", "stix2/test/test_custom.py::test_custom_extension_invalid_observable", "stix2/test/test_custom.py::test_custom_extension_no_properties", "stix2/test/test_custom.py::test_custom_extension_empty_properties", "stix2/test/test_custom.py::test_custom_extension_dict_properties", "stix2/test/test_custom.py::test_parse_observable_with_custom_extension", "stix2/test/test_custom.py::test_register_custom_object", "stix2/test/test_custom.py::test_extension_property_location", "stix2/test/test_properties.py::test_property", "stix2/test/test_properties.py::test_basic_clean", "stix2/test/test_properties.py::test_property_default", "stix2/test/test_properties.py::test_fixed_property", "stix2/test/test_properties.py::test_list_property", "stix2/test/test_properties.py::test_string_property", "stix2/test/test_properties.py::test_type_property", "stix2/test/test_properties.py::test_id_property", "stix2/test/test_properties.py::test_integer_property_valid[2]", "stix2/test/test_properties.py::test_integer_property_valid[-1]", "stix2/test/test_properties.py::test_integer_property_valid[3.14]", "stix2/test/test_properties.py::test_integer_property_valid[False]", "stix2/test/test_properties.py::test_integer_property_invalid[something]", "stix2/test/test_properties.py::test_integer_property_invalid[value1]", "stix2/test/test_properties.py::test_float_property_valid[2]", "stix2/test/test_properties.py::test_float_property_valid[-1]", "stix2/test/test_properties.py::test_float_property_valid[3.14]", "stix2/test/test_properties.py::test_float_property_valid[False]", "stix2/test/test_properties.py::test_float_property_invalid[something]", "stix2/test/test_properties.py::test_float_property_invalid[value1]", "stix2/test/test_properties.py::test_boolean_property_valid[True0]", "stix2/test/test_properties.py::test_boolean_property_valid[False0]", "stix2/test/test_properties.py::test_boolean_property_valid[True1]", "stix2/test/test_properties.py::test_boolean_property_valid[False1]", "stix2/test/test_properties.py::test_boolean_property_valid[true]", "stix2/test/test_properties.py::test_boolean_property_valid[false]", "stix2/test/test_properties.py::test_boolean_property_valid[TRUE]", "stix2/test/test_properties.py::test_boolean_property_valid[FALSE]", "stix2/test/test_properties.py::test_boolean_property_valid[T]", "stix2/test/test_properties.py::test_boolean_property_valid[F]", "stix2/test/test_properties.py::test_boolean_property_valid[t]", "stix2/test/test_properties.py::test_boolean_property_valid[f]", "stix2/test/test_properties.py::test_boolean_property_valid[1]", "stix2/test/test_properties.py::test_boolean_property_valid[0]", "stix2/test/test_properties.py::test_boolean_property_invalid[abc]", "stix2/test/test_properties.py::test_boolean_property_invalid[value1]", "stix2/test/test_properties.py::test_boolean_property_invalid[value2]", "stix2/test/test_properties.py::test_boolean_property_invalid[2]", "stix2/test/test_properties.py::test_boolean_property_invalid[-1]", "stix2/test/test_properties.py::test_reference_property", "stix2/test/test_properties.py::test_timestamp_property_valid[2017-01-01T12:34:56Z]", "stix2/test/test_properties.py::test_timestamp_property_valid[2017-01-01", "stix2/test/test_properties.py::test_timestamp_property_valid[Jan", "stix2/test/test_properties.py::test_timestamp_property_invalid", "stix2/test/test_properties.py::test_binary_property", "stix2/test/test_properties.py::test_hex_property", "stix2/test/test_properties.py::test_dictionary_property_valid[d0]", "stix2/test/test_properties.py::test_dictionary_property_valid[d1]", "stix2/test/test_properties.py::test_dictionary_property_invalid_key[d0]", "stix2/test/test_properties.py::test_dictionary_property_invalid_key[d1]", "stix2/test/test_properties.py::test_dictionary_property_invalid_key[d2]", "stix2/test/test_properties.py::test_dictionary_property_invalid[d0]", "stix2/test/test_properties.py::test_dictionary_property_invalid[d1]", "stix2/test/test_properties.py::test_hashes_property_valid[value1]", "stix2/test/test_properties.py::test_hashes_property_invalid[value0]", "stix2/test/test_properties.py::test_hashes_property_invalid[value1]", "stix2/test/test_properties.py::test_embedded_property", "stix2/test/test_properties.py::test_enum_property_valid[value0]", "stix2/test/test_properties.py::test_enum_property_valid[value1]", "stix2/test/test_properties.py::test_enum_property_valid[b]", "stix2/test/test_properties.py::test_enum_property_invalid", "stix2/test/test_properties.py::test_extension_property_valid", "stix2/test/test_properties.py::test_extension_property_invalid[1]", "stix2/test/test_properties.py::test_extension_property_invalid[data1]", "stix2/test/test_properties.py::test_extension_property_invalid_type", "stix2/test/test_properties.py::test_extension_at_least_one_property_constraint" ]
2018-04-13 15:46:09+00:00
4,281
oasis-open__cti-python-stix2-172
diff --git a/stix2/patterns.py b/stix2/patterns.py index 23ce71b..3f9cbd9 100644 --- a/stix2/patterns.py +++ b/stix2/patterns.py @@ -147,6 +147,9 @@ class ListConstant(_Constant): def make_constant(value): + if isinstance(value, _Constant): + return value + try: return parse_into_datetime(value) except ValueError:
oasis-open/cti-python-stix2
f778a45b33f9b74c5a3b62c38db477bb504c2202
diff --git a/stix2/test/test_pattern_expressions.py b/stix2/test/test_pattern_expressions.py index 74a7d0f..14e3774 100644 --- a/stix2/test/test_pattern_expressions.py +++ b/stix2/test/test_pattern_expressions.py @@ -372,3 +372,9 @@ def test_invalid_startstop_qualifier(): stix2.StartStopQualifier(datetime.date(2016, 6, 1), 'foo') assert 'is not a valid argument for a Start/Stop Qualifier' in str(excinfo) + + +def test_make_constant_already_a_constant(): + str_const = stix2.StringConstant('Foo') + result = stix2.patterns.make_constant(str_const) + assert result is str_const
make_constant() should check if value is already a constant ``` python >>> from stix2.patterns import StringConstant >>> from stix2.patterns import make_constant >>> a = StringConstant('foo') >>> make_constant(a) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/lu/Projects/cti-python-stix2/stix2/patterns.py", line 166, in make_constant raise ValueError("Unable to create a constant from %s" % value) ValueError: Unable to create a constant from 'foo' ```
0.0
[ "stix2/test/test_pattern_expressions.py::test_make_constant_already_a_constant" ]
[ "stix2/test/test_pattern_expressions.py::test_create_comparison_expression", "stix2/test/test_pattern_expressions.py::test_boolean_expression", "stix2/test/test_pattern_expressions.py::test_boolean_expression_with_parentheses", "stix2/test/test_pattern_expressions.py::test_hash_followed_by_registryKey_expression_python_constant", "stix2/test/test_pattern_expressions.py::test_hash_followed_by_registryKey_expression", "stix2/test/test_pattern_expressions.py::test_file_observable_expression", "stix2/test/test_pattern_expressions.py::test_multiple_file_observable_expression[AndObservationExpression-AND]", "stix2/test/test_pattern_expressions.py::test_multiple_file_observable_expression[OrObservationExpression-OR]", "stix2/test/test_pattern_expressions.py::test_root_types", "stix2/test/test_pattern_expressions.py::test_artifact_payload", "stix2/test/test_pattern_expressions.py::test_greater_than_python_constant", "stix2/test/test_pattern_expressions.py::test_greater_than", "stix2/test/test_pattern_expressions.py::test_less_than", "stix2/test/test_pattern_expressions.py::test_greater_than_or_equal", "stix2/test/test_pattern_expressions.py::test_less_than_or_equal", "stix2/test/test_pattern_expressions.py::test_not", "stix2/test/test_pattern_expressions.py::test_and_observable_expression", "stix2/test/test_pattern_expressions.py::test_invalid_and_observable_expression", "stix2/test/test_pattern_expressions.py::test_hex", "stix2/test/test_pattern_expressions.py::test_multiple_qualifiers", "stix2/test/test_pattern_expressions.py::test_set_op", "stix2/test/test_pattern_expressions.py::test_timestamp", "stix2/test/test_pattern_expressions.py::test_boolean", "stix2/test/test_pattern_expressions.py::test_binary", "stix2/test/test_pattern_expressions.py::test_list", "stix2/test/test_pattern_expressions.py::test_list2", "stix2/test/test_pattern_expressions.py::test_invalid_constant_type", "stix2/test/test_pattern_expressions.py::test_invalid_integer_constant", "stix2/test/test_pattern_expressions.py::test_invalid_timestamp_constant", "stix2/test/test_pattern_expressions.py::test_invalid_float_constant", "stix2/test/test_pattern_expressions.py::test_boolean_constant[True-True0]", "stix2/test/test_pattern_expressions.py::test_boolean_constant[False-False0]", "stix2/test/test_pattern_expressions.py::test_boolean_constant[True-True1]", "stix2/test/test_pattern_expressions.py::test_boolean_constant[False-False1]", "stix2/test/test_pattern_expressions.py::test_boolean_constant[true-True]", "stix2/test/test_pattern_expressions.py::test_boolean_constant[false-False]", "stix2/test/test_pattern_expressions.py::test_boolean_constant[t-True]", "stix2/test/test_pattern_expressions.py::test_boolean_constant[f-False]", "stix2/test/test_pattern_expressions.py::test_boolean_constant[T-True]", "stix2/test/test_pattern_expressions.py::test_boolean_constant[F-False]", "stix2/test/test_pattern_expressions.py::test_boolean_constant[1-True]", "stix2/test/test_pattern_expressions.py::test_boolean_constant[0-False]", "stix2/test/test_pattern_expressions.py::test_invalid_boolean_constant", "stix2/test/test_pattern_expressions.py::test_invalid_hash_constant[MD5-zzz]", "stix2/test/test_pattern_expressions.py::test_invalid_hash_constant[ssdeep-zzz==]", "stix2/test/test_pattern_expressions.py::test_invalid_hex_constant", "stix2/test/test_pattern_expressions.py::test_invalid_binary_constant", "stix2/test/test_pattern_expressions.py::test_escape_quotes_and_backslashes", "stix2/test/test_pattern_expressions.py::test_like", "stix2/test/test_pattern_expressions.py::test_issuperset", "stix2/test/test_pattern_expressions.py::test_repeat_qualifier", "stix2/test/test_pattern_expressions.py::test_invalid_repeat_qualifier", "stix2/test/test_pattern_expressions.py::test_invalid_within_qualifier", "stix2/test/test_pattern_expressions.py::test_startstop_qualifier", "stix2/test/test_pattern_expressions.py::test_invalid_startstop_qualifier" ]
2018-04-26 14:25:09+00:00
4,282
oasis-open__cti-python-stix2-185
diff --git a/stix2/base.py b/stix2/base.py index 2afba16..7c62db4 100644 --- a/stix2/base.py +++ b/stix2/base.py @@ -185,7 +185,13 @@ class _STIXBase(collections.Mapping): # Handle attribute access just like key access def __getattr__(self, name): - if name in self: + # Pickle-proofing: pickle invokes this on uninitialized instances (i.e. + # __init__ has not run). So no "self" attributes are set yet. The + # usual behavior of this method reads an __init__-assigned attribute, + # which would cause infinite recursion. So this check disables all + # attribute reads until the instance has been properly initialized. + unpickling = "_inner" not in self.__dict__ + if not unpickling and name in self: return self.__getitem__(name) raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name)) @@ -236,6 +242,21 @@ class _STIXBase(collections.Mapping): optional properties set to the default value defined in the spec. **kwargs: The arguments for a json.dumps() call. + Examples: + >>> import stix2 + >>> identity = stix2.Identity(name='Example Corp.', identity_class='organization') + >>> print(identity.serialize(sort_keys=True)) + {"created": "2018-06-08T19:03:54.066Z", ... "name": "Example Corp.", "type": "identity"} + >>> print(identity.serialize(sort_keys=True, indent=4)) + { + "created": "2018-06-08T19:03:54.066Z", + "id": "identity--d7f3e25a-ba1c-447a-ab71-6434b092b05e", + "identity_class": "organization", + "modified": "2018-06-08T19:03:54.066Z", + "name": "Example Corp.", + "type": "identity" + } + Returns: str: The serialized JSON object. diff --git a/stix2/utils.py b/stix2/utils.py index 619652a..137ea01 100644 --- a/stix2/utils.py +++ b/stix2/utils.py @@ -165,44 +165,87 @@ def _get_dict(data): raise ValueError("Cannot convert '%s' to dictionary." % str(data)) +def _iterate_over_values(dict_values, tuple_to_find): + """Loop recursively over dictionary values""" + from .base import _STIXBase + for pv in dict_values: + if isinstance(pv, list): + for item in pv: + if isinstance(item, _STIXBase): + index = find_property_index( + item, + item.object_properties(), + tuple_to_find + ) + if index is not None: + return index + elif isinstance(item, dict): + for idx, val in enumerate(sorted(item)): + if (tuple_to_find[0] == val and + item.get(val) == tuple_to_find[1]): + return idx + elif isinstance(pv, dict): + if pv.get(tuple_to_find[0]) is not None: + for idx, item in enumerate(sorted(pv.keys())): + if ((item == tuple_to_find[0] and str.isdigit(item)) and + (pv[item] == tuple_to_find[1])): + return int(tuple_to_find[0]) + elif pv[item] == tuple_to_find[1]: + return idx + for item in pv.values(): + if isinstance(item, _STIXBase): + index = find_property_index( + item, + item.object_properties(), + tuple_to_find + ) + if index is not None: + return index + elif isinstance(item, dict): + index = find_property_index( + item, + item.keys(), + tuple_to_find + ) + if index is not None: + return index + + def find_property_index(obj, properties, tuple_to_find): """Recursively find the property in the object model, return the index - according to the _properties OrderedDict. If it's a list look for - individual objects. Returns and integer indicating its location + according to the ``properties`` OrderedDict when working with `stix2` + objects. If it's a list look for individual objects. Returns and integer + indicating its location. + + Notes: + This method is intended to pretty print `stix2` properties for better + visual feedback when working with the library. + + Warnings: + This method may not be able to produce the same output if called + multiple times and makes a best effort attempt to print the properties + according to the STIX technical specification. + + See Also: + py:meth:`stix2.base._STIXBase.serialize` for more information. + """ from .base import _STIXBase try: - if tuple_to_find[1] in obj._inner.values(): - return properties.index(tuple_to_find[0]) + if isinstance(obj, _STIXBase): + if tuple_to_find[1] in obj._inner.values(): + return properties.index(tuple_to_find[0]) + elif isinstance(obj, dict): + for idx, val in enumerate(sorted(obj)): + if (tuple_to_find[0] == val and + obj.get(val) == tuple_to_find[1]): + return idx raise ValueError except ValueError: - for pv in obj._inner.values(): - if isinstance(pv, list): - for item in pv: - if isinstance(item, _STIXBase): - val = find_property_index(item, - item.object_properties(), - tuple_to_find) - if val is not None: - return val - elif isinstance(item, dict): - for idx, val in enumerate(sorted(item)): - if (tuple_to_find[0] == val and - item.get(val) == tuple_to_find[1]): - return idx - elif isinstance(pv, dict): - if pv.get(tuple_to_find[0]) is not None: - try: - return int(tuple_to_find[0]) - except ValueError: - return len(tuple_to_find[0]) - for item in pv.values(): - if isinstance(item, _STIXBase): - val = find_property_index(item, - item.object_properties(), - tuple_to_find) - if val is not None: - return val + if isinstance(obj, _STIXBase): + return _iterate_over_values(obj._inner.values(), tuple_to_find) + elif isinstance(obj, dict): + return _iterate_over_values(obj.values(), tuple_to_find) def new_version(data, **kwargs):
oasis-open/cti-python-stix2
d67f2da0ea839db464197f7da0f7991bdd774d1f
diff --git a/stix2/test/test_custom.py b/stix2/test/test_custom.py index 7f91d79..6fb24d2 100644 --- a/stix2/test/test_custom.py +++ b/stix2/test/test_custom.py @@ -860,3 +860,33 @@ def test_register_custom_object(): def test_extension_property_location(): assert 'extensions' in stix2.v20.observables.OBJ_MAP_OBSERVABLE['x-new-observable']._properties assert 'extensions' not in stix2.v20.observables.EXT_MAP['domain-name']['x-new-ext']._properties + + [email protected]("data", [ + """{ + "type": "x-example", + "id": "x-example--336d8a9f-91f1-46c5-b142-6441bb9f8b8d", + "created": "2018-06-12T16:20:58.059Z", + "modified": "2018-06-12T16:20:58.059Z", + "dictionary": { + "key": { + "key_a": "value", + "key_b": "value" + } + } +}""", +]) +def test_custom_object_nested_dictionary(data): + @stix2.sdo.CustomObject('x-example', [ + ('dictionary', stix2.properties.DictionaryProperty()), + ]) + class Example(object): + def __init__(self, **kwargs): + pass + + example = Example(id='x-example--336d8a9f-91f1-46c5-b142-6441bb9f8b8d', + created='2018-06-12T16:20:58.059Z', + modified='2018-06-12T16:20:58.059Z', + dictionary={'key': {'key_b': 'value', 'key_a': 'value'}}) + + assert data == str(example) diff --git a/stix2/test/test_pickle.py b/stix2/test/test_pickle.py new file mode 100644 index 0000000..9e2cc9a --- /dev/null +++ b/stix2/test/test_pickle.py @@ -0,0 +1,17 @@ +import pickle + +import stix2 + + +def test_pickling(): + """ + Ensure a pickle/unpickle cycle works okay. + """ + identity = stix2.Identity( + id="identity--d66cb89d-5228-4983-958c-fa84ef75c88c", + name="alice", + description="this is a pickle test", + identity_class="some_class" + ) + + pickle.loads(pickle.dumps(identity)) diff --git a/stix2/test/test_utils.py b/stix2/test/test_utils.py index 655cd61..fb63ff7 100644 --- a/stix2/test/test_utils.py +++ b/stix2/test/test_utils.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + import datetime as dt from io import StringIO @@ -10,7 +12,7 @@ amsterdam = pytz.timezone('Europe/Amsterdam') eastern = pytz.timezone('US/Eastern') [email protected]('dttm,timestamp', [ [email protected]('dttm, timestamp', [ (dt.datetime(2017, 1, 1, tzinfo=pytz.utc), '2017-01-01T00:00:00Z'), (amsterdam.localize(dt.datetime(2017, 1, 1)), '2016-12-31T23:00:00Z'), (eastern.localize(dt.datetime(2017, 1, 1, 12, 34, 56)), '2017-01-01T17:34:56Z'), @@ -76,12 +78,12 @@ def test_get_dict_invalid(data): stix2.utils._get_dict(data) [email protected]('stix_id, typ', [ [email protected]('stix_id, type', [ ('malware--d69c8146-ab35-4d50-8382-6fc80e641d43', 'malware'), ('intrusion-set--899ce53f-13a0-479b-a0e4-67d46e241542', 'intrusion-set') ]) -def test_get_type_from_id(stix_id, typ): - assert stix2.utils.get_type_from_id(stix_id) == typ +def test_get_type_from_id(stix_id, type): + assert stix2.utils.get_type_from_id(stix_id) == type def test_deduplicate(stix_objs1): @@ -100,3 +102,110 @@ def test_deduplicate(stix_objs1): assert "indicator--d81f86b9-975b-bc0b-775e-810c5ad45a4f" in ids assert "2017-01-27T13:49:53.935Z" in mods assert "2017-01-27T13:49:53.936Z" in mods + + [email protected]('object, tuple_to_find, expected_index', [ + (stix2.ObservedData( + id="observed-data--b67d30ff-02ac-498a-92f9-32f845f448cf", + created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", + created="2016-04-06T19:58:16.000Z", + modified="2016-04-06T19:58:16.000Z", + first_observed="2015-12-21T19:00:00Z", + last_observed="2015-12-21T19:00:00Z", + number_observed=50, + objects={ + "0": { + "name": "foo.exe", + "type": "file" + }, + "1": { + "type": "ipv4-addr", + "value": "198.51.100.3" + }, + "2": { + "type": "network-traffic", + "src_ref": "1", + "protocols": [ + "tcp", + "http" + ], + "extensions": { + "http-request-ext": { + "request_method": "get", + "request_value": "/download.html", + "request_version": "http/1.1", + "request_header": { + "Accept-Encoding": "gzip,deflate", + "User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.6) Gecko/20040113", + "Host": "www.example.com" + } + } + } + } + }, + ), ('1', {"type": "ipv4-addr", "value": "198.51.100.3"}), 1), + ({ + "type": "x-example", + "id": "x-example--d5413db2-c26c-42e0-b0e0-ec800a310bfb", + "created": "2018-06-11T01:25:22.063Z", + "modified": "2018-06-11T01:25:22.063Z", + "dictionary": { + "key": { + "key_one": "value", + "key_two": "value" + } + } + }, ('key', {'key_one': 'value', 'key_two': 'value'}), 0), + ({ + "type": "language-content", + "id": "language-content--b86bd89f-98bb-4fa9-8cb2-9ad421da981d", + "created": "2017-02-08T21:31:22.007Z", + "modified": "2017-02-08T21:31:22.007Z", + "object_ref": "campaign--12a111f0-b824-4baf-a224-83b80237a094", + "object_modified": "2017-02-08T21:31:22.007Z", + "contents": { + "de": { + "name": "Bank Angriff 1", + "description": "Weitere Informationen über Banküberfall" + }, + "fr": { + "name": "Attaque Bank 1", + "description": "Plus d'informations sur la crise bancaire" + } + } + }, ('fr', {"name": "Attaque Bank 1", "description": "Plus d'informations sur la crise bancaire"}), 1) +]) +def test_find_property_index(object, tuple_to_find, expected_index): + assert stix2.utils.find_property_index( + object, + [], + tuple_to_find + ) == expected_index + + [email protected]('dict_value, tuple_to_find, expected_index', [ + ({ + "contents": { + "de": { + "name": "Bank Angriff 1", + "description": "Weitere Informationen über Banküberfall" + }, + "fr": { + "name": "Attaque Bank 1", + "description": "Plus d'informations sur la crise bancaire" + }, + "es": { + "name": "Ataque al Banco", + "description": "Mas informacion sobre el ataque al banco" + } + } + }, ('es', {"name": "Ataque al Banco", "description": "Mas informacion sobre el ataque al banco"}), 1), # Sorted alphabetically + ({ + 'my_list': [ + {"key_one": 1}, + {"key_two": 2} + ] + }, ('key_one', 1), 0) +]) +def test_iterate_over_values(dict_value, tuple_to_find, expected_index): + assert stix2.utils._iterate_over_values(dict_value.values(), tuple_to_find) == expected_index
Custom STIX objects with nested dictionary error A custom STIX object with a nested dictionary created using the following example: ``` python #!/usr/bin/env python3.6 from stix2 import CustomObject, properties @CustomObject('x-example', [ ('dictionary', properties.DictionaryProperty()), ]) class Example(object): def __init__(self, **kwargs): pass example = Example(dictionary={'key':{'key_one':'value', 'key_two':'value'}}) print(example) ``` throws the following error when calling the `__str__()` method: ``` bash Traceback (most recent call last): File "./example.py", line 16, in <module> print(example) File "/home/lib64/python3.6/site-packages/stix2/base.py", line 199, in __str__ return self.serialize(pretty=True) File "/home/lib64/python3.6/site-packages/stix2/base.py", line 262, in serialize return json.dumps(self, cls=STIXJSONEncoder, **kwargs) File "/home/lib64/python3.6/site-packages/simplejson/__init__.py", line 399, in dumps **kw).encode(obj) File "home/lib64/python3.6/site-packages/simplejson/encoder.py", line 298, in encode chunks = list(chunks) File "/home/lib64/python3.6/site-packages/simplejson/encoder.py", line 717, in _iterencode for chunk in _iterencode(o, _current_indent_level): File "home/lib64/python3.6/site-packages/simplejson/encoder.py", line 696, in _iterencode for chunk in _iterencode_dict(o, _current_indent_level): File "home/lib64/python3.6/site-packages/simplejson/encoder.py", line 652, in _iterencode_dict for chunk in chunks: File "/home/lib64/python3.6/site-packages/simplejson/encoder.py", line 652, in _iterencode_dict for chunk in chunks: File "/home/lib64/python3.6/site-packages/simplejson/encoder.py", line 602, in _iterencode_dict items.sort(key=_item_sort_key) TypeError: '<' not supported between instances of 'NoneType' and 'NoneType' ``` the work around is to call: ``` python print(example.serialize(pretty=False)) ``` I'm assuming its something do with how `simplejson` is trying to sort the keys and struggles with the nested dictionary. Is there a reason why the `__str__()` method defaults to `pretty=True`?
0.0
[ "stix2/test/test_custom.py::test_custom_object_nested_dictionary[{\\n", "stix2/test/test_pickle.py::test_pickling", "stix2/test/test_utils.py::test_find_property_index[object1-tuple_to_find1-0]", "stix2/test/test_utils.py::test_find_property_index[object2-tuple_to_find2-1]", "stix2/test/test_utils.py::test_iterate_over_values[dict_value0-tuple_to_find0-1]", "stix2/test/test_utils.py::test_iterate_over_values[dict_value1-tuple_to_find1-0]" ]
[ "stix2/test/test_custom.py::test_identity_custom_property", "stix2/test/test_custom.py::test_identity_custom_property_invalid", "stix2/test/test_custom.py::test_identity_custom_property_allowed", "stix2/test/test_custom.py::test_parse_identity_custom_property[{\\n", "stix2/test/test_custom.py::test_custom_property_object_in_bundled_object", "stix2/test/test_custom.py::test_custom_properties_object_in_bundled_object", "stix2/test/test_custom.py::test_custom_property_dict_in_bundled_object", "stix2/test/test_custom.py::test_custom_properties_dict_in_bundled_object", "stix2/test/test_custom.py::test_custom_property_in_observed_data", "stix2/test/test_custom.py::test_custom_property_object_in_observable_extension", "stix2/test/test_custom.py::test_custom_property_dict_in_observable_extension", "stix2/test/test_custom.py::test_identity_custom_property_revoke", "stix2/test/test_custom.py::test_identity_custom_property_edit_markings", "stix2/test/test_custom.py::test_custom_object_raises_exception", "stix2/test/test_custom.py::test_custom_object_type", "stix2/test/test_custom.py::test_custom_object_invalid_type_name", "stix2/test/test_custom.py::test_parse_custom_object_type", "stix2/test/test_custom.py::test_parse_unregistered_custom_object_type", "stix2/test/test_custom.py::test_parse_unregistered_custom_object_type_w_allow_custom", "stix2/test/test_custom.py::test_custom_observable_object_1", "stix2/test/test_custom.py::test_custom_observable_object_2", "stix2/test/test_custom.py::test_custom_observable_object_3", "stix2/test/test_custom.py::test_custom_observable_raises_exception", "stix2/test/test_custom.py::test_custom_observable_object_invalid_type_name", "stix2/test/test_custom.py::test_custom_observable_object_invalid_ref_property", "stix2/test/test_custom.py::test_custom_observable_object_invalid_refs_property", "stix2/test/test_custom.py::test_custom_observable_object_invalid_refs_list_property", "stix2/test/test_custom.py::test_custom_observable_object_invalid_valid_refs", "stix2/test/test_custom.py::test_custom_no_properties_raises_exception", "stix2/test/test_custom.py::test_custom_wrong_properties_arg_raises_exception", "stix2/test/test_custom.py::test_parse_unregistered_custom_observable_object", "stix2/test/test_custom.py::test_parse_unregistered_custom_observable_object_with_no_type", "stix2/test/test_custom.py::test_parse_observed_data_with_custom_observable", "stix2/test/test_custom.py::test_parse_invalid_custom_observable_object", "stix2/test/test_custom.py::test_observable_custom_property", "stix2/test/test_custom.py::test_observable_custom_property_invalid", "stix2/test/test_custom.py::test_observable_custom_property_allowed", "stix2/test/test_custom.py::test_custom_extension_raises_exception", "stix2/test/test_custom.py::test_custom_extension", "stix2/test/test_custom.py::test_custom_extension_wrong_observable_type", "stix2/test/test_custom.py::test_custom_extension_invalid_observable", "stix2/test/test_custom.py::test_custom_extension_invalid_type_name", "stix2/test/test_custom.py::test_custom_extension_no_properties", "stix2/test/test_custom.py::test_custom_extension_empty_properties", "stix2/test/test_custom.py::test_custom_extension_dict_properties", "stix2/test/test_custom.py::test_parse_observable_with_custom_extension", "stix2/test/test_custom.py::test_parse_observable_with_unregistered_custom_extension", "stix2/test/test_custom.py::test_register_custom_object", "stix2/test/test_custom.py::test_extension_property_location", "stix2/test/test_utils.py::test_timestamp_formatting[dttm0-2017-01-01T00:00:00Z]", "stix2/test/test_utils.py::test_timestamp_formatting[dttm1-2016-12-31T23:00:00Z]", "stix2/test/test_utils.py::test_timestamp_formatting[dttm2-2017-01-01T17:34:56Z]", "stix2/test/test_utils.py::test_timestamp_formatting[dttm3-2017-07-01T04:00:00Z]", "stix2/test/test_utils.py::test_timestamp_formatting[dttm4-2017-07-01T00:00:00Z]", "stix2/test/test_utils.py::test_timestamp_formatting[dttm5-2017-07-01T00:00:00.000001Z]", "stix2/test/test_utils.py::test_timestamp_formatting[dttm6-2017-07-01T00:00:00.000Z]", "stix2/test/test_utils.py::test_timestamp_formatting[dttm7-2017-07-01T00:00:00Z]", "stix2/test/test_utils.py::test_parse_datetime[timestamp0-dttm0]", "stix2/test/test_utils.py::test_parse_datetime[timestamp1-dttm1]", "stix2/test/test_utils.py::test_parse_datetime[2017-01-01T00:00:00Z-dttm2]", "stix2/test/test_utils.py::test_parse_datetime[2017-01-01T02:00:00+2:00-dttm3]", "stix2/test/test_utils.py::test_parse_datetime[2017-01-01T00:00:00-dttm4]", "stix2/test/test_utils.py::test_parse_datetime_precision[2017-01-01T01:02:03.000001-dttm0-millisecond]", "stix2/test/test_utils.py::test_parse_datetime_precision[2017-01-01T01:02:03.001-dttm1-millisecond]", "stix2/test/test_utils.py::test_parse_datetime_precision[2017-01-01T01:02:03.1-dttm2-millisecond]", "stix2/test/test_utils.py::test_parse_datetime_precision[2017-01-01T01:02:03.45-dttm3-millisecond]", "stix2/test/test_utils.py::test_parse_datetime_precision[2017-01-01T01:02:03.45-dttm4-second]", "stix2/test/test_utils.py::test_parse_datetime_invalid[foobar]", "stix2/test/test_utils.py::test_parse_datetime_invalid[1]", "stix2/test/test_utils.py::test_get_dict[data0]", "stix2/test/test_utils.py::test_get_dict[{\"a\":", "stix2/test/test_utils.py::test_get_dict[data2]", "stix2/test/test_utils.py::test_get_dict[data3]", "stix2/test/test_utils.py::test_get_dict_invalid[1]", "stix2/test/test_utils.py::test_get_dict_invalid[data1]", "stix2/test/test_utils.py::test_get_dict_invalid[data2]", "stix2/test/test_utils.py::test_get_dict_invalid[foobar]", "stix2/test/test_utils.py::test_get_type_from_id[malware--d69c8146-ab35-4d50-8382-6fc80e641d43-malware]", "stix2/test/test_utils.py::test_get_type_from_id[intrusion-set--899ce53f-13a0-479b-a0e4-67d46e241542-intrusion-set]", "stix2/test/test_utils.py::test_deduplicate", "stix2/test/test_utils.py::test_find_property_index[object0-tuple_to_find0-1]" ]
2018-06-01 12:52:37+00:00
4,283
oasis-open__cti-python-stix2-187
diff --git a/stix2/base.py b/stix2/base.py index 2afba16..9b5308f 100644 --- a/stix2/base.py +++ b/stix2/base.py @@ -185,7 +185,13 @@ class _STIXBase(collections.Mapping): # Handle attribute access just like key access def __getattr__(self, name): - if name in self: + # Pickle-proofing: pickle invokes this on uninitialized instances (i.e. + # __init__ has not run). So no "self" attributes are set yet. The + # usual behavior of this method reads an __init__-assigned attribute, + # which would cause infinite recursion. So this check disables all + # attribute reads until the instance has been properly initialized. + unpickling = "_inner" not in self.__dict__ + if not unpickling and name in self: return self.__getitem__(name) raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name))
oasis-open/cti-python-stix2
d67f2da0ea839db464197f7da0f7991bdd774d1f
diff --git a/stix2/test/test_pickle.py b/stix2/test/test_pickle.py new file mode 100644 index 0000000..9e2cc9a --- /dev/null +++ b/stix2/test/test_pickle.py @@ -0,0 +1,17 @@ +import pickle + +import stix2 + + +def test_pickling(): + """ + Ensure a pickle/unpickle cycle works okay. + """ + identity = stix2.Identity( + id="identity--d66cb89d-5228-4983-958c-fa84ef75c88c", + name="alice", + description="this is a pickle test", + identity_class="some_class" + ) + + pickle.loads(pickle.dumps(identity))
Infinite recursion on _STIXBase object deserialization Hi! There seems to be a bug in the way the `__getitem__`/`__getattr__` functions are implemented in `_STIXBase` (_cti-python-stix2/stix2/base.py_). The bug can be reproduced by trying to serialize/deserialize an object instance, resulting in infinite recursion causing the program to terminate with a `RecursionError` once the max recursion depth is exceeded. Here is a short example with copy.copy() triggering the recursion: ``` import copy, stix2 indicator = stix2.Indicator(name="a", labels=["a"], pattern="[file:name = 'a']") copy.copy(indicator) ``` I believe this is because the unpickling tries to find the optional `__set_state__` method in `_STIXBase`. But since it's not there, the `__getattr__` is being called for it. However, the way `__getattr__` is implemented in the class, the `__getitem__` is called which tries to look up an item in `self._inner`. Due to the way the deserialization works in general, the object itself is empty and the `__init__` was never called - meaning that the `_inner` attribute was never set. The access attempt on the non-existent `_inner` however triggers a call to `__getattr__` again, resulting in the recursion. Here are two possible patches, I'm not sure though if that's the proper way of fixing it: 1) Checking for `_inner` access in `__getitem__`: ``` def __getitem__(self, key): if key == '_inner': raise KeyError return self._inner[key] ``` 2) Checking for protected attributes in `__getattr__`: ``` def __getattr__(self, name): if name.startswith('_'): raise AttributeError(name) if name in self: return self.__getitem__(name) raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name)) ``` Thanks!
0.0
[ "stix2/test/test_pickle.py::test_pickling" ]
[]
2018-06-06 19:42:25+00:00
4,284
oasis-open__cti-python-stix2-216
diff --git a/stix2/v20/common.py b/stix2/v20/common.py index c66b8f6..d574c92 100644 --- a/stix2/v20/common.py +++ b/stix2/v20/common.py @@ -1,6 +1,7 @@ """STIX 2 Common Data Types and Properties.""" from collections import OrderedDict +import copy from ..base import _cls_init, _STIXBase from ..markings import _MarkingsMixin @@ -124,6 +125,13 @@ class MarkingDefinition(_STIXBase, _MarkingsMixin): except KeyError: raise ValueError("definition_type must be a valid marking type") + if marking_type == TLPMarking: + # TLP instances in the spec have millisecond precision unlike other markings + self._properties = copy.deepcopy(self._properties) + self._properties.update([ + ('created', TimestampProperty(default=lambda: NOW, precision='millisecond')), + ]) + if not isinstance(kwargs['definition'], marking_type): defn = _get_dict(kwargs['definition']) kwargs['definition'] = marking_type(**defn)
oasis-open/cti-python-stix2
6613b55a433d4278c46f51327569fce0f125724c
diff --git a/stix2/test/test_markings.py b/stix2/test/test_markings.py index ec8b664..49803f3 100644 --- a/stix2/test/test_markings.py +++ b/stix2/test/test_markings.py @@ -11,7 +11,7 @@ from .constants import MARKING_DEFINITION_ID EXPECTED_TLP_MARKING_DEFINITION = """{ "type": "marking-definition", "id": "marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9", - "created": "2017-01-20T00:00:00Z", + "created": "2017-01-20T00:00:00.000Z", "definition_type": "tlp", "definition": { "tlp": "white"
The instance of MarkingDefinition cannot pass validation because the 'created' property does't have millisecond. Here is the screenshot: ![marking](https://user-images.githubusercontent.com/5939857/47416920-56c50f00-d7a9-11e8-87a7-aa9b1f82cdb7.PNG) Source code: ![marking_class](https://user-images.githubusercontent.com/5939857/47417251-2af65900-d7aa-11e8-8914-5b1f0312bbb3.PNG) Does the 'created' property should be ![property](https://user-images.githubusercontent.com/5939857/47417384-73ae1200-d7aa-11e8-86b3-7960130ca96f.PNG) to pass validation?
0.0
[ "stix2/test/test_markings.py::test_marking_def_example_with_tlp" ]
[ "stix2/test/test_markings.py::test_marking_def_example_with_statement_positional_argument", "stix2/test/test_markings.py::test_marking_def_example_with_kwargs_statement", "stix2/test/test_markings.py::test_marking_def_invalid_type", "stix2/test/test_markings.py::test_campaign_with_markings_example", "stix2/test/test_markings.py::test_granular_example", "stix2/test/test_markings.py::test_granular_example_with_bad_selector", "stix2/test/test_markings.py::test_campaign_with_granular_markings_example", "stix2/test/test_markings.py::test_parse_marking_definition[{\\n", "stix2/test/test_markings.py::test_parse_marking_definition[data1]", "stix2/test/test_markings.py::test_registered_custom_marking", "stix2/test/test_markings.py::test_registered_custom_marking_raises_exception", "stix2/test/test_markings.py::test_not_registered_marking_raises_exception", "stix2/test/test_markings.py::test_marking_wrong_type_construction", "stix2/test/test_markings.py::test_campaign_add_markings" ]
2018-10-25 18:03:28+00:00
4,285
oasis-open__cti-python-stix2-221
diff --git a/stix2/v20/observables.py b/stix2/v20/observables.py index 36def28..faa5868 100644 --- a/stix2/v20/observables.py +++ b/stix2/v20/observables.py @@ -73,26 +73,23 @@ class ExtensionsProperty(DictionaryProperty): if dictified == {}: raise ValueError("The extensions property must contain a non-empty dictionary") - if self.enclosing_type in EXT_MAP: - specific_type_map = EXT_MAP[self.enclosing_type] - for key, subvalue in dictified.items(): - if key in specific_type_map: - cls = specific_type_map[key] - if type(subvalue) is dict: - if self.allow_custom: - subvalue['allow_custom'] = True - dictified[key] = cls(**subvalue) - else: - dictified[key] = cls(**subvalue) - elif type(subvalue) is cls: - # If already an instance of an _Extension class, assume it's valid - dictified[key] = subvalue + specific_type_map = EXT_MAP.get(self.enclosing_type, {}) + for key, subvalue in dictified.items(): + if key in specific_type_map: + cls = specific_type_map[key] + if type(subvalue) is dict: + if self.allow_custom: + subvalue['allow_custom'] = True + dictified[key] = cls(**subvalue) else: - raise ValueError("Cannot determine extension type.") + dictified[key] = cls(**subvalue) + elif type(subvalue) is cls: + # If already an instance of an _Extension class, assume it's valid + dictified[key] = subvalue else: - raise CustomContentError("Can't parse unknown extension type: {}".format(key)) - else: - raise ValueError("The enclosing type '%s' has no extensions defined" % self.enclosing_type) + raise ValueError("Cannot determine extension type.") + else: + raise CustomContentError("Can't parse unknown extension type: {}".format(key)) return dictified
oasis-open/cti-python-stix2
3084c9f51fcd00cf6b0ed76827af90d0e86746d5
diff --git a/stix2/test/test_custom.py b/stix2/test/test_custom.py index 18ad03a..18b8f18 100644 --- a/stix2/test/test_custom.py +++ b/stix2/test/test_custom.py @@ -826,9 +826,10 @@ def test_parse_observable_with_custom_extension(): assert parsed.extensions['x-new-ext'].property2 == 12 -def test_parse_observable_with_unregistered_custom_extension(): - input_str = """{ - "type": "domain-name", [email protected]("data", [ + # URL is not in EXT_MAP + """{ + "type": "url", "value": "example.com", "extensions": { "x-foobar-ext": { @@ -836,13 +837,25 @@ def test_parse_observable_with_unregistered_custom_extension(): "property2": 12 } } - }""" - + }""", + # File is in EXT_MAP + """{ + "type": "file", + "name": "foo.txt", + "extensions": { + "x-foobar-ext": { + "property1": "foo", + "property2": 12 + } + } + }""", +]) +def test_parse_observable_with_unregistered_custom_extension(data): with pytest.raises(ValueError) as excinfo: - stix2.parse_observable(input_str) + stix2.parse_observable(data) assert "Can't parse unknown extension type" in str(excinfo.value) - parsed_ob = stix2.parse_observable(input_str, allow_custom=True) + parsed_ob = stix2.parse_observable(data, allow_custom=True) assert parsed_ob['extensions']['x-foobar-ext']['property1'] == 'foo' assert not isinstance(parsed_ob['extensions']['x-foobar-ext'], stix2.core._STIXBase) diff --git a/stix2/test/test_properties.py b/stix2/test/test_properties.py index 1106bcb..19419bb 100644 --- a/stix2/test/test_properties.py +++ b/stix2/test/test_properties.py @@ -412,7 +412,7 @@ def test_extension_property_invalid_type(): 'pe_type': 'exe' }} ) - assert 'no extensions defined' in str(excinfo.value) + assert "Can't parse unknown extension" in str(excinfo.value) def test_extension_at_least_one_property_constraint():
stix2.exceptions.InvalidValueError: Invalid value for ObservedData 'objects': Invalid value for URL 'extensions': The enclosing type 'url' has no extensions defined According to the [stix2 standard](http://docs.oasis-open.org/cti/stix/v2.0/cs01/part4-cyber-observable-objects/stix-v2.0-cs01-part4-cyber-observable-objects.html#_Toc496716284), URL observables have `extensions` Common Properties. But I encountered this error when I tried to add a custom extension to a URL observable.
0.0
[ "stix2/test/test_custom.py::test_parse_observable_with_unregistered_custom_extension[{\\n", "stix2/test/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--5b9ea668-5777-11ef-a777-fa3cdcf14c24]", "stix2/test/test_properties.py::test_extension_property_invalid_type" ]
[ "stix2/test/test_custom.py::test_identity_custom_property", "stix2/test/test_custom.py::test_identity_custom_property_invalid", "stix2/test/test_custom.py::test_identity_custom_property_allowed", "stix2/test/test_custom.py::test_parse_identity_custom_property[{\\n", "stix2/test/test_custom.py::test_custom_property_object_in_bundled_object", "stix2/test/test_custom.py::test_custom_properties_object_in_bundled_object", "stix2/test/test_custom.py::test_custom_property_dict_in_bundled_object", "stix2/test/test_custom.py::test_custom_properties_dict_in_bundled_object", "stix2/test/test_custom.py::test_custom_property_in_observed_data", "stix2/test/test_custom.py::test_custom_property_object_in_observable_extension", "stix2/test/test_custom.py::test_custom_property_dict_in_observable_extension", "stix2/test/test_custom.py::test_identity_custom_property_revoke", "stix2/test/test_custom.py::test_identity_custom_property_edit_markings", "stix2/test/test_custom.py::test_custom_marking_no_init_1", "stix2/test/test_custom.py::test_custom_marking_no_init_2", "stix2/test/test_custom.py::test_custom_object_raises_exception", "stix2/test/test_custom.py::test_custom_object_type", "stix2/test/test_custom.py::test_custom_object_no_init_1", "stix2/test/test_custom.py::test_custom_object_no_init_2", "stix2/test/test_custom.py::test_custom_object_invalid_type_name", "stix2/test/test_custom.py::test_parse_custom_object_type", "stix2/test/test_custom.py::test_parse_unregistered_custom_object_type", "stix2/test/test_custom.py::test_parse_unregistered_custom_object_type_w_allow_custom", "stix2/test/test_custom.py::test_custom_observable_object_1", "stix2/test/test_custom.py::test_custom_observable_object_2", "stix2/test/test_custom.py::test_custom_observable_object_3", "stix2/test/test_custom.py::test_custom_observable_raises_exception", "stix2/test/test_custom.py::test_custom_observable_object_no_init_1", "stix2/test/test_custom.py::test_custom_observable_object_no_init_2", "stix2/test/test_custom.py::test_custom_observable_object_invalid_type_name", "stix2/test/test_custom.py::test_custom_observable_object_invalid_ref_property", "stix2/test/test_custom.py::test_custom_observable_object_invalid_refs_property", "stix2/test/test_custom.py::test_custom_observable_object_invalid_refs_list_property", "stix2/test/test_custom.py::test_custom_observable_object_invalid_valid_refs", "stix2/test/test_custom.py::test_custom_no_properties_raises_exception", "stix2/test/test_custom.py::test_custom_wrong_properties_arg_raises_exception", "stix2/test/test_custom.py::test_parse_custom_observable_object", "stix2/test/test_custom.py::test_parse_unregistered_custom_observable_object", "stix2/test/test_custom.py::test_parse_unregistered_custom_observable_object_with_no_type", "stix2/test/test_custom.py::test_parse_observed_data_with_custom_observable", "stix2/test/test_custom.py::test_parse_invalid_custom_observable_object", "stix2/test/test_custom.py::test_observable_custom_property", "stix2/test/test_custom.py::test_observable_custom_property_invalid", "stix2/test/test_custom.py::test_observable_custom_property_allowed", "stix2/test/test_custom.py::test_observed_data_with_custom_observable_object", "stix2/test/test_custom.py::test_custom_extension_raises_exception", "stix2/test/test_custom.py::test_custom_extension", "stix2/test/test_custom.py::test_custom_extension_wrong_observable_type", "stix2/test/test_custom.py::test_custom_extension_with_list_and_dict_properties_observable_type[{\\n", "stix2/test/test_custom.py::test_custom_extension_invalid_observable", "stix2/test/test_custom.py::test_custom_extension_invalid_type_name", "stix2/test/test_custom.py::test_custom_extension_no_properties", "stix2/test/test_custom.py::test_custom_extension_empty_properties", "stix2/test/test_custom.py::test_custom_extension_dict_properties", "stix2/test/test_custom.py::test_custom_extension_no_init_1", "stix2/test/test_custom.py::test_custom_extension_no_init_2", "stix2/test/test_custom.py::test_parse_observable_with_custom_extension", "stix2/test/test_custom.py::test_register_custom_object", "stix2/test/test_custom.py::test_extension_property_location", "stix2/test/test_custom.py::test_custom_object_nested_dictionary[{\\n", "stix2/test/test_properties.py::test_property", "stix2/test/test_properties.py::test_basic_clean", "stix2/test/test_properties.py::test_property_default", "stix2/test/test_properties.py::test_fixed_property", "stix2/test/test_properties.py::test_list_property", "stix2/test/test_properties.py::test_string_property", "stix2/test/test_properties.py::test_type_property", "stix2/test/test_properties.py::test_id_property_valid[my-type--232c9d3f-49fc-4440-bb01-607f638778e7]", "stix2/test/test_properties.py::test_id_property_valid[my-type--00000000-0000-4000-8000-000000000000]", "stix2/test/test_properties.py::test_id_property_valid_for_type[attack-pattern--0c7b5b88-8ff7-4a4d-aa9d-feb398cd0061]", "stix2/test/test_properties.py::test_id_property_valid_for_type[campaign--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f]", "stix2/test/test_properties.py::test_id_property_valid_for_type[course-of-action--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f]", "stix2/test/test_properties.py::test_id_property_valid_for_type[identity--311b2d2d-f010-4473-83ec-1edf84858f4c]", "stix2/test/test_properties.py::test_id_property_valid_for_type[indicator--a740531e-63ff-4e49-a9e1-a0a3eed0e3e7]", "stix2/test/test_properties.py::test_id_property_valid_for_type[intrusion-set--4e78f46f-a023-4e5f-bc24-71b3ca22ec29]", "stix2/test/test_properties.py::test_id_property_valid_for_type[malware--9c4638ec-f1de-4ddb-abf4-1b760417654e]", "stix2/test/test_properties.py::test_id_property_valid_for_type[marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9_0]", "stix2/test/test_properties.py::test_id_property_valid_for_type[observed-data--b67d30ff-02ac-498a-92f9-32f845f448cf]", "stix2/test/test_properties.py::test_id_property_valid_for_type[relationship--df7c87eb-75d2-4948-af81-9d49d246f301]", "stix2/test/test_properties.py::test_id_property_valid_for_type[report--84e4d88f-44ea-4bcd-bbf3-b2c1c320bcb3]", "stix2/test/test_properties.py::test_id_property_valid_for_type[sighting--bfbc19db-ec35-4e45-beed-f8bde2a772fb]", "stix2/test/test_properties.py::test_id_property_valid_for_type[threat-actor--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f]", "stix2/test/test_properties.py::test_id_property_valid_for_type[tool--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f]", "stix2/test/test_properties.py::test_id_property_valid_for_type[vulnerability--0c7b5b88-8ff7-4a4d-aa9d-feb398cd0061]", "stix2/test/test_properties.py::test_id_property_valid_for_type[marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9_1]", "stix2/test/test_properties.py::test_id_property_valid_for_type[marking-definition--443eb5c3-a76c-4a0a-8caa-e93998e7bc09]", "stix2/test/test_properties.py::test_id_property_valid_for_type[marking-definition--57fcd772-9c1d-41b0-8d1f-3d47713415d9]", "stix2/test/test_properties.py::test_id_property_valid_for_type[marking-definition--462bf1a6-03d2-419c-b74e-eee2238b2de4]", "stix2/test/test_properties.py::test_id_property_valid_for_type[marking-definition--68520ae2-fefe-43a9-84ee-2c2a934d2c7d]", "stix2/test/test_properties.py::test_id_property_valid_for_type[marking-definition--2802dfb1-1019-40a8-8848-68d0ec0e417f]", "stix2/test/test_properties.py::test_id_property_valid_for_type[relationship--06520621-5352-4e6a-b976-e8fa3d437ffd]", "stix2/test/test_properties.py::test_id_property_valid_for_type[relationship--181c9c09-43e6-45dd-9374-3bec192f05ef]", "stix2/test/test_properties.py::test_id_property_valid_for_type[relationship--a0cbb21c-8daf-4a7f-96aa-7155a4ef8f70]", "stix2/test/test_properties.py::test_id_property_wrong_type", "stix2/test/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--foo]", "stix2/test/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--00000000-0000-0000-0000-000000000000]", "stix2/test/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--04738bdf-b25a-3829-a801-b21a1d25095b]", "stix2/test/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--aad03681-8b63-5304-89e0-8ca8f49461b5]", "stix2/test/test_properties.py::test_id_property_default", "stix2/test/test_properties.py::test_integer_property_valid[2]", "stix2/test/test_properties.py::test_integer_property_valid[-1]", "stix2/test/test_properties.py::test_integer_property_valid[3.14]", "stix2/test/test_properties.py::test_integer_property_valid[False]", "stix2/test/test_properties.py::test_integer_property_invalid[something]", "stix2/test/test_properties.py::test_integer_property_invalid[value1]", "stix2/test/test_properties.py::test_float_property_valid[2]", "stix2/test/test_properties.py::test_float_property_valid[-1]", "stix2/test/test_properties.py::test_float_property_valid[3.14]", "stix2/test/test_properties.py::test_float_property_valid[False]", "stix2/test/test_properties.py::test_float_property_invalid[something]", "stix2/test/test_properties.py::test_float_property_invalid[value1]", "stix2/test/test_properties.py::test_boolean_property_valid[True0]", "stix2/test/test_properties.py::test_boolean_property_valid[False0]", "stix2/test/test_properties.py::test_boolean_property_valid[True1]", "stix2/test/test_properties.py::test_boolean_property_valid[False1]", "stix2/test/test_properties.py::test_boolean_property_valid[true]", "stix2/test/test_properties.py::test_boolean_property_valid[false]", "stix2/test/test_properties.py::test_boolean_property_valid[TRUE]", "stix2/test/test_properties.py::test_boolean_property_valid[FALSE]", "stix2/test/test_properties.py::test_boolean_property_valid[T]", "stix2/test/test_properties.py::test_boolean_property_valid[F]", "stix2/test/test_properties.py::test_boolean_property_valid[t]", "stix2/test/test_properties.py::test_boolean_property_valid[f]", "stix2/test/test_properties.py::test_boolean_property_valid[1]", "stix2/test/test_properties.py::test_boolean_property_valid[0]", "stix2/test/test_properties.py::test_boolean_property_invalid[abc]", "stix2/test/test_properties.py::test_boolean_property_invalid[value1]", "stix2/test/test_properties.py::test_boolean_property_invalid[value2]", "stix2/test/test_properties.py::test_boolean_property_invalid[2]", "stix2/test/test_properties.py::test_boolean_property_invalid[-1]", "stix2/test/test_properties.py::test_reference_property", "stix2/test/test_properties.py::test_timestamp_property_valid[2017-01-01T12:34:56Z]", "stix2/test/test_properties.py::test_timestamp_property_valid[2017-01-01", "stix2/test/test_properties.py::test_timestamp_property_valid[Jan", "stix2/test/test_properties.py::test_timestamp_property_invalid", "stix2/test/test_properties.py::test_binary_property", "stix2/test/test_properties.py::test_hex_property", "stix2/test/test_properties.py::test_dictionary_property_valid[d0]", "stix2/test/test_properties.py::test_dictionary_property_valid[d1]", "stix2/test/test_properties.py::test_dictionary_property_invalid_key[d0]", "stix2/test/test_properties.py::test_dictionary_property_invalid_key[d1]", "stix2/test/test_properties.py::test_dictionary_property_invalid_key[d2]", "stix2/test/test_properties.py::test_dictionary_property_invalid[d0]", "stix2/test/test_properties.py::test_dictionary_property_invalid[d1]", "stix2/test/test_properties.py::test_property_list_of_dictionary", "stix2/test/test_properties.py::test_hashes_property_valid[value1]", "stix2/test/test_properties.py::test_hashes_property_invalid[value0]", "stix2/test/test_properties.py::test_hashes_property_invalid[value1]", "stix2/test/test_properties.py::test_embedded_property", "stix2/test/test_properties.py::test_enum_property_valid[value0]", "stix2/test/test_properties.py::test_enum_property_valid[value1]", "stix2/test/test_properties.py::test_enum_property_valid[b]", "stix2/test/test_properties.py::test_enum_property_invalid", "stix2/test/test_properties.py::test_extension_property_valid", "stix2/test/test_properties.py::test_extension_property_invalid[1]", "stix2/test/test_properties.py::test_extension_property_invalid[data1]", "stix2/test/test_properties.py::test_extension_at_least_one_property_constraint" ]
2018-11-01 21:28:16+00:00
4,286
oasis-open__cti-python-stix2-237
diff --git a/stix2/properties.py b/stix2/properties.py index 24549aa..d6cc624 100644 --- a/stix2/properties.py +++ b/stix2/properties.py @@ -11,7 +11,7 @@ import uuid from six import string_types, text_type from stix2patterns.validator import run_validator -from .base import _STIXBase +from .base import _Observable, _STIXBase from .core import STIX2_OBJ_MAPS, parse, parse_observable from .exceptions import CustomContentError, DictionaryKeyError from .utils import _get_dict, get_class_hierarchy_names, parse_into_datetime @@ -167,6 +167,19 @@ class ListProperty(Property): return result +class CallableValues(list): + """Wrapper to allow `values()` method on WindowsRegistryKey objects. + Needed because `values` is also a property. + """ + + def __init__(self, parent_instance, *args, **kwargs): + self.parent_instance = parent_instance + super(CallableValues, self).__init__(*args, **kwargs) + + def __call__(self): + return _Observable.values(self.parent_instance) + + class StringProperty(Property): def __init__(self, **kwargs): @@ -291,8 +304,6 @@ class DictionaryProperty(Property): dictified = _get_dict(value) except ValueError: raise ValueError("The dictionary property must contain a dictionary") - if dictified == {}: - raise ValueError("The dictionary property must contain a non-empty dictionary") for k in dictified.keys(): if self.spec_version == '2.0': if len(k) < 3: @@ -498,8 +509,6 @@ class ExtensionsProperty(DictionaryProperty): dictified = copy.deepcopy(dictified) except ValueError: raise ValueError("The extensions property must contain a dictionary") - if dictified == {}: - raise ValueError("The extensions property must contain a non-empty dictionary") v = 'v' + self.spec_version.replace('.', '') diff --git a/stix2/v20/observables.py b/stix2/v20/observables.py index 0e7c4a0..55872cd 100644 --- a/stix2/v20/observables.py +++ b/stix2/v20/observables.py @@ -12,7 +12,7 @@ from ..base import _Extension, _Observable, _STIXBase from ..custom import _custom_extension_builder, _custom_observable_builder from ..exceptions import AtLeastOnePropertyError, DependentPropertiesError from ..properties import ( - BinaryProperty, BooleanProperty, DictionaryProperty, + BinaryProperty, BooleanProperty, CallableValues, DictionaryProperty, EmbeddedObjectProperty, EnumProperty, ExtensionsProperty, FloatProperty, HashesProperty, HexProperty, IntegerProperty, ListProperty, ObjectReferenceProperty, StringProperty, TimestampProperty, TypeProperty, @@ -726,7 +726,7 @@ class WindowsRegistryKey(_Observable): @property def values(self): # Needed because 'values' is a property on collections.Mapping objects - return self._inner['values'] + return CallableValues(self, self._inner['values']) class X509V3ExtenstionsType(_STIXBase): diff --git a/stix2/v21/observables.py b/stix2/v21/observables.py index 1b2251d..f383899 100644 --- a/stix2/v21/observables.py +++ b/stix2/v21/observables.py @@ -12,7 +12,7 @@ from ..base import _Extension, _Observable, _STIXBase from ..custom import _custom_extension_builder, _custom_observable_builder from ..exceptions import AtLeastOnePropertyError, DependentPropertiesError from ..properties import ( - BinaryProperty, BooleanProperty, DictionaryProperty, + BinaryProperty, BooleanProperty, CallableValues, DictionaryProperty, EmbeddedObjectProperty, EnumProperty, ExtensionsProperty, FloatProperty, HashesProperty, HexProperty, IntegerProperty, ListProperty, ObjectReferenceProperty, StringProperty, TimestampProperty, TypeProperty, @@ -779,7 +779,7 @@ class WindowsRegistryKey(_Observable): @property def values(self): # Needed because 'values' is a property on collections.Mapping objects - return self._inner['values'] + return CallableValues(self, self._inner['values']) class X509V3ExtenstionsType(_STIXBase):
oasis-open/cti-python-stix2
06e23b08b8877bedc909889800682eec16a219c9
diff --git a/stix2/test/v20/test_observed_data.py b/stix2/test/v20/test_observed_data.py index 41a80d6..c186361 100644 --- a/stix2/test/v20/test_observed_data.py +++ b/stix2/test/v20/test_observed_data.py @@ -1141,12 +1141,13 @@ def test_process_example_windows_process_ext_empty(): def test_process_example_extensions_empty(): - with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo: - stix2.v20.Process(extensions={}) + proc = stix2.v20.Process( + pid=314, + name="foobar.exe", + extensions={}, + ) - assert excinfo.value.cls == stix2.v20.Process - assert excinfo.value.prop_name == 'extensions' - assert 'non-empty dictionary' in excinfo.value.reason + assert '{}' in str(proc) def test_process_example_with_WindowsProcessExt_Object(): @@ -1290,6 +1291,8 @@ def test_windows_registry_key_example(): assert w.values[0].name == "Foo" assert w.values[0].data == "qwerty" assert w.values[0].data_type == "REG_SZ" + # ensure no errors in serialization because of 'values' + assert "Foo" in str(w) def test_x509_certificate_example(): diff --git a/stix2/test/v20/test_properties.py b/stix2/test/v20/test_properties.py index 24c1c99..e9a513e 100644 --- a/stix2/test/v20/test_properties.py +++ b/stix2/test/v20/test_properties.py @@ -360,7 +360,6 @@ def test_dictionary_property_invalid_key(d): @pytest.mark.parametrize( "d", [ - ({}, "The dictionary property must contain a non-empty dictionary"), # TODO: This error message could be made more helpful. The error is caused # because `json.loads()` doesn't like the *single* quotes around the key # name, even though they are valid in a Python dictionary. While technically diff --git a/stix2/test/v21/test_observed_data.py b/stix2/test/v21/test_observed_data.py index 5a5881a..eb811b2 100644 --- a/stix2/test/v21/test_observed_data.py +++ b/stix2/test/v21/test_observed_data.py @@ -1115,12 +1115,12 @@ def test_process_example_windows_process_ext_empty(): def test_process_example_extensions_empty(): - with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo: - stix2.v21.Process(extensions={}) + proc = stix2.v21.Process( + pid=314, + extensions={}, + ) - assert excinfo.value.cls == stix2.v21.Process - assert excinfo.value.prop_name == 'extensions' - assert 'non-empty dictionary' in excinfo.value.reason + assert '{}' in str(proc) def test_process_example_with_WindowsProcessExt_Object(): @@ -1264,6 +1264,8 @@ def test_windows_registry_key_example(): assert w.values[0].name == "Foo" assert w.values[0].data == "qwerty" assert w.values[0].data_type == "REG_SZ" + # ensure no errors in serialization because of 'values' + assert "Foo" in str(w) def test_x509_certificate_example(): diff --git a/stix2/test/v21/test_properties.py b/stix2/test/v21/test_properties.py index 611ec5e..298a8df 100644 --- a/stix2/test/v21/test_properties.py +++ b/stix2/test/v21/test_properties.py @@ -369,7 +369,6 @@ def test_dictionary_property_invalid_key(d): @pytest.mark.parametrize( "d", [ - ({}, "The dictionary property must contain a non-empty dictionary"), # TODO: This error message could be made more helpful. The error is caused # because `json.loads()` doesn't like the *single* quotes around the key # name, even though they are valid in a Python dictionary. While technically
WindowsRegistryKey fails to print I am not sure if I am doing something wrong but trying to print a WindowsRegistryKey object always fails, even when using the provided example. ``` def test_key(): v = stix2.v21.WindowsRegistryValueType( name="Foo", data="qwerty", data_type="REG_SZ", ) w = stix2.v21.WindowsRegistryKey( key="hkey_local_machine\\system\\bar\\foo", values=[v], ) print(v) print(w) assert w.key == "hkey_local_machine\\system\\bar\\foo" assert w.values[0].name == "Foo" assert w.values[0].data == "qwerty" assert w.values[0].data_type == "REG_SZ" ``` Output ``` { "name": "Foo", "data": "qwerty", "data_type": "REG_SZ" } Traceback (most recent call last): File "sandbox_to_stix.py", line 341, in <module> test_key() File "sandbox_to_stix.py", line 294, in test_key print(w) File "/home/timngo/venvs/stix/lib/python3.6/site-packages/stix2/base.py", line 206, in __str__ return self.serialize(pretty=True) File "/home/timngo/venvs/stix/lib/python3.6/site-packages/stix2/base.py", line 284, in serialize return json.dumps(self, cls=STIXJSONEncoder, **kwargs) File "/home/timngo/venvs/stix/lib/python3.6/site-packages/simplejson/__init__.py", line 399, in dumps **kw).encode(obj) File "/home/timngo/venvs/stix/lib/python3.6/site-packages/simplejson/encoder.py", line 298, in encode chunks = list(chunks) File "/home/timngo/venvs/stix/lib/python3.6/site-packages/simplejson/encoder.py", line 717, in _iterencode for chunk in _iterencode(o, _current_indent_level): File "/home/timngo/venvs/stix/lib/python3.6/site-packages/simplejson/encoder.py", line 696, in _iterencode for chunk in _iterencode_dict(o, _current_indent_level): File "/home/timngo/venvs/stix/lib/python3.6/site-packages/simplejson/encoder.py", line 652, in _iterencode_dict for chunk in chunks: File "/home/timngo/venvs/stix/lib/python3.6/site-packages/simplejson/encoder.py", line 531, in _iterencode_list for chunk in chunks: File "/home/timngo/venvs/stix/lib/python3.6/site-packages/simplejson/encoder.py", line 717, in _iterencode for chunk in _iterencode(o, _current_indent_level): File "/home/timngo/venvs/stix/lib/python3.6/site-packages/simplejson/encoder.py", line 696, in _iterencode for chunk in _iterencode_dict(o, _current_indent_level): File "/home/timngo/venvs/stix/lib/python3.6/site-packages/simplejson/encoder.py", line 602, in _iterencode_dict items.sort(key=_item_sort_key) File "/home/timngo/venvs/stix/lib/python3.6/site-packages/stix2/base.py", line 277, in sort_by return find_property_index(self, *element) File "/home/timngo/venvs/stix/lib/python3.6/site-packages/stix2/utils.py", line 240, in find_property_index idx = _find_property_in_seq(obj.values(), search_key, search_value) TypeError: 'list' object is not callable ``` I noticed that commenting out the values() getter function in stix2/v21/observables.py will get the print working but then the assert fails since there is no getter ``` class WindowsRegistryKey(_Observable): # TODO: Add link """For more detailed information on this object's properties, see `the STIX 2.1 specification <link here>`__. """ _type = 'windows-registry-key' _properties = OrderedDict([ ('type', TypeProperty(_type)), ('key', StringProperty()), ('values', ListProperty(EmbeddedObjectProperty(type=WindowsRegistryValueType))), # this is not the modified timestamps of the object itself ('modified', TimestampProperty()), ('creator_user_ref', ObjectReferenceProperty(valid_types='user-account')), ('number_of_subkeys', IntegerProperty()), ('extensions', ExtensionsProperty(spec_version='2.1', enclosing_type=_type)), ]) #@property #def values(self): # Needed because 'values' is a property on collections.Mapping objects # return self._inner['values'] ``` New Output ``` { "name": "Foo", "data": "qwerty", "data_type": "REG_SZ" } { "type": "windows-registry-key", "key": "hkey_local_machine\\system\\bar\\foo", "values": [ { "name": "Foo", "data": "qwerty", "data_type": "REG_SZ" } ] } Traceback (most recent call last): File "sandbox_to_stix.py", line 341, in <module> test_key() File "sandbox_to_stix.py", line 296, in test_key assert w.values[0].name == "Foo" TypeError: 'method' object is not subscriptable ```
0.0
[ "stix2/test/v20/test_observed_data.py::test_process_example_extensions_empty", "stix2/test/v20/test_observed_data.py::test_windows_registry_key_example", "stix2/test/v20/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--7e70bea4-5779-11ef-af1a-fa3cdcf14c24]", "stix2/test/v21/test_observed_data.py::test_process_example_extensions_empty", "stix2/test/v21/test_observed_data.py::test_windows_registry_key_example", "stix2/test/v21/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--7e76d82a-5779-11ef-af1a-fa3cdcf14c24]" ]
[ "stix2/test/v20/test_observed_data.py::test_observed_data_example", "stix2/test/v20/test_observed_data.py::test_observed_data_example_with_refs", "stix2/test/v20/test_observed_data.py::test_observed_data_example_with_bad_refs", "stix2/test/v20/test_observed_data.py::test_observed_data_example_with_non_dictionary", "stix2/test/v20/test_observed_data.py::test_observed_data_example_with_empty_dictionary", "stix2/test/v20/test_observed_data.py::test_parse_observed_data[{\\n", "stix2/test/v20/test_observed_data.py::test_parse_observed_data[data1]", "stix2/test/v20/test_observed_data.py::test_parse_artifact_valid[\"0\":", "stix2/test/v20/test_observed_data.py::test_parse_artifact_invalid[\"0\":", "stix2/test/v20/test_observed_data.py::test_artifact_example_dependency_error", "stix2/test/v20/test_observed_data.py::test_parse_autonomous_system_valid[\"0\":", "stix2/test/v20/test_observed_data.py::test_parse_email_address[{\\n", "stix2/test/v20/test_observed_data.py::test_parse_email_message[\\n", "stix2/test/v20/test_observed_data.py::test_parse_email_message_not_multipart[\\n", "stix2/test/v20/test_observed_data.py::test_parse_file_archive[\"0\":", "stix2/test/v20/test_observed_data.py::test_parse_email_message_with_at_least_one_error[\\n", "stix2/test/v20/test_observed_data.py::test_parse_basic_tcp_traffic[\\n", "stix2/test/v20/test_observed_data.py::test_parse_basic_tcp_traffic_with_error[\\n", "stix2/test/v20/test_observed_data.py::test_observed_data_with_process_example", "stix2/test/v20/test_observed_data.py::test_artifact_example", "stix2/test/v20/test_observed_data.py::test_artifact_mutual_exclusion_error", "stix2/test/v20/test_observed_data.py::test_directory_example", "stix2/test/v20/test_observed_data.py::test_directory_example_ref_error", "stix2/test/v20/test_observed_data.py::test_domain_name_example", "stix2/test/v20/test_observed_data.py::test_domain_name_example_invalid_ref_type", "stix2/test/v20/test_observed_data.py::test_file_example", "stix2/test/v20/test_observed_data.py::test_file_example_with_NTFSExt", "stix2/test/v20/test_observed_data.py::test_file_example_with_empty_NTFSExt", "stix2/test/v20/test_observed_data.py::test_file_example_with_PDFExt", "stix2/test/v20/test_observed_data.py::test_file_example_with_PDFExt_Object", "stix2/test/v20/test_observed_data.py::test_file_example_with_RasterImageExt_Object", "stix2/test/v20/test_observed_data.py::test_raster_image_ext_parse", "stix2/test/v20/test_observed_data.py::test_raster_images_ext_create", "stix2/test/v20/test_observed_data.py::test_file_example_with_WindowsPEBinaryExt", "stix2/test/v20/test_observed_data.py::test_file_example_encryption_error", "stix2/test/v20/test_observed_data.py::test_ip4_address_example", "stix2/test/v20/test_observed_data.py::test_ip4_address_example_cidr", "stix2/test/v20/test_observed_data.py::test_ip6_address_example", "stix2/test/v20/test_observed_data.py::test_mac_address_example", "stix2/test/v20/test_observed_data.py::test_network_traffic_example", "stix2/test/v20/test_observed_data.py::test_network_traffic_http_request_example", "stix2/test/v20/test_observed_data.py::test_network_traffic_icmp_example", "stix2/test/v20/test_observed_data.py::test_network_traffic_socket_example", "stix2/test/v20/test_observed_data.py::test_network_traffic_tcp_example", "stix2/test/v20/test_observed_data.py::test_mutex_example", "stix2/test/v20/test_observed_data.py::test_process_example", "stix2/test/v20/test_observed_data.py::test_process_example_empty_error", "stix2/test/v20/test_observed_data.py::test_process_example_empty_with_extensions", "stix2/test/v20/test_observed_data.py::test_process_example_windows_process_ext", "stix2/test/v20/test_observed_data.py::test_process_example_windows_process_ext_empty", "stix2/test/v20/test_observed_data.py::test_process_example_with_WindowsProcessExt_Object", "stix2/test/v20/test_observed_data.py::test_process_example_with_WindowsServiceExt", "stix2/test/v20/test_observed_data.py::test_process_example_with_WindowsProcessServiceExt", "stix2/test/v20/test_observed_data.py::test_software_example", "stix2/test/v20/test_observed_data.py::test_url_example", "stix2/test/v20/test_observed_data.py::test_user_account_example", "stix2/test/v20/test_observed_data.py::test_user_account_unix_account_ext_example", "stix2/test/v20/test_observed_data.py::test_x509_certificate_example", "stix2/test/v20/test_observed_data.py::test_new_version_with_related_objects", "stix2/test/v20/test_properties.py::test_property", "stix2/test/v20/test_properties.py::test_basic_clean", "stix2/test/v20/test_properties.py::test_property_default", "stix2/test/v20/test_properties.py::test_fixed_property", "stix2/test/v20/test_properties.py::test_list_property", "stix2/test/v20/test_properties.py::test_string_property", "stix2/test/v20/test_properties.py::test_type_property", "stix2/test/v20/test_properties.py::test_id_property_valid[my-type--232c9d3f-49fc-4440-bb01-607f638778e7]", "stix2/test/v20/test_properties.py::test_id_property_valid[my-type--00000000-0000-4000-8000-000000000000]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[attack-pattern--0c7b5b88-8ff7-4a4d-aa9d-feb398cd0061]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[campaign--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[course-of-action--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[identity--311b2d2d-f010-4473-83ec-1edf84858f4c]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[indicator--a740531e-63ff-4e49-a9e1-a0a3eed0e3e7]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[intrusion-set--4e78f46f-a023-4e5f-bc24-71b3ca22ec29]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[malware--9c4638ec-f1de-4ddb-abf4-1b760417654e]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9_0]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[observed-data--b67d30ff-02ac-498a-92f9-32f845f448cf]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[relationship--df7c87eb-75d2-4948-af81-9d49d246f301]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[report--84e4d88f-44ea-4bcd-bbf3-b2c1c320bcb3]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[sighting--bfbc19db-ec35-4e45-beed-f8bde2a772fb]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[threat-actor--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[tool--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[vulnerability--0c7b5b88-8ff7-4a4d-aa9d-feb398cd0061]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9_1]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[marking-definition--443eb5c3-a76c-4a0a-8caa-e93998e7bc09]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[marking-definition--57fcd772-9c1d-41b0-8d1f-3d47713415d9]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[marking-definition--462bf1a6-03d2-419c-b74e-eee2238b2de4]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[marking-definition--68520ae2-fefe-43a9-84ee-2c2a934d2c7d]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[marking-definition--2802dfb1-1019-40a8-8848-68d0ec0e417f]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[relationship--06520621-5352-4e6a-b976-e8fa3d437ffd]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[relationship--181c9c09-43e6-45dd-9374-3bec192f05ef]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[relationship--a0cbb21c-8daf-4a7f-96aa-7155a4ef8f70]", "stix2/test/v20/test_properties.py::test_id_property_wrong_type", "stix2/test/v20/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--foo]", "stix2/test/v20/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--00000000-0000-0000-0000-000000000000]", "stix2/test/v20/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--04738bdf-b25a-3829-a801-b21a1d25095b]", "stix2/test/v20/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--aad03681-8b63-5304-89e0-8ca8f49461b5]", "stix2/test/v20/test_properties.py::test_id_property_default", "stix2/test/v20/test_properties.py::test_integer_property_valid[2]", "stix2/test/v20/test_properties.py::test_integer_property_valid[-1]", "stix2/test/v20/test_properties.py::test_integer_property_valid[3.14]", "stix2/test/v20/test_properties.py::test_integer_property_valid[False]", "stix2/test/v20/test_properties.py::test_integer_property_invalid_min_with_constraints[-1]", "stix2/test/v20/test_properties.py::test_integer_property_invalid_min_with_constraints[-100]", "stix2/test/v20/test_properties.py::test_integer_property_invalid_min_with_constraints[-30]", "stix2/test/v20/test_properties.py::test_integer_property_invalid_max_with_constraints[181]", "stix2/test/v20/test_properties.py::test_integer_property_invalid_max_with_constraints[200]", "stix2/test/v20/test_properties.py::test_integer_property_invalid_max_with_constraints[300]", "stix2/test/v20/test_properties.py::test_integer_property_invalid[something]", "stix2/test/v20/test_properties.py::test_integer_property_invalid[value1]", "stix2/test/v20/test_properties.py::test_float_property_valid[2]", "stix2/test/v20/test_properties.py::test_float_property_valid[-1]", "stix2/test/v20/test_properties.py::test_float_property_valid[3.14]", "stix2/test/v20/test_properties.py::test_float_property_valid[False]", "stix2/test/v20/test_properties.py::test_float_property_invalid[something]", "stix2/test/v20/test_properties.py::test_float_property_invalid[value1]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[True0]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[False0]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[True1]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[False1]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[true]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[false]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[TRUE]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[FALSE]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[T]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[F]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[t]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[f]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[1]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[0]", "stix2/test/v20/test_properties.py::test_boolean_property_invalid[abc]", "stix2/test/v20/test_properties.py::test_boolean_property_invalid[value1]", "stix2/test/v20/test_properties.py::test_boolean_property_invalid[value2]", "stix2/test/v20/test_properties.py::test_boolean_property_invalid[2]", "stix2/test/v20/test_properties.py::test_boolean_property_invalid[-1]", "stix2/test/v20/test_properties.py::test_reference_property", "stix2/test/v20/test_properties.py::test_timestamp_property_valid[2017-01-01T12:34:56Z]", "stix2/test/v20/test_properties.py::test_timestamp_property_valid[2017-01-01", "stix2/test/v20/test_properties.py::test_timestamp_property_valid[Jan", "stix2/test/v20/test_properties.py::test_timestamp_property_invalid", "stix2/test/v20/test_properties.py::test_binary_property", "stix2/test/v20/test_properties.py::test_hex_property", "stix2/test/v20/test_properties.py::test_dictionary_property_valid[d0]", "stix2/test/v20/test_properties.py::test_dictionary_property_valid[d1]", "stix2/test/v20/test_properties.py::test_dictionary_property_invalid_key[d0]", "stix2/test/v20/test_properties.py::test_dictionary_property_invalid_key[d1]", "stix2/test/v20/test_properties.py::test_dictionary_property_invalid_key[d2]", "stix2/test/v20/test_properties.py::test_dictionary_property_invalid[d0]", "stix2/test/v20/test_properties.py::test_property_list_of_dictionary", "stix2/test/v20/test_properties.py::test_hashes_property_valid[value1]", "stix2/test/v20/test_properties.py::test_hashes_property_invalid[value0]", "stix2/test/v20/test_properties.py::test_hashes_property_invalid[value1]", "stix2/test/v20/test_properties.py::test_embedded_property", "stix2/test/v20/test_properties.py::test_enum_property_valid[value0]", "stix2/test/v20/test_properties.py::test_enum_property_valid[value1]", "stix2/test/v20/test_properties.py::test_enum_property_valid[b]", "stix2/test/v20/test_properties.py::test_enum_property_invalid", "stix2/test/v20/test_properties.py::test_extension_property_valid", "stix2/test/v20/test_properties.py::test_extension_property_invalid[1]", "stix2/test/v20/test_properties.py::test_extension_property_invalid[data1]", "stix2/test/v20/test_properties.py::test_extension_property_invalid_type", "stix2/test/v20/test_properties.py::test_extension_at_least_one_property_constraint", "stix2/test/v20/test_properties.py::test_marking_property_error", "stix2/test/v20/test_properties.py::test_stix_property_not_compliant_spec", "stix2/test/v21/test_observed_data.py::test_observed_data_example", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_refs", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_bad_refs", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_non_dictionary", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_empty_dictionary", "stix2/test/v21/test_observed_data.py::test_parse_observed_data[{\\n", "stix2/test/v21/test_observed_data.py::test_parse_observed_data[data1]", "stix2/test/v21/test_observed_data.py::test_parse_artifact_valid[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_artifact_invalid[\"0\":", "stix2/test/v21/test_observed_data.py::test_artifact_example_dependency_error", "stix2/test/v21/test_observed_data.py::test_parse_autonomous_system_valid[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_email_address[{\\n", "stix2/test/v21/test_observed_data.py::test_parse_email_message[\\n", "stix2/test/v21/test_observed_data.py::test_parse_email_message_not_multipart[\\n", "stix2/test/v21/test_observed_data.py::test_parse_file_archive[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_email_message_with_at_least_one_error[\\n", "stix2/test/v21/test_observed_data.py::test_parse_basic_tcp_traffic[\\n", "stix2/test/v21/test_observed_data.py::test_parse_basic_tcp_traffic_with_error[\\n", "stix2/test/v21/test_observed_data.py::test_observed_data_with_process_example", "stix2/test/v21/test_observed_data.py::test_artifact_example", "stix2/test/v21/test_observed_data.py::test_artifact_mutual_exclusion_error", "stix2/test/v21/test_observed_data.py::test_directory_example", "stix2/test/v21/test_observed_data.py::test_directory_example_ref_error", "stix2/test/v21/test_observed_data.py::test_domain_name_example", "stix2/test/v21/test_observed_data.py::test_domain_name_example_invalid_ref_type", "stix2/test/v21/test_observed_data.py::test_file_example", "stix2/test/v21/test_observed_data.py::test_file_example_with_NTFSExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_empty_NTFSExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_PDFExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_PDFExt_Object", "stix2/test/v21/test_observed_data.py::test_file_example_with_RasterImageExt_Object", "stix2/test/v21/test_observed_data.py::test_raster_image_ext_parse", "stix2/test/v21/test_observed_data.py::test_raster_images_ext_create", "stix2/test/v21/test_observed_data.py::test_file_example_with_WindowsPEBinaryExt", "stix2/test/v21/test_observed_data.py::test_file_example_encryption_error", "stix2/test/v21/test_observed_data.py::test_ip4_address_example", "stix2/test/v21/test_observed_data.py::test_ip4_address_example_cidr", "stix2/test/v21/test_observed_data.py::test_ip6_address_example", "stix2/test/v21/test_observed_data.py::test_mac_address_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_http_request_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_icmp_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_socket_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_tcp_example", "stix2/test/v21/test_observed_data.py::test_mutex_example", "stix2/test/v21/test_observed_data.py::test_process_example", "stix2/test/v21/test_observed_data.py::test_process_example_empty_error", "stix2/test/v21/test_observed_data.py::test_process_example_empty_with_extensions", "stix2/test/v21/test_observed_data.py::test_process_example_windows_process_ext", "stix2/test/v21/test_observed_data.py::test_process_example_windows_process_ext_empty", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsProcessExt_Object", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsServiceExt", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsProcessServiceExt", "stix2/test/v21/test_observed_data.py::test_software_example", "stix2/test/v21/test_observed_data.py::test_url_example", "stix2/test/v21/test_observed_data.py::test_user_account_example", "stix2/test/v21/test_observed_data.py::test_user_account_unix_account_ext_example", "stix2/test/v21/test_observed_data.py::test_x509_certificate_example", "stix2/test/v21/test_observed_data.py::test_new_version_with_related_objects", "stix2/test/v21/test_properties.py::test_property", "stix2/test/v21/test_properties.py::test_basic_clean", "stix2/test/v21/test_properties.py::test_property_default", "stix2/test/v21/test_properties.py::test_fixed_property", "stix2/test/v21/test_properties.py::test_list_property", "stix2/test/v21/test_properties.py::test_string_property", "stix2/test/v21/test_properties.py::test_type_property", "stix2/test/v21/test_properties.py::test_id_property_valid[my-type--232c9d3f-49fc-4440-bb01-607f638778e7]", "stix2/test/v21/test_properties.py::test_id_property_valid[my-type--00000000-0000-4000-8000-000000000000]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[attack-pattern--0c7b5b88-8ff7-4a4d-aa9d-feb398cd0061]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[campaign--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[course-of-action--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[identity--311b2d2d-f010-4473-83ec-1edf84858f4c]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[indicator--a740531e-63ff-4e49-a9e1-a0a3eed0e3e7]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[intrusion-set--4e78f46f-a023-4e5f-bc24-71b3ca22ec29]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[malware--9c4638ec-f1de-4ddb-abf4-1b760417654e]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9_0]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[observed-data--b67d30ff-02ac-498a-92f9-32f845f448cf]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[relationship--df7c87eb-75d2-4948-af81-9d49d246f301]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[report--84e4d88f-44ea-4bcd-bbf3-b2c1c320bcb3]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[sighting--bfbc19db-ec35-4e45-beed-f8bde2a772fb]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[threat-actor--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[tool--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[vulnerability--0c7b5b88-8ff7-4a4d-aa9d-feb398cd0061]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9_1]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[marking-definition--443eb5c3-a76c-4a0a-8caa-e93998e7bc09]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[marking-definition--57fcd772-9c1d-41b0-8d1f-3d47713415d9]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[marking-definition--462bf1a6-03d2-419c-b74e-eee2238b2de4]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[marking-definition--68520ae2-fefe-43a9-84ee-2c2a934d2c7d]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[marking-definition--2802dfb1-1019-40a8-8848-68d0ec0e417f]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[relationship--06520621-5352-4e6a-b976-e8fa3d437ffd]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[relationship--181c9c09-43e6-45dd-9374-3bec192f05ef]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[relationship--a0cbb21c-8daf-4a7f-96aa-7155a4ef8f70]", "stix2/test/v21/test_properties.py::test_id_property_wrong_type", "stix2/test/v21/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--foo]", "stix2/test/v21/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--00000000-0000-0000-0000-000000000000]", "stix2/test/v21/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--04738bdf-b25a-3829-a801-b21a1d25095b]", "stix2/test/v21/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--aad03681-8b63-5304-89e0-8ca8f49461b5]", "stix2/test/v21/test_properties.py::test_id_property_default", "stix2/test/v21/test_properties.py::test_integer_property_valid[2]", "stix2/test/v21/test_properties.py::test_integer_property_valid[-1]", "stix2/test/v21/test_properties.py::test_integer_property_valid[3.14]", "stix2/test/v21/test_properties.py::test_integer_property_valid[False]", "stix2/test/v21/test_properties.py::test_integer_property_invalid_min_with_constraints[-1]", "stix2/test/v21/test_properties.py::test_integer_property_invalid_min_with_constraints[-100]", "stix2/test/v21/test_properties.py::test_integer_property_invalid_min_with_constraints[-300]", "stix2/test/v21/test_properties.py::test_integer_property_invalid_max_with_constraints[181]", "stix2/test/v21/test_properties.py::test_integer_property_invalid_max_with_constraints[200]", "stix2/test/v21/test_properties.py::test_integer_property_invalid_max_with_constraints[300]", "stix2/test/v21/test_properties.py::test_integer_property_invalid[something]", "stix2/test/v21/test_properties.py::test_integer_property_invalid[value1]", "stix2/test/v21/test_properties.py::test_float_property_valid[2]", "stix2/test/v21/test_properties.py::test_float_property_valid[-1]", "stix2/test/v21/test_properties.py::test_float_property_valid[3.14]", "stix2/test/v21/test_properties.py::test_float_property_valid[False]", "stix2/test/v21/test_properties.py::test_float_property_invalid[something]", "stix2/test/v21/test_properties.py::test_float_property_invalid[value1]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[True0]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[False0]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[True1]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[False1]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[true]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[false]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[TRUE]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[FALSE]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[T]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[F]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[t]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[f]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[1]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[0]", "stix2/test/v21/test_properties.py::test_boolean_property_invalid[abc]", "stix2/test/v21/test_properties.py::test_boolean_property_invalid[value1]", "stix2/test/v21/test_properties.py::test_boolean_property_invalid[value2]", "stix2/test/v21/test_properties.py::test_boolean_property_invalid[2]", "stix2/test/v21/test_properties.py::test_boolean_property_invalid[-1]", "stix2/test/v21/test_properties.py::test_reference_property", "stix2/test/v21/test_properties.py::test_timestamp_property_valid[2017-01-01T12:34:56Z]", "stix2/test/v21/test_properties.py::test_timestamp_property_valid[2017-01-01", "stix2/test/v21/test_properties.py::test_timestamp_property_valid[Jan", "stix2/test/v21/test_properties.py::test_timestamp_property_invalid", "stix2/test/v21/test_properties.py::test_binary_property", "stix2/test/v21/test_properties.py::test_hex_property", "stix2/test/v21/test_properties.py::test_dictionary_property_valid[d0]", "stix2/test/v21/test_properties.py::test_dictionary_property_valid[d1]", "stix2/test/v21/test_properties.py::test_dictionary_no_longer_raises[d0]", "stix2/test/v21/test_properties.py::test_dictionary_property_invalid_key[d0]", "stix2/test/v21/test_properties.py::test_dictionary_property_invalid_key[d1]", "stix2/test/v21/test_properties.py::test_dictionary_property_invalid[d0]", "stix2/test/v21/test_properties.py::test_property_list_of_dictionary", "stix2/test/v21/test_properties.py::test_hashes_property_valid[value1]", "stix2/test/v21/test_properties.py::test_hashes_property_invalid[value0]", "stix2/test/v21/test_properties.py::test_hashes_property_invalid[value1]", "stix2/test/v21/test_properties.py::test_embedded_property", "stix2/test/v21/test_properties.py::test_enum_property_valid[value0]", "stix2/test/v21/test_properties.py::test_enum_property_valid[value1]", "stix2/test/v21/test_properties.py::test_enum_property_valid[b]", "stix2/test/v21/test_properties.py::test_enum_property_invalid", "stix2/test/v21/test_properties.py::test_extension_property_valid", "stix2/test/v21/test_properties.py::test_extension_property_invalid[1]", "stix2/test/v21/test_properties.py::test_extension_property_invalid[data1]", "stix2/test/v21/test_properties.py::test_extension_property_invalid_type", "stix2/test/v21/test_properties.py::test_extension_at_least_one_property_constraint", "stix2/test/v21/test_properties.py::test_marking_property_error" ]
2018-12-21 19:36:07+00:00
4,287
oasis-open__cti-python-stix2-239
diff --git a/stix2/properties.py b/stix2/properties.py index 24549aa..7202f9a 100644 --- a/stix2/properties.py +++ b/stix2/properties.py @@ -291,8 +291,6 @@ class DictionaryProperty(Property): dictified = _get_dict(value) except ValueError: raise ValueError("The dictionary property must contain a dictionary") - if dictified == {}: - raise ValueError("The dictionary property must contain a non-empty dictionary") for k in dictified.keys(): if self.spec_version == '2.0': if len(k) < 3: @@ -498,8 +496,6 @@ class ExtensionsProperty(DictionaryProperty): dictified = copy.deepcopy(dictified) except ValueError: raise ValueError("The extensions property must contain a dictionary") - if dictified == {}: - raise ValueError("The extensions property must contain a non-empty dictionary") v = 'v' + self.spec_version.replace('.', '')
oasis-open/cti-python-stix2
06e23b08b8877bedc909889800682eec16a219c9
diff --git a/stix2/test/v20/test_observed_data.py b/stix2/test/v20/test_observed_data.py index 41a80d6..17d732e 100644 --- a/stix2/test/v20/test_observed_data.py +++ b/stix2/test/v20/test_observed_data.py @@ -1141,12 +1141,13 @@ def test_process_example_windows_process_ext_empty(): def test_process_example_extensions_empty(): - with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo: - stix2.v20.Process(extensions={}) + proc = stix2.v20.Process( + pid=314, + name="foobar.exe", + extensions={}, + ) - assert excinfo.value.cls == stix2.v20.Process - assert excinfo.value.prop_name == 'extensions' - assert 'non-empty dictionary' in excinfo.value.reason + assert '{}' in str(proc) def test_process_example_with_WindowsProcessExt_Object(): diff --git a/stix2/test/v20/test_properties.py b/stix2/test/v20/test_properties.py index 24c1c99..e9a513e 100644 --- a/stix2/test/v20/test_properties.py +++ b/stix2/test/v20/test_properties.py @@ -360,7 +360,6 @@ def test_dictionary_property_invalid_key(d): @pytest.mark.parametrize( "d", [ - ({}, "The dictionary property must contain a non-empty dictionary"), # TODO: This error message could be made more helpful. The error is caused # because `json.loads()` doesn't like the *single* quotes around the key # name, even though they are valid in a Python dictionary. While technically diff --git a/stix2/test/v21/test_observed_data.py b/stix2/test/v21/test_observed_data.py index 5a5881a..d2aaf52 100644 --- a/stix2/test/v21/test_observed_data.py +++ b/stix2/test/v21/test_observed_data.py @@ -1115,12 +1115,12 @@ def test_process_example_windows_process_ext_empty(): def test_process_example_extensions_empty(): - with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo: - stix2.v21.Process(extensions={}) + proc = stix2.v21.Process( + pid=314, + extensions={}, + ) - assert excinfo.value.cls == stix2.v21.Process - assert excinfo.value.prop_name == 'extensions' - assert 'non-empty dictionary' in excinfo.value.reason + assert '{}' in str(proc) def test_process_example_with_WindowsProcessExt_Object(): diff --git a/stix2/test/v21/test_properties.py b/stix2/test/v21/test_properties.py index 611ec5e..298a8df 100644 --- a/stix2/test/v21/test_properties.py +++ b/stix2/test/v21/test_properties.py @@ -369,7 +369,6 @@ def test_dictionary_property_invalid_key(d): @pytest.mark.parametrize( "d", [ - ({}, "The dictionary property must contain a non-empty dictionary"), # TODO: This error message could be made more helpful. The error is caused # because `json.loads()` doesn't like the *single* quotes around the key # name, even though they are valid in a Python dictionary. While technically
Creating LanguageContent object has error If you pass a language content object an empty contents dictionary, you get an exception saying it must be non-empty. I do not see anywhere in the 2.1 specification that requires this. ``` from stix2.v21 import LanguageContent, Campaign camp = Campaign(name='foo') LanguageContent(object_ref=camp.id, object_modified=camp.modified, contents={}) ``` produces: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/jmg/work/cti-i18n/p/lib/python2.7/site-packages/stix2/base.py", line 161, in __init__ self._check_property(prop_name, prop_metadata, setting_kwargs) File "/Users/jmg/work/cti-i18n/p/lib/python2.7/site-packages/stix2/base.py", line 94, in _check_property raise InvalidValueError(self.__class__, prop_name, reason=str(exc)) stix2.exceptions.InvalidValueError: Invalid value for LanguageContent 'contents': The dictionary property must contain a non-empty dictionary ```
0.0
[ "stix2/test/v20/test_observed_data.py::test_process_example_extensions_empty", "stix2/test/v20/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--cc4adbc4-577d-11ef-93b6-fa3cdcf14c24]", "stix2/test/v21/test_observed_data.py::test_process_example_extensions_empty", "stix2/test/v21/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--cc5010d0-577d-11ef-93b6-fa3cdcf14c24]" ]
[ "stix2/test/v20/test_observed_data.py::test_observed_data_example", "stix2/test/v20/test_observed_data.py::test_observed_data_example_with_refs", "stix2/test/v20/test_observed_data.py::test_observed_data_example_with_bad_refs", "stix2/test/v20/test_observed_data.py::test_observed_data_example_with_non_dictionary", "stix2/test/v20/test_observed_data.py::test_observed_data_example_with_empty_dictionary", "stix2/test/v20/test_observed_data.py::test_parse_observed_data[{\\n", "stix2/test/v20/test_observed_data.py::test_parse_observed_data[data1]", "stix2/test/v20/test_observed_data.py::test_parse_artifact_valid[\"0\":", "stix2/test/v20/test_observed_data.py::test_parse_artifact_invalid[\"0\":", "stix2/test/v20/test_observed_data.py::test_artifact_example_dependency_error", "stix2/test/v20/test_observed_data.py::test_parse_autonomous_system_valid[\"0\":", "stix2/test/v20/test_observed_data.py::test_parse_email_address[{\\n", "stix2/test/v20/test_observed_data.py::test_parse_email_message[\\n", "stix2/test/v20/test_observed_data.py::test_parse_email_message_not_multipart[\\n", "stix2/test/v20/test_observed_data.py::test_parse_file_archive[\"0\":", "stix2/test/v20/test_observed_data.py::test_parse_email_message_with_at_least_one_error[\\n", "stix2/test/v20/test_observed_data.py::test_parse_basic_tcp_traffic[\\n", "stix2/test/v20/test_observed_data.py::test_parse_basic_tcp_traffic_with_error[\\n", "stix2/test/v20/test_observed_data.py::test_observed_data_with_process_example", "stix2/test/v20/test_observed_data.py::test_artifact_example", "stix2/test/v20/test_observed_data.py::test_artifact_mutual_exclusion_error", "stix2/test/v20/test_observed_data.py::test_directory_example", "stix2/test/v20/test_observed_data.py::test_directory_example_ref_error", "stix2/test/v20/test_observed_data.py::test_domain_name_example", "stix2/test/v20/test_observed_data.py::test_domain_name_example_invalid_ref_type", "stix2/test/v20/test_observed_data.py::test_file_example", "stix2/test/v20/test_observed_data.py::test_file_example_with_NTFSExt", "stix2/test/v20/test_observed_data.py::test_file_example_with_empty_NTFSExt", "stix2/test/v20/test_observed_data.py::test_file_example_with_PDFExt", "stix2/test/v20/test_observed_data.py::test_file_example_with_PDFExt_Object", "stix2/test/v20/test_observed_data.py::test_file_example_with_RasterImageExt_Object", "stix2/test/v20/test_observed_data.py::test_raster_image_ext_parse", "stix2/test/v20/test_observed_data.py::test_raster_images_ext_create", "stix2/test/v20/test_observed_data.py::test_file_example_with_WindowsPEBinaryExt", "stix2/test/v20/test_observed_data.py::test_file_example_encryption_error", "stix2/test/v20/test_observed_data.py::test_ip4_address_example", "stix2/test/v20/test_observed_data.py::test_ip4_address_example_cidr", "stix2/test/v20/test_observed_data.py::test_ip6_address_example", "stix2/test/v20/test_observed_data.py::test_mac_address_example", "stix2/test/v20/test_observed_data.py::test_network_traffic_example", "stix2/test/v20/test_observed_data.py::test_network_traffic_http_request_example", "stix2/test/v20/test_observed_data.py::test_network_traffic_icmp_example", "stix2/test/v20/test_observed_data.py::test_network_traffic_socket_example", "stix2/test/v20/test_observed_data.py::test_network_traffic_tcp_example", "stix2/test/v20/test_observed_data.py::test_mutex_example", "stix2/test/v20/test_observed_data.py::test_process_example", "stix2/test/v20/test_observed_data.py::test_process_example_empty_error", "stix2/test/v20/test_observed_data.py::test_process_example_empty_with_extensions", "stix2/test/v20/test_observed_data.py::test_process_example_windows_process_ext", "stix2/test/v20/test_observed_data.py::test_process_example_windows_process_ext_empty", "stix2/test/v20/test_observed_data.py::test_process_example_with_WindowsProcessExt_Object", "stix2/test/v20/test_observed_data.py::test_process_example_with_WindowsServiceExt", "stix2/test/v20/test_observed_data.py::test_process_example_with_WindowsProcessServiceExt", "stix2/test/v20/test_observed_data.py::test_software_example", "stix2/test/v20/test_observed_data.py::test_url_example", "stix2/test/v20/test_observed_data.py::test_user_account_example", "stix2/test/v20/test_observed_data.py::test_user_account_unix_account_ext_example", "stix2/test/v20/test_observed_data.py::test_windows_registry_key_example", "stix2/test/v20/test_observed_data.py::test_x509_certificate_example", "stix2/test/v20/test_observed_data.py::test_new_version_with_related_objects", "stix2/test/v20/test_properties.py::test_property", "stix2/test/v20/test_properties.py::test_basic_clean", "stix2/test/v20/test_properties.py::test_property_default", "stix2/test/v20/test_properties.py::test_fixed_property", "stix2/test/v20/test_properties.py::test_list_property", "stix2/test/v20/test_properties.py::test_string_property", "stix2/test/v20/test_properties.py::test_type_property", "stix2/test/v20/test_properties.py::test_id_property_valid[my-type--232c9d3f-49fc-4440-bb01-607f638778e7]", "stix2/test/v20/test_properties.py::test_id_property_valid[my-type--00000000-0000-4000-8000-000000000000]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[attack-pattern--0c7b5b88-8ff7-4a4d-aa9d-feb398cd0061]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[campaign--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[course-of-action--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[identity--311b2d2d-f010-4473-83ec-1edf84858f4c]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[indicator--a740531e-63ff-4e49-a9e1-a0a3eed0e3e7]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[intrusion-set--4e78f46f-a023-4e5f-bc24-71b3ca22ec29]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[malware--9c4638ec-f1de-4ddb-abf4-1b760417654e]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9_0]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[observed-data--b67d30ff-02ac-498a-92f9-32f845f448cf]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[relationship--df7c87eb-75d2-4948-af81-9d49d246f301]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[report--84e4d88f-44ea-4bcd-bbf3-b2c1c320bcb3]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[sighting--bfbc19db-ec35-4e45-beed-f8bde2a772fb]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[threat-actor--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[tool--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[vulnerability--0c7b5b88-8ff7-4a4d-aa9d-feb398cd0061]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9_1]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[marking-definition--443eb5c3-a76c-4a0a-8caa-e93998e7bc09]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[marking-definition--57fcd772-9c1d-41b0-8d1f-3d47713415d9]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[marking-definition--462bf1a6-03d2-419c-b74e-eee2238b2de4]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[marking-definition--68520ae2-fefe-43a9-84ee-2c2a934d2c7d]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[marking-definition--2802dfb1-1019-40a8-8848-68d0ec0e417f]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[relationship--06520621-5352-4e6a-b976-e8fa3d437ffd]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[relationship--181c9c09-43e6-45dd-9374-3bec192f05ef]", "stix2/test/v20/test_properties.py::test_id_property_valid_for_type[relationship--a0cbb21c-8daf-4a7f-96aa-7155a4ef8f70]", "stix2/test/v20/test_properties.py::test_id_property_wrong_type", "stix2/test/v20/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--foo]", "stix2/test/v20/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--00000000-0000-0000-0000-000000000000]", "stix2/test/v20/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--04738bdf-b25a-3829-a801-b21a1d25095b]", "stix2/test/v20/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--aad03681-8b63-5304-89e0-8ca8f49461b5]", "stix2/test/v20/test_properties.py::test_id_property_default", "stix2/test/v20/test_properties.py::test_integer_property_valid[2]", "stix2/test/v20/test_properties.py::test_integer_property_valid[-1]", "stix2/test/v20/test_properties.py::test_integer_property_valid[3.14]", "stix2/test/v20/test_properties.py::test_integer_property_valid[False]", "stix2/test/v20/test_properties.py::test_integer_property_invalid_min_with_constraints[-1]", "stix2/test/v20/test_properties.py::test_integer_property_invalid_min_with_constraints[-100]", "stix2/test/v20/test_properties.py::test_integer_property_invalid_min_with_constraints[-30]", "stix2/test/v20/test_properties.py::test_integer_property_invalid_max_with_constraints[181]", "stix2/test/v20/test_properties.py::test_integer_property_invalid_max_with_constraints[200]", "stix2/test/v20/test_properties.py::test_integer_property_invalid_max_with_constraints[300]", "stix2/test/v20/test_properties.py::test_integer_property_invalid[something]", "stix2/test/v20/test_properties.py::test_integer_property_invalid[value1]", "stix2/test/v20/test_properties.py::test_float_property_valid[2]", "stix2/test/v20/test_properties.py::test_float_property_valid[-1]", "stix2/test/v20/test_properties.py::test_float_property_valid[3.14]", "stix2/test/v20/test_properties.py::test_float_property_valid[False]", "stix2/test/v20/test_properties.py::test_float_property_invalid[something]", "stix2/test/v20/test_properties.py::test_float_property_invalid[value1]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[True0]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[False0]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[True1]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[False1]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[true]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[false]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[TRUE]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[FALSE]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[T]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[F]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[t]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[f]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[1]", "stix2/test/v20/test_properties.py::test_boolean_property_valid[0]", "stix2/test/v20/test_properties.py::test_boolean_property_invalid[abc]", "stix2/test/v20/test_properties.py::test_boolean_property_invalid[value1]", "stix2/test/v20/test_properties.py::test_boolean_property_invalid[value2]", "stix2/test/v20/test_properties.py::test_boolean_property_invalid[2]", "stix2/test/v20/test_properties.py::test_boolean_property_invalid[-1]", "stix2/test/v20/test_properties.py::test_reference_property", "stix2/test/v20/test_properties.py::test_timestamp_property_valid[2017-01-01T12:34:56Z]", "stix2/test/v20/test_properties.py::test_timestamp_property_valid[2017-01-01", "stix2/test/v20/test_properties.py::test_timestamp_property_valid[Jan", "stix2/test/v20/test_properties.py::test_timestamp_property_invalid", "stix2/test/v20/test_properties.py::test_binary_property", "stix2/test/v20/test_properties.py::test_hex_property", "stix2/test/v20/test_properties.py::test_dictionary_property_valid[d0]", "stix2/test/v20/test_properties.py::test_dictionary_property_valid[d1]", "stix2/test/v20/test_properties.py::test_dictionary_property_invalid_key[d0]", "stix2/test/v20/test_properties.py::test_dictionary_property_invalid_key[d1]", "stix2/test/v20/test_properties.py::test_dictionary_property_invalid_key[d2]", "stix2/test/v20/test_properties.py::test_dictionary_property_invalid[d0]", "stix2/test/v20/test_properties.py::test_property_list_of_dictionary", "stix2/test/v20/test_properties.py::test_hashes_property_valid[value1]", "stix2/test/v20/test_properties.py::test_hashes_property_invalid[value0]", "stix2/test/v20/test_properties.py::test_hashes_property_invalid[value1]", "stix2/test/v20/test_properties.py::test_embedded_property", "stix2/test/v20/test_properties.py::test_enum_property_valid[value0]", "stix2/test/v20/test_properties.py::test_enum_property_valid[value1]", "stix2/test/v20/test_properties.py::test_enum_property_valid[b]", "stix2/test/v20/test_properties.py::test_enum_property_invalid", "stix2/test/v20/test_properties.py::test_extension_property_valid", "stix2/test/v20/test_properties.py::test_extension_property_invalid[1]", "stix2/test/v20/test_properties.py::test_extension_property_invalid[data1]", "stix2/test/v20/test_properties.py::test_extension_property_invalid_type", "stix2/test/v20/test_properties.py::test_extension_at_least_one_property_constraint", "stix2/test/v20/test_properties.py::test_marking_property_error", "stix2/test/v20/test_properties.py::test_stix_property_not_compliant_spec", "stix2/test/v21/test_observed_data.py::test_observed_data_example", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_refs", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_bad_refs", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_non_dictionary", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_empty_dictionary", "stix2/test/v21/test_observed_data.py::test_parse_observed_data[{\\n", "stix2/test/v21/test_observed_data.py::test_parse_observed_data[data1]", "stix2/test/v21/test_observed_data.py::test_parse_artifact_valid[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_artifact_invalid[\"0\":", "stix2/test/v21/test_observed_data.py::test_artifact_example_dependency_error", "stix2/test/v21/test_observed_data.py::test_parse_autonomous_system_valid[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_email_address[{\\n", "stix2/test/v21/test_observed_data.py::test_parse_email_message[\\n", "stix2/test/v21/test_observed_data.py::test_parse_email_message_not_multipart[\\n", "stix2/test/v21/test_observed_data.py::test_parse_file_archive[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_email_message_with_at_least_one_error[\\n", "stix2/test/v21/test_observed_data.py::test_parse_basic_tcp_traffic[\\n", "stix2/test/v21/test_observed_data.py::test_parse_basic_tcp_traffic_with_error[\\n", "stix2/test/v21/test_observed_data.py::test_observed_data_with_process_example", "stix2/test/v21/test_observed_data.py::test_artifact_example", "stix2/test/v21/test_observed_data.py::test_artifact_mutual_exclusion_error", "stix2/test/v21/test_observed_data.py::test_directory_example", "stix2/test/v21/test_observed_data.py::test_directory_example_ref_error", "stix2/test/v21/test_observed_data.py::test_domain_name_example", "stix2/test/v21/test_observed_data.py::test_domain_name_example_invalid_ref_type", "stix2/test/v21/test_observed_data.py::test_file_example", "stix2/test/v21/test_observed_data.py::test_file_example_with_NTFSExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_empty_NTFSExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_PDFExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_PDFExt_Object", "stix2/test/v21/test_observed_data.py::test_file_example_with_RasterImageExt_Object", "stix2/test/v21/test_observed_data.py::test_raster_image_ext_parse", "stix2/test/v21/test_observed_data.py::test_raster_images_ext_create", "stix2/test/v21/test_observed_data.py::test_file_example_with_WindowsPEBinaryExt", "stix2/test/v21/test_observed_data.py::test_file_example_encryption_error", "stix2/test/v21/test_observed_data.py::test_ip4_address_example", "stix2/test/v21/test_observed_data.py::test_ip4_address_example_cidr", "stix2/test/v21/test_observed_data.py::test_ip6_address_example", "stix2/test/v21/test_observed_data.py::test_mac_address_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_http_request_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_icmp_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_socket_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_tcp_example", "stix2/test/v21/test_observed_data.py::test_mutex_example", "stix2/test/v21/test_observed_data.py::test_process_example", "stix2/test/v21/test_observed_data.py::test_process_example_empty_error", "stix2/test/v21/test_observed_data.py::test_process_example_empty_with_extensions", "stix2/test/v21/test_observed_data.py::test_process_example_windows_process_ext", "stix2/test/v21/test_observed_data.py::test_process_example_windows_process_ext_empty", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsProcessExt_Object", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsServiceExt", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsProcessServiceExt", "stix2/test/v21/test_observed_data.py::test_software_example", "stix2/test/v21/test_observed_data.py::test_url_example", "stix2/test/v21/test_observed_data.py::test_user_account_example", "stix2/test/v21/test_observed_data.py::test_user_account_unix_account_ext_example", "stix2/test/v21/test_observed_data.py::test_windows_registry_key_example", "stix2/test/v21/test_observed_data.py::test_x509_certificate_example", "stix2/test/v21/test_observed_data.py::test_new_version_with_related_objects", "stix2/test/v21/test_properties.py::test_property", "stix2/test/v21/test_properties.py::test_basic_clean", "stix2/test/v21/test_properties.py::test_property_default", "stix2/test/v21/test_properties.py::test_fixed_property", "stix2/test/v21/test_properties.py::test_list_property", "stix2/test/v21/test_properties.py::test_string_property", "stix2/test/v21/test_properties.py::test_type_property", "stix2/test/v21/test_properties.py::test_id_property_valid[my-type--232c9d3f-49fc-4440-bb01-607f638778e7]", "stix2/test/v21/test_properties.py::test_id_property_valid[my-type--00000000-0000-4000-8000-000000000000]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[attack-pattern--0c7b5b88-8ff7-4a4d-aa9d-feb398cd0061]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[campaign--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[course-of-action--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[identity--311b2d2d-f010-4473-83ec-1edf84858f4c]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[indicator--a740531e-63ff-4e49-a9e1-a0a3eed0e3e7]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[intrusion-set--4e78f46f-a023-4e5f-bc24-71b3ca22ec29]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[malware--9c4638ec-f1de-4ddb-abf4-1b760417654e]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9_0]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[observed-data--b67d30ff-02ac-498a-92f9-32f845f448cf]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[relationship--df7c87eb-75d2-4948-af81-9d49d246f301]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[report--84e4d88f-44ea-4bcd-bbf3-b2c1c320bcb3]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[sighting--bfbc19db-ec35-4e45-beed-f8bde2a772fb]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[threat-actor--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[tool--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[vulnerability--0c7b5b88-8ff7-4a4d-aa9d-feb398cd0061]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9_1]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[marking-definition--443eb5c3-a76c-4a0a-8caa-e93998e7bc09]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[marking-definition--57fcd772-9c1d-41b0-8d1f-3d47713415d9]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[marking-definition--462bf1a6-03d2-419c-b74e-eee2238b2de4]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[marking-definition--68520ae2-fefe-43a9-84ee-2c2a934d2c7d]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[marking-definition--2802dfb1-1019-40a8-8848-68d0ec0e417f]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[relationship--06520621-5352-4e6a-b976-e8fa3d437ffd]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[relationship--181c9c09-43e6-45dd-9374-3bec192f05ef]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[relationship--a0cbb21c-8daf-4a7f-96aa-7155a4ef8f70]", "stix2/test/v21/test_properties.py::test_id_property_wrong_type", "stix2/test/v21/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--foo]", "stix2/test/v21/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--00000000-0000-0000-0000-000000000000]", "stix2/test/v21/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--04738bdf-b25a-3829-a801-b21a1d25095b]", "stix2/test/v21/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--aad03681-8b63-5304-89e0-8ca8f49461b5]", "stix2/test/v21/test_properties.py::test_id_property_default", "stix2/test/v21/test_properties.py::test_integer_property_valid[2]", "stix2/test/v21/test_properties.py::test_integer_property_valid[-1]", "stix2/test/v21/test_properties.py::test_integer_property_valid[3.14]", "stix2/test/v21/test_properties.py::test_integer_property_valid[False]", "stix2/test/v21/test_properties.py::test_integer_property_invalid_min_with_constraints[-1]", "stix2/test/v21/test_properties.py::test_integer_property_invalid_min_with_constraints[-100]", "stix2/test/v21/test_properties.py::test_integer_property_invalid_min_with_constraints[-300]", "stix2/test/v21/test_properties.py::test_integer_property_invalid_max_with_constraints[181]", "stix2/test/v21/test_properties.py::test_integer_property_invalid_max_with_constraints[200]", "stix2/test/v21/test_properties.py::test_integer_property_invalid_max_with_constraints[300]", "stix2/test/v21/test_properties.py::test_integer_property_invalid[something]", "stix2/test/v21/test_properties.py::test_integer_property_invalid[value1]", "stix2/test/v21/test_properties.py::test_float_property_valid[2]", "stix2/test/v21/test_properties.py::test_float_property_valid[-1]", "stix2/test/v21/test_properties.py::test_float_property_valid[3.14]", "stix2/test/v21/test_properties.py::test_float_property_valid[False]", "stix2/test/v21/test_properties.py::test_float_property_invalid[something]", "stix2/test/v21/test_properties.py::test_float_property_invalid[value1]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[True0]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[False0]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[True1]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[False1]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[true]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[false]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[TRUE]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[FALSE]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[T]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[F]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[t]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[f]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[1]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[0]", "stix2/test/v21/test_properties.py::test_boolean_property_invalid[abc]", "stix2/test/v21/test_properties.py::test_boolean_property_invalid[value1]", "stix2/test/v21/test_properties.py::test_boolean_property_invalid[value2]", "stix2/test/v21/test_properties.py::test_boolean_property_invalid[2]", "stix2/test/v21/test_properties.py::test_boolean_property_invalid[-1]", "stix2/test/v21/test_properties.py::test_reference_property", "stix2/test/v21/test_properties.py::test_timestamp_property_valid[2017-01-01T12:34:56Z]", "stix2/test/v21/test_properties.py::test_timestamp_property_valid[2017-01-01", "stix2/test/v21/test_properties.py::test_timestamp_property_valid[Jan", "stix2/test/v21/test_properties.py::test_timestamp_property_invalid", "stix2/test/v21/test_properties.py::test_binary_property", "stix2/test/v21/test_properties.py::test_hex_property", "stix2/test/v21/test_properties.py::test_dictionary_property_valid[d0]", "stix2/test/v21/test_properties.py::test_dictionary_property_valid[d1]", "stix2/test/v21/test_properties.py::test_dictionary_no_longer_raises[d0]", "stix2/test/v21/test_properties.py::test_dictionary_property_invalid_key[d0]", "stix2/test/v21/test_properties.py::test_dictionary_property_invalid_key[d1]", "stix2/test/v21/test_properties.py::test_dictionary_property_invalid[d0]", "stix2/test/v21/test_properties.py::test_property_list_of_dictionary", "stix2/test/v21/test_properties.py::test_hashes_property_valid[value1]", "stix2/test/v21/test_properties.py::test_hashes_property_invalid[value0]", "stix2/test/v21/test_properties.py::test_hashes_property_invalid[value1]", "stix2/test/v21/test_properties.py::test_embedded_property", "stix2/test/v21/test_properties.py::test_enum_property_valid[value0]", "stix2/test/v21/test_properties.py::test_enum_property_valid[value1]", "stix2/test/v21/test_properties.py::test_enum_property_valid[b]", "stix2/test/v21/test_properties.py::test_enum_property_invalid", "stix2/test/v21/test_properties.py::test_extension_property_valid", "stix2/test/v21/test_properties.py::test_extension_property_invalid[1]", "stix2/test/v21/test_properties.py::test_extension_property_invalid[data1]", "stix2/test/v21/test_properties.py::test_extension_property_invalid_type", "stix2/test/v21/test_properties.py::test_extension_at_least_one_property_constraint", "stix2/test/v21/test_properties.py::test_marking_property_error" ]
2019-01-07 16:22:21+00:00
4,288
oasis-open__cti-python-stix2-258
diff --git a/stix2/base.py b/stix2/base.py index a6bafff..9fcdf56 100644 --- a/stix2/base.py +++ b/stix2/base.py @@ -143,12 +143,12 @@ class _STIXBase(collections.Mapping): if custom_props: self.__allow_custom = True - # Remove any keyword arguments whose value is None + # Remove any keyword arguments whose value is None or [] (i.e. empty list) setting_kwargs = {} props = kwargs.copy() props.update(custom_props) for prop_name, prop_value in props.items(): - if prop_value is not None: + if prop_value is not None and prop_value != []: setting_kwargs[prop_name] = prop_value # Detect any missing required properties
oasis-open/cti-python-stix2
f8d4669f800291fd5977efaf924c9bb97b12052f
diff --git a/stix2/test/v20/test_malware.py b/stix2/test/v20/test_malware.py index d0c6d7e..900a4b9 100644 --- a/stix2/test/v20/test_malware.py +++ b/stix2/test/v20/test_malware.py @@ -35,6 +35,22 @@ def test_malware_with_all_required_properties(): assert str(mal) == EXPECTED_MALWARE +def test_malware_with_empty_optional_field(): + now = dt.datetime(2016, 5, 12, 8, 17, 27, tzinfo=pytz.utc) + + mal = stix2.v20.Malware( + type="malware", + id=MALWARE_ID, + created=now, + modified=now, + labels=["ransomware"], + name="Cryptolocker", + external_references=[], + ) + + assert str(mal) == EXPECTED_MALWARE + + def test_malware_autogenerated_properties(malware): assert malware.type == 'malware' assert malware.id == 'malware--00000000-0000-4000-8000-000000000001' diff --git a/stix2/test/v20/test_object_markings.py b/stix2/test/v20/test_object_markings.py index 495c45a..156c42d 100644 --- a/stix2/test/v20/test_object_markings.py +++ b/stix2/test/v20/test_object_markings.py @@ -107,7 +107,6 @@ def test_add_markings_combination(): "data", [ ([""]), (""), - ([]), ([MARKING_IDS[0], 456]), ], ) @@ -576,7 +575,6 @@ def test_set_marking(): @pytest.mark.parametrize( "data", [ - ([]), ([""]), (""), ([MARKING_IDS[4], 687]), diff --git a/stix2/test/v21/test_object_markings.py b/stix2/test/v21/test_object_markings.py index d43aad5..7b19d4f 100644 --- a/stix2/test/v21/test_object_markings.py +++ b/stix2/test/v21/test_object_markings.py @@ -106,7 +106,6 @@ def test_add_markings_combination(): "data", [ ([""]), (""), - ([]), ([MARKING_IDS[0], 456]), ], ) @@ -575,7 +574,6 @@ def test_set_marking(): @pytest.mark.parametrize( "data", [ - ([]), ([""]), (""), ([MARKING_IDS[4], 687]),
Ignore empty values for optional fields Latest version of the library will not allow me to create instances of STIX2 classes with `None` or `[]` values for optional fields. Example: ```python In [4]: stix2.Malware(name='test malware', labels=['foo', 'bar'], external_references=[]) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) ~/.p/lib/python3.7/site-packages/stix2/base.py in _check_property(self, prop_name, prop, kwargs) 89 try: ---> 90 kwargs[prop_name] = prop.clean(kwargs[prop_name]) 91 except ValueError as exc: ~/.p/lib/python3.7/site-packages/stix2/properties.py in clean(self, value) 164 if len(result) < 1: --> 165 raise ValueError("must not be empty.") 166 ValueError: must not be empty. ``` This forces me to write code like this: ```python external_references = get_external_references() if external_references: obj = stix2.Malware( name='test malware', labels=['foo', 'bar'], external_references=external_references) else: obj = stix2.Malware( name='test malware', labels=['foo', 'bar']) ``` which is inconvenient. Proposed solution: the library should accept empty fields for optional fields but should not serialize these in the output JSON, treating these fields as unset
0.0
[ "stix2/test/v20/test_malware.py::test_malware_with_empty_optional_field" ]
[ "stix2/test/v20/test_malware.py::test_malware_with_all_required_properties", "stix2/test/v20/test_malware.py::test_malware_autogenerated_properties", "stix2/test/v20/test_malware.py::test_malware_type_must_be_malware", "stix2/test/v20/test_malware.py::test_malware_id_must_start_with_malware", "stix2/test/v20/test_malware.py::test_malware_required_properties", "stix2/test/v20/test_malware.py::test_malware_required_property_name", "stix2/test/v20/test_malware.py::test_cannot_assign_to_malware_attributes", "stix2/test/v20/test_malware.py::test_invalid_kwarg_to_malware", "stix2/test/v20/test_malware.py::test_parse_malware[{\\n", "stix2/test/v20/test_malware.py::test_parse_malware[data1]", "stix2/test/v20/test_malware.py::test_parse_malware_invalid_labels", "stix2/test/v20/test_malware.py::test_parse_malware_kill_chain_phases", "stix2/test/v20/test_malware.py::test_parse_malware_clean_kill_chain_phases", "stix2/test/v20/test_object_markings.py::test_add_markings_one_marking[data0]", "stix2/test/v20/test_object_markings.py::test_add_markings_one_marking[data1]", "stix2/test/v20/test_object_markings.py::test_add_markings_one_marking[data2]", "stix2/test/v20/test_object_markings.py::test_add_markings_multiple_marking", "stix2/test/v20/test_object_markings.py::test_add_markings_combination", "stix2/test/v20/test_object_markings.py::test_add_markings_bad_markings[data0]", "stix2/test/v20/test_object_markings.py::test_add_markings_bad_markings[]", "stix2/test/v20/test_object_markings.py::test_add_markings_bad_markings[data2]", "stix2/test/v20/test_object_markings.py::test_get_markings_object_marking[data0]", "stix2/test/v20/test_object_markings.py::test_get_markings_object_and_granular_combinations[data0]", "stix2/test/v20/test_object_markings.py::test_remove_markings_object_level[data0]", "stix2/test/v20/test_object_markings.py::test_remove_markings_object_level[data1]", "stix2/test/v20/test_object_markings.py::test_remove_markings_multiple[data0]", "stix2/test/v20/test_object_markings.py::test_remove_markings_multiple[data1]", "stix2/test/v20/test_object_markings.py::test_remove_markings_multiple[data2]", "stix2/test/v20/test_object_markings.py::test_remove_markings_bad_markings", "stix2/test/v20/test_object_markings.py::test_clear_markings[data0]", "stix2/test/v20/test_object_markings.py::test_clear_markings[data1]", "stix2/test/v20/test_object_markings.py::test_is_marked_object_and_granular_combinations", "stix2/test/v20/test_object_markings.py::test_is_marked_no_markings[data0]", "stix2/test/v20/test_object_markings.py::test_is_marked_no_markings[data1]", "stix2/test/v20/test_object_markings.py::test_set_marking", "stix2/test/v20/test_object_markings.py::test_set_marking_bad_input[data0]", "stix2/test/v20/test_object_markings.py::test_set_marking_bad_input[]", "stix2/test/v20/test_object_markings.py::test_set_marking_bad_input[data2]", "stix2/test/v21/test_object_markings.py::test_add_markings_one_marking[data0]", "stix2/test/v21/test_object_markings.py::test_add_markings_one_marking[data1]", "stix2/test/v21/test_object_markings.py::test_add_markings_one_marking[data2]", "stix2/test/v21/test_object_markings.py::test_add_markings_multiple_marking", "stix2/test/v21/test_object_markings.py::test_add_markings_combination", "stix2/test/v21/test_object_markings.py::test_add_markings_bad_markings[data0]", "stix2/test/v21/test_object_markings.py::test_add_markings_bad_markings[]", "stix2/test/v21/test_object_markings.py::test_add_markings_bad_markings[data2]", "stix2/test/v21/test_object_markings.py::test_get_markings_object_marking[data0]", "stix2/test/v21/test_object_markings.py::test_get_markings_object_and_granular_combinations[data0]", "stix2/test/v21/test_object_markings.py::test_remove_markings_object_level[data0]", "stix2/test/v21/test_object_markings.py::test_remove_markings_object_level[data1]", "stix2/test/v21/test_object_markings.py::test_remove_markings_multiple[data0]", "stix2/test/v21/test_object_markings.py::test_remove_markings_multiple[data1]", "stix2/test/v21/test_object_markings.py::test_remove_markings_multiple[data2]", "stix2/test/v21/test_object_markings.py::test_remove_markings_bad_markings", "stix2/test/v21/test_object_markings.py::test_clear_markings[data0]", "stix2/test/v21/test_object_markings.py::test_clear_markings[data1]", "stix2/test/v21/test_object_markings.py::test_is_marked_object_and_granular_combinations", "stix2/test/v21/test_object_markings.py::test_is_marked_no_markings[data0]", "stix2/test/v21/test_object_markings.py::test_is_marked_no_markings[data1]", "stix2/test/v21/test_object_markings.py::test_set_marking", "stix2/test/v21/test_object_markings.py::test_set_marking_bad_input[data0]", "stix2/test/v21/test_object_markings.py::test_set_marking_bad_input[]", "stix2/test/v21/test_object_markings.py::test_set_marking_bad_input[data2]" ]
2019-04-17 14:10:34+00:00
4,289
oasis-open__cti-python-stix2-27
diff --git a/stix2/__init__.py b/stix2/__init__.py index 392e947..25e160a 100644 --- a/stix2/__init__.py +++ b/stix2/__init__.py @@ -15,7 +15,8 @@ from .observables import (URL, AlternateDataStream, ArchiveExt, Artifact, WindowsProcessExt, WindowsRegistryKey, WindowsRegistryValueType, WindowsServiceExt, X509Certificate, X509V3ExtenstionsType) -from .other import (ExternalReference, GranularMarking, KillChainPhase, +from .other import (TLP_AMBER, TLP_GREEN, TLP_RED, TLP_WHITE, + ExternalReference, GranularMarking, KillChainPhase, MarkingDefinition, StatementMarking, TLPMarking) from .sdo import (AttackPattern, Campaign, CourseOfAction, Identity, Indicator, IntrusionSet, Malware, ObservedData, Report, ThreatActor, diff --git a/stix2/bundle.py b/stix2/bundle.py index 85be3e1..b598ceb 100644 --- a/stix2/bundle.py +++ b/stix2/bundle.py @@ -17,6 +17,9 @@ class Bundle(_STIXBase): def __init__(self, *args, **kwargs): # Add any positional arguments to the 'objects' kwarg. if args: - kwargs['objects'] = kwargs.get('objects', []) + list(args) + if isinstance(args[0], list): + kwargs['objects'] = args[0] + list(args[1:]) + kwargs.get('objects', []) + else: + kwargs['objects'] = list(args) + kwargs.get('objects', []) super(Bundle, self).__init__(**kwargs)
oasis-open/cti-python-stix2
f8e3a4f0e895da95fbef109041dec26d6f968690
diff --git a/stix2/test/test_bundle.py b/stix2/test/test_bundle.py index fc3e350..54d7080 100644 --- a/stix2/test/test_bundle.py +++ b/stix2/test/test_bundle.py @@ -92,3 +92,27 @@ def test_create_bundle_with_positional_args(indicator, malware, relationship): bundle = stix2.Bundle(indicator, malware, relationship) assert str(bundle) == EXPECTED_BUNDLE + + +def test_create_bundle_with_positional_listarg(indicator, malware, relationship): + bundle = stix2.Bundle([indicator, malware, relationship]) + + assert str(bundle) == EXPECTED_BUNDLE + + +def test_create_bundle_with_listarg_and_positional_arg(indicator, malware, relationship): + bundle = stix2.Bundle([indicator, malware], relationship) + + assert str(bundle) == EXPECTED_BUNDLE + + +def test_create_bundle_with_listarg_and_kwarg(indicator, malware, relationship): + bundle = stix2.Bundle([indicator, malware], objects=[relationship]) + + assert str(bundle) == EXPECTED_BUNDLE + + +def test_create_bundle_with_arg_listarg_and_kwarg(indicator, malware, relationship): + bundle = stix2.Bundle([indicator], malware, objects=[relationship]) + + assert str(bundle) == EXPECTED_BUNDLE diff --git a/stix2/test/test_markings.py b/stix2/test/test_markings.py index c2e0276..ebfa480 100644 --- a/stix2/test/test_markings.py +++ b/stix2/test/test_markings.py @@ -4,7 +4,7 @@ import pytest import pytz import stix2 -from stix2.other import TLP_WHITE +from stix2 import TLP_WHITE from .constants import MARKING_DEFINITION_ID
Passing a list to Bundle constructor creates list within a list Currently if you pass a list to the Bundle constructor it creates a list within a list: ```json { "objects": [ [ { }, { } ] ] } ``` If the first argument is a list, the constructor should just assign it to `objects`.
0.0
[ "stix2/test/test_bundle.py::test_empty_bundle", "stix2/test/test_bundle.py::test_bundle_with_wrong_type", "stix2/test/test_bundle.py::test_bundle_id_must_start_with_bundle", "stix2/test/test_bundle.py::test_bundle_with_wrong_spec_version", "stix2/test/test_bundle.py::test_create_bundle", "stix2/test/test_bundle.py::test_create_bundle_with_positional_args", "stix2/test/test_bundle.py::test_create_bundle_with_positional_listarg", "stix2/test/test_bundle.py::test_create_bundle_with_listarg_and_positional_arg", "stix2/test/test_bundle.py::test_create_bundle_with_listarg_and_kwarg", "stix2/test/test_bundle.py::test_create_bundle_with_arg_listarg_and_kwarg", "stix2/test/test_markings.py::test_marking_def_example_with_tlp", "stix2/test/test_markings.py::test_marking_def_example_with_statement", "stix2/test/test_markings.py::test_marking_def_example_with_positional_statement", "stix2/test/test_markings.py::test_granular_example", "stix2/test/test_markings.py::test_granular_example_with_bad_selector", "stix2/test/test_markings.py::test_campaign_with_granular_markings_example", "stix2/test/test_markings.py::test_parse_marking_definition[{\\n", "stix2/test/test_markings.py::test_parse_marking_definition[data1]" ]
[]
2017-07-05 15:40:21+00:00
4,290
oasis-open__cti-python-stix2-301
diff --git a/stix2/environment.py b/stix2/environment.py index d2c6d3a..34e0a04 100644 --- a/stix2/environment.py +++ b/stix2/environment.py @@ -6,7 +6,6 @@ import time from .core import parse as _parse from .datastore import CompositeDataSource, DataStoreMixin -from .exceptions import SemanticEquivalenceUnsupportedTypeError from .utils import STIXdatetime, parse_into_datetime logger = logging.getLogger(__name__) @@ -228,9 +227,6 @@ class Environment(DataStoreMixin): "aliases": 40, "method": _campaign_checks, }, - "course-of-action": { - "method": _course_of_action_checks, - }, "identity": { "name": 60, "identity_class": 20, @@ -244,9 +240,6 @@ class Environment(DataStoreMixin): "tdelta": 1, # One day interval "method": _indicator_checks, }, - "intrusion-set": { - "method": _intrusion_set_checks, - }, "location": { "longitude_latitude": 34, "region": 33, @@ -259,12 +252,6 @@ class Environment(DataStoreMixin): "name": 80, "method": _malware_checks, }, - "observed-data": { - "method": _observed_data_checks, - }, - "report": { - "method": _report_checks, - }, "threat-actor": { "name": 60, "threat_actor_types": 20, @@ -298,8 +285,14 @@ class Environment(DataStoreMixin): if ignore_spec_version is False and obj1.get("spec_version", "2.0") != obj2.get("spec_version", "2.0"): raise ValueError('The objects to compare must be of the same spec version!') - method = weights[type1]["method"] - matching_score, sum_weights = method(obj1, obj2, **weights[type1]) + try: + method = weights[type1]["method"] + except KeyError: + logger.warning("'%s' type has no semantic equivalence method to call!", type1) + sum_weights = matching_score = 0 + else: + logger.debug("Starting semantic equivalence process between: '%s' and '%s'", obj1["id"], obj2["id"]) + matching_score, sum_weights = method(obj1, obj2, **weights[type1]) if sum_weights <= 0: return 0 @@ -333,7 +326,9 @@ def partial_timestamp_based(t1, t2, tdelta): if not isinstance(t2, STIXdatetime): t2 = parse_into_datetime(t2) t1, t2 = time.mktime(t1.timetuple()), time.mktime(t2.timetuple()) - return 1 - min(abs(t1 - t2) / (86400 * tdelta), 1) + result = 1 - min(abs(t1 - t2) / (86400 * tdelta), 1) + logger.debug("--\t\tpartial_timestamp_based '%s' '%s' tdelta: '%s'\tresult: '%s'", t1, t2, tdelta, result) + return result def partial_list_based(l1, l2): @@ -348,7 +343,9 @@ def partial_list_based(l1, l2): """ l1_set, l2_set = set(l1), set(l2) - return len(l1_set.intersection(l2_set)) / max(len(l1), len(l2)) + result = len(l1_set.intersection(l2_set)) / max(len(l1), len(l2)) + logger.debug("--\t\tpartial_list_based '%s' '%s'\tresult: '%s'", l1, l2, result) + return result def exact_match(val1, val2): @@ -362,9 +359,11 @@ def exact_match(val1, val2): float: 1.0 if the value matches exactly, 0.0 otherwise. """ + result = 0.0 if val1 == val2: - return 1.0 - return 0.0 + result = 1.0 + logger.debug("--\t\texact_match '%s' '%s'\tresult: '%s'", val1, val2, result) + return result def partial_string_based(str1, str2): @@ -379,7 +378,9 @@ def partial_string_based(str1, str2): """ from pyjarowinkler import distance - return distance.get_jaro_distance(str1, str2) + result = distance.get_jaro_distance(str1, str2) + logger.debug("--\t\tpartial_string_based '%s' '%s'\tresult: '%s'", str1, str2, result) + return result def custom_pattern_based(pattern1, pattern2): @@ -440,14 +441,24 @@ def partial_external_reference_based(refs1, refs2): # external_id or url match then its a perfect match and other entries # can be ignored. if sn_match and (ei_match or url_match) and source_name in allowed: - return 1.0 + result = 1.0 + logger.debug( + "--\t\tpartial_external_reference_based '%s' '%s'\tresult: '%s'", + refs1, refs2, result, + ) + return result # Regular check. If the source_name (not STIX-defined) or external_id or # url matches then we consider the entry a match. if (sn_match or ei_match or url_match) and source_name not in allowed: matches += 1 - return matches / max(len(refs1), len(refs2)) + result = matches / max(len(refs1), len(refs2)) + logger.debug( + "--\t\tpartial_external_reference_based '%s' '%s'\tresult: '%s'", + refs1, refs2, result, + ) + return result def partial_location_distance(lat1, long1, lat2, long2, threshold): @@ -466,7 +477,12 @@ def partial_location_distance(lat1, long1, lat2, long2, threshold): """ from haversine import haversine, Unit distance = haversine((lat1, long1), (lat2, long2), unit=Unit.KILOMETERS) - return 1 - (distance / threshold) + result = 1 - (distance / threshold) + logger.debug( + "--\t\tpartial_location_distance '%s' '%s' threshold: '%s'\tresult: '%s'", + (lat1, long1), (lat2, long2), threshold, result, + ) + return result def _attack_pattern_checks(obj1, obj2, **weights): @@ -474,15 +490,19 @@ def _attack_pattern_checks(obj1, obj2, **weights): sum_weights = 0.0 if check_property_present("name", obj1, obj2): w = weights["name"] + contributing_score = w * partial_string_based(obj1["name"], obj2["name"]) sum_weights += w - matching_score += w * partial_string_based(obj1["name"], obj2["name"]) + matching_score += contributing_score + logger.debug("'name' check -- weight: %s, contributing score: %s", w, contributing_score) if check_property_present("external_references", obj1, obj2): w = weights["external_references"] - sum_weights += w - matching_score += ( - w * - partial_external_reference_based(obj1["external_references"], obj2["external_references"]) + contributing_score = ( + w * partial_external_reference_based(obj1["external_references"], obj2["external_references"]) ) + sum_weights += w + matching_score += contributing_score + logger.debug("'external_references' check -- weight: %s, contributing score: %s", w, contributing_score) + logger.debug("Matching Score: %s, Sum of Weights: %s", matching_score, sum_weights) return matching_score, sum_weights @@ -491,12 +511,17 @@ def _campaign_checks(obj1, obj2, **weights): sum_weights = 0.0 if check_property_present("name", obj1, obj2): w = weights["name"] + contributing_score = w * partial_string_based(obj1["name"], obj2["name"]) sum_weights += w - matching_score += w * partial_string_based(obj1["name"], obj2["name"]) + matching_score += contributing_score + logger.debug("'name' check -- weight: %s, contributing score: %s", w, contributing_score) if check_property_present("aliases", obj1, obj2): w = weights["aliases"] + contributing_score = w * partial_list_based(obj1["aliases"], obj2["aliases"]) sum_weights += w - matching_score += w * partial_list_based(obj1["aliases"], obj2["aliases"]) + matching_score += contributing_score + logger.debug("'aliases' check -- weight: %s, contributing score: %s", w, contributing_score) + logger.debug("Matching Score: %s, Sum of Weights: %s", matching_score, sum_weights) return matching_score, sum_weights @@ -505,16 +530,23 @@ def _identity_checks(obj1, obj2, **weights): sum_weights = 0.0 if check_property_present("name", obj1, obj2): w = weights["name"] + contributing_score = w * exact_match(obj1["name"], obj2["name"]) sum_weights += w - matching_score += w * exact_match(obj1["name"], obj2["name"]) + matching_score += contributing_score + logger.debug("'name' check -- weight: %s, contributing score: %s", w, contributing_score) if check_property_present("identity_class", obj1, obj2): w = weights["identity_class"] + contributing_score = w * exact_match(obj1["identity_class"], obj2["identity_class"]) sum_weights += w - matching_score += w * exact_match(obj1["identity_class"], obj2["identity_class"]) + matching_score += contributing_score + logger.debug("'identity_class' check -- weight: %s, contributing score: %s", w, contributing_score) if check_property_present("sectors", obj1, obj2): w = weights["sectors"] + contributing_score = w * partial_list_based(obj1["sectors"], obj2["sectors"]) sum_weights += w - matching_score += w * partial_list_based(obj1["sectors"], obj2["sectors"]) + matching_score += contributing_score + logger.debug("'sectors' check -- weight: %s, contributing score: %s", w, contributing_score) + logger.debug("Matching Score: %s, Sum of Weights: %s", matching_score, sum_weights) return matching_score, sum_weights @@ -523,19 +555,26 @@ def _indicator_checks(obj1, obj2, **weights): sum_weights = 0.0 if check_property_present("indicator_types", obj1, obj2): w = weights["indicator_types"] + contributing_score = w * partial_list_based(obj1["indicator_types"], obj2["indicator_types"]) sum_weights += w - matching_score += w * partial_list_based(obj1["indicator_types"], obj2["indicator_types"]) + matching_score += contributing_score + logger.debug("'indicator_types' check -- weight: %s, contributing score: %s", w, contributing_score) if check_property_present("pattern", obj1, obj2): w = weights["pattern"] + contributing_score = w * custom_pattern_based(obj1["pattern"], obj2["pattern"]) sum_weights += w - matching_score += w * custom_pattern_based(obj1["pattern"], obj2["pattern"]) + matching_score += contributing_score + logger.debug("'pattern' check -- weight: %s, contributing score: %s", w, contributing_score) if check_property_present("valid_from", obj1, obj2): w = weights["valid_from"] - sum_weights += w - matching_score += ( + contributing_score = ( w * partial_timestamp_based(obj1["valid_from"], obj2["valid_from"], weights["tdelta"]) ) + sum_weights += w + matching_score += contributing_score + logger.debug("'valid_from' check -- weight: %s, contributing score: %s", w, contributing_score) + logger.debug("Matching Score: %s, Sum of Weights: %s", matching_score, sum_weights) return matching_score, sum_weights @@ -544,19 +583,26 @@ def _location_checks(obj1, obj2, **weights): sum_weights = 0.0 if check_property_present("latitude", obj1, obj2) and check_property_present("longitude", obj1, obj2): w = weights["longitude_latitude"] - sum_weights += w - matching_score += ( + contributing_score = ( w * partial_location_distance(obj1["latitude"], obj1["longitude"], obj2["latitude"], obj2["longitude"], weights["threshold"]) ) + sum_weights += w + matching_score += contributing_score + logger.debug("'longitude_latitude' check -- weight: %s, contributing score: %s", w, contributing_score) if check_property_present("region", obj1, obj2): w = weights["region"] + contributing_score = w * exact_match(obj1["region"], obj2["region"]) sum_weights += w - matching_score += w * exact_match(obj1["region"], obj2["region"]) + matching_score += contributing_score + logger.debug("'region' check -- weight: %s, contributing score: %s", w, contributing_score) if check_property_present("country", obj1, obj2): w = weights["country"] + contributing_score = w * exact_match(obj1["country"], obj2["country"]) sum_weights += w - matching_score += w * exact_match(obj1["country"], obj2["country"]) + matching_score += contributing_score + logger.debug("'country' check -- weight: %s, contributing score: %s", w, contributing_score) + logger.debug("Matching Score: %s, Sum of Weights: %s", matching_score, sum_weights) return matching_score, sum_weights @@ -565,12 +611,17 @@ def _malware_checks(obj1, obj2, **weights): sum_weights = 0.0 if check_property_present("malware_types", obj1, obj2): w = weights["malware_types"] + contributing_score = w * partial_list_based(obj1["malware_types"], obj2["malware_types"]) sum_weights += w - matching_score += w * partial_list_based(obj1["malware_types"], obj2["malware_types"]) + matching_score += contributing_score + logger.debug("'malware_types' check -- weight: %s, contributing score: %s", w, contributing_score) if check_property_present("name", obj1, obj2): w = weights["name"] + contributing_score = w * partial_string_based(obj1["name"], obj2["name"]) sum_weights += w - matching_score += w * partial_string_based(obj1["name"], obj2["name"]) + matching_score += contributing_score + logger.debug("'name' check -- weight: %s, contributing score: %s", w, contributing_score) + logger.debug("Matching Score: %s, Sum of Weights: %s", matching_score, sum_weights) return matching_score, sum_weights @@ -579,16 +630,23 @@ def _threat_actor_checks(obj1, obj2, **weights): sum_weights = 0.0 if check_property_present("name", obj1, obj2): w = weights["name"] + contributing_score = w * partial_string_based(obj1["name"], obj2["name"]) sum_weights += w - matching_score += w * partial_string_based(obj1["name"], obj2["name"]) + matching_score += contributing_score + logger.debug("'name' check -- weight: %s, contributing score: %s", w, contributing_score) if check_property_present("threat_actor_types", obj1, obj2): w = weights["threat_actor_types"] + contributing_score = w * partial_list_based(obj1["threat_actor_types"], obj2["threat_actor_types"]) sum_weights += w - matching_score += w * partial_list_based(obj1["threat_actor_types"], obj2["threat_actor_types"]) + matching_score += contributing_score + logger.debug("'threat_actor_types' check -- weight: %s, contributing score: %s", w, contributing_score) if check_property_present("aliases", obj1, obj2): w = weights["aliases"] + contributing_score = w * partial_list_based(obj1["aliases"], obj2["aliases"]) sum_weights += w - matching_score += w * partial_list_based(obj1["aliases"], obj2["aliases"]) + matching_score += contributing_score + logger.debug("'aliases' check -- weight: %s, contributing score: %s", w, contributing_score) + logger.debug("Matching Score: %s, Sum of Weights: %s", matching_score, sum_weights) return matching_score, sum_weights @@ -597,12 +655,17 @@ def _tool_checks(obj1, obj2, **weights): sum_weights = 0.0 if check_property_present("tool_types", obj1, obj2): w = weights["tool_types"] + contributing_score = w * partial_list_based(obj1["tool_types"], obj2["tool_types"]) sum_weights += w - matching_score += w * partial_list_based(obj1["tool_types"], obj2["tool_types"]) + matching_score += contributing_score + logger.debug("'tool_types' check -- weight: %s, contributing score: %s", w, contributing_score) if check_property_present("name", obj1, obj2): w = weights["name"] + contributing_score = w * partial_string_based(obj1["name"], obj2["name"]) sum_weights += w - matching_score += w * partial_string_based(obj1["name"], obj2["name"]) + matching_score += contributing_score + logger.debug("'name' check -- weight: %s, contributing score: %s", w, contributing_score) + logger.debug("Matching Score: %s, Sum of Weights: %s", matching_score, sum_weights) return matching_score, sum_weights @@ -611,29 +674,18 @@ def _vulnerability_checks(obj1, obj2, **weights): sum_weights = 0.0 if check_property_present("name", obj1, obj2): w = weights["name"] + contributing_score = w * partial_string_based(obj1["name"], obj2["name"]) sum_weights += w - matching_score += w * partial_string_based(obj1["name"], obj2["name"]) + matching_score += contributing_score + logger.debug("'name' check -- weight: %s, contributing score: %s", w, contributing_score) if check_property_present("external_references", obj1, obj2): w = weights["external_references"] - sum_weights += w - matching_score += w * partial_external_reference_based( + contributing_score = w * partial_external_reference_based( obj1["external_references"], obj2["external_references"], ) + sum_weights += w + matching_score += contributing_score + logger.debug("'external_references' check -- weight: %s, contributing score: %s", w, contributing_score) + logger.debug("Matching Score: %s, Sum of Weights: %s", matching_score, sum_weights) return matching_score, sum_weights - - -def _course_of_action_checks(obj1, obj2, **weights): - raise SemanticEquivalenceUnsupportedTypeError("course-of-action type has no semantic equivalence implementation!") - - -def _intrusion_set_checks(obj1, obj2, **weights): - raise SemanticEquivalenceUnsupportedTypeError("intrusion-set type has no semantic equivalence implementation!") - - -def _observed_data_checks(obj1, obj2, **weights): - raise SemanticEquivalenceUnsupportedTypeError("observed-data type has no semantic equivalence implementation!") - - -def _report_checks(obj1, obj2, **weights): - raise SemanticEquivalenceUnsupportedTypeError("report type has no semantic equivalence implementation!") diff --git a/stix2/exceptions.py b/stix2/exceptions.py index 6405c2e..d2ec3fc 100644 --- a/stix2/exceptions.py +++ b/stix2/exceptions.py @@ -233,10 +233,3 @@ class STIXDeprecationWarning(DeprecationWarning): Represents usage of a deprecated component of a STIX specification. """ pass - - -class SemanticEquivalenceUnsupportedTypeError(STIXError, TypeError): - """STIX object type not supported by the semantic equivalence approach.""" - - def __init__(self, msg): - super(SemanticEquivalenceUnsupportedTypeError, self).__init__(msg)
oasis-open/cti-python-stix2
39e1ddbbf67aaef7c998678ec7df3748777efa35
diff --git a/stix2/test/v21/test_environment.py b/stix2/test/v21/test_environment.py index 62b0c53..d057df5 100644 --- a/stix2/test/v21/test_environment.py +++ b/stix2/test/v21/test_environment.py @@ -6,10 +6,8 @@ import stix2.exceptions from .constants import ( ATTACK_PATTERN_ID, ATTACK_PATTERN_KWARGS, CAMPAIGN_ID, CAMPAIGN_KWARGS, - COURSE_OF_ACTION_ID, COURSE_OF_ACTION_KWARGS, FAKE_TIME, IDENTITY_ID, - IDENTITY_KWARGS, INDICATOR_ID, INDICATOR_KWARGS, INTRUSION_SET_ID, - INTRUSION_SET_KWARGS, LOCATION_ID, MALWARE_ID, MALWARE_KWARGS, - OBSERVED_DATA_ID, OBSERVED_DATA_KWARGS, RELATIONSHIP_IDS, REPORT_ID, + FAKE_TIME, IDENTITY_ID, IDENTITY_KWARGS, INDICATOR_ID, INDICATOR_KWARGS, + LOCATION_ID, MALWARE_ID, MALWARE_KWARGS, RELATIONSHIP_IDS, REPORT_ID, REPORT_KWARGS, THREAT_ACTOR_ID, THREAT_ACTOR_KWARGS, TOOL_ID, TOOL_KWARGS, VULNERABILITY_ID, VULNERABILITY_KWARGS, ) @@ -615,37 +613,6 @@ def test_semantic_equivalence_different_spec_version_raises(): assert str(excinfo.value) == "The objects to compare must be of the same spec version!" [email protected]( - "obj1,obj2,ret_val", - [ - ( - stix2.v21.CourseOfAction(id=COURSE_OF_ACTION_ID, **COURSE_OF_ACTION_KWARGS), - stix2.v21.CourseOfAction(id=COURSE_OF_ACTION_ID, **COURSE_OF_ACTION_KWARGS), - "course-of-action type has no semantic equivalence implementation!", - ), - ( - stix2.v21.IntrusionSet(id=INTRUSION_SET_ID, **INTRUSION_SET_KWARGS), - stix2.v21.IntrusionSet(id=INTRUSION_SET_ID, **INTRUSION_SET_KWARGS), - "intrusion-set type has no semantic equivalence implementation!", - ), - ( - stix2.v21.ObservedData(id=OBSERVED_DATA_ID, **OBSERVED_DATA_KWARGS), - stix2.v21.ObservedData(id=OBSERVED_DATA_ID, **OBSERVED_DATA_KWARGS), - "observed-data type has no semantic equivalence implementation!", - ), - ( - stix2.v21.Report(id=REPORT_ID, **REPORT_KWARGS), - stix2.v21.Report(id=REPORT_ID, **REPORT_KWARGS), - "report type has no semantic equivalence implementation!", - ), - ], -) -def test_semantic_equivalence_on_unsupported_types(obj1, obj2, ret_val): - with pytest.raises(stix2.exceptions.SemanticEquivalenceUnsupportedTypeError) as excinfo: - stix2.Environment().semantically_equivalent(obj1, obj2) - assert ret_val == str(excinfo.value) - - def test_semantic_equivalence_zero_match(): IND_KWARGS = dict( indicator_types=["APTX"], @@ -767,7 +734,7 @@ def test_semantic_equivalence_external_references(refs1, refs2, ret_val): assert value == ret_val -def test_semantic_equivalence_timetamp(): +def test_semantic_equivalence_timestamp(): t1 = "2018-10-17T00:14:20.652Z" t2 = "2018-10-17T12:14:20.652Z" assert stix2.environment.partial_timestamp_based(t1, t2, 1) == 0.5 @@ -777,3 +744,9 @@ def test_semantic_equivalence_exact_match(): t1 = "2018-10-17T00:14:20.652Z" t2 = "2018-10-17T12:14:20.652Z" assert stix2.environment.exact_match(t1, t2) == 0.0 + + +def test_non_existent_config_for_object(): + r1 = stix2.v21.Report(id=REPORT_ID, **REPORT_KWARGS) + r2 = stix2.v21.Report(id=REPORT_ID, **REPORT_KWARGS) + assert stix2.Environment().semantically_equivalent(r1, r2) == 0.0
Semantic Equivalence: More detailed output We should offer an option for the semantic equivalence function to provide more detailed output, showing the score for each property seperately so users can tell how the algorithm ended up with the final value. This can help with debugging. The current output should be the default.
0.0
[ "stix2/test/v21/test_environment.py::test_non_existent_config_for_object" ]
[ "stix2/test/v21/test_environment.py::test_object_factory_created_by_ref_str", "stix2/test/v21/test_environment.py::test_object_factory_created_by_ref_obj", "stix2/test/v21/test_environment.py::test_object_factory_override_default", "stix2/test/v21/test_environment.py::test_object_factory_created", "stix2/test/v21/test_environment.py::test_object_factory_external_reference", "stix2/test/v21/test_environment.py::test_object_factory_obj_markings", "stix2/test/v21/test_environment.py::test_object_factory_list_append", "stix2/test/v21/test_environment.py::test_object_factory_list_replace", "stix2/test/v21/test_environment.py::test_environment_functions", "stix2/test/v21/test_environment.py::test_environment_source_and_sink", "stix2/test/v21/test_environment.py::test_environment_datastore_and_sink", "stix2/test/v21/test_environment.py::test_environment_no_datastore", "stix2/test/v21/test_environment.py::test_environment_add_filters", "stix2/test/v21/test_environment.py::test_environment_datastore_and_no_object_factory", "stix2/test/v21/test_environment.py::test_parse_malware", "stix2/test/v21/test_environment.py::test_creator_of", "stix2/test/v21/test_environment.py::test_creator_of_no_datasource", "stix2/test/v21/test_environment.py::test_creator_of_not_found", "stix2/test/v21/test_environment.py::test_creator_of_no_created_by_ref", "stix2/test/v21/test_environment.py::test_relationships", "stix2/test/v21/test_environment.py::test_relationships_no_id", "stix2/test/v21/test_environment.py::test_relationships_by_type", "stix2/test/v21/test_environment.py::test_relationships_by_source", "stix2/test/v21/test_environment.py::test_relationships_by_target", "stix2/test/v21/test_environment.py::test_relationships_by_target_and_type", "stix2/test/v21/test_environment.py::test_relationships_by_target_and_source", "stix2/test/v21/test_environment.py::test_related_to", "stix2/test/v21/test_environment.py::test_related_to_no_id", "stix2/test/v21/test_environment.py::test_related_to_by_source", "stix2/test/v21/test_environment.py::test_related_to_by_target", "stix2/test/v21/test_environment.py::test_semantic_equivalence_on_same_identity1", "stix2/test/v21/test_environment.py::test_semantic_equivalence_on_same_identity2", "stix2/test/v21/test_environment.py::test_semantic_equivalence_on_same_indicator", "stix2/test/v21/test_environment.py::test_semantic_equivalence_different_type_raises", "stix2/test/v21/test_environment.py::test_semantic_equivalence_different_spec_version_raises", "stix2/test/v21/test_environment.py::test_semantic_equivalence_zero_match", "stix2/test/v21/test_environment.py::test_semantic_equivalence_different_spec_version", "stix2/test/v21/test_environment.py::test_semantic_equivalence_external_references[refs10-refs20-0.0]", "stix2/test/v21/test_environment.py::test_semantic_equivalence_external_references[refs11-refs21-1.0]", "stix2/test/v21/test_environment.py::test_semantic_equivalence_external_references[refs12-refs22-1.0]", "stix2/test/v21/test_environment.py::test_semantic_equivalence_timestamp", "stix2/test/v21/test_environment.py::test_semantic_equivalence_exact_match" ]
2019-10-15 16:59:11+00:00
4,291
oasis-open__cti-python-stix2-306
diff --git a/README.rst b/README.rst index 0613a15..0bf30fd 100644 --- a/README.rst +++ b/README.rst @@ -52,6 +52,7 @@ To parse a STIX JSON string into a Python STIX object, use ``parse()``: "indicator_types": [ "malicious-activity" ], + "pattern_type": "stix", "pattern": "[file:hashes.md5 ='d41d8cd98f00b204e9800998ecf8427e']", "valid_from": "2017-09-26T23:33:39.829952Z" }""") diff --git a/stix2/patterns.py b/stix2/patterns.py index 9656ff1..2e149be 100644 --- a/stix2/patterns.py +++ b/stix2/patterns.py @@ -135,6 +135,7 @@ _HASH_REGEX = { "SHA3512": ("^[a-fA-F0-9]{128}$", "SHA3-512"), "SSDEEP": ("^[a-zA-Z0-9/+:.]{1,128}$", "ssdeep"), "WHIRLPOOL": ("^[a-fA-F0-9]{128}$", "WHIRLPOOL"), + "TLSH": ("^[a-fA-F0-9]{70}$", "TLSH"), } diff --git a/stix2/properties.py b/stix2/properties.py index c956a08..f6211c8 100644 --- a/stix2/properties.py +++ b/stix2/properties.py @@ -363,6 +363,10 @@ class DictionaryProperty(Property): "underscore (_)" ) raise DictionaryKeyError(k, msg) + + if len(dictified) < 1: + raise ValueError("must not be empty.") + return dictified @@ -381,6 +385,7 @@ HASHES_REGEX = { "SHA3512": (r"^[a-fA-F0-9]{128}$", "SHA3-512"), "SSDEEP": (r"^[a-zA-Z0-9/+:.]{1,128}$", "ssdeep"), "WHIRLPOOL": (r"^[a-fA-F0-9]{128}$", "WHIRLPOOL"), + "TLSH": (r"^[a-fA-F0-9]{70}$", "TLSH"), } diff --git a/stix2/v21/observables.py b/stix2/v21/observables.py index 0d27bb4..fdb61f4 100644 --- a/stix2/v21/observables.py +++ b/stix2/v21/observables.py @@ -592,6 +592,18 @@ class SocketExt(_Extension): ('socket_handle', IntegerProperty()), ]) + def _check_object_constraints(self): + super(SocketExt, self)._check_object_constraints() + + options = self.get('options') + + if options is not None: + for key, val in options.items(): + if key[:3] != "SO_": + raise ValueError("Incorrect options key") + if not isinstance(val, int): + raise ValueError("Options value must be an integer") + class TCPExt(_Extension): # TODO: Add link @@ -986,6 +998,18 @@ class X509Certificate(_Observable): ]) _id_contributing_properties = ["hashes", "serial_number"] + def _check_object_constraints(self): + super(X509Certificate, self)._check_object_constraints() + + att_list = [ + 'is_self_signed', 'hashes', 'version', 'serial_number', + 'signature_algorithm', 'issuer', 'validity_not_before', + 'validity_not_after', 'subject', 'subject_public_key_algorithm', + 'subject_public_key_modulus', 'subject_public_key_exponent', + 'x509_v3_extensions', + ] + self._check_at_least_one_property(att_list) + def CustomObservable(type='x-custom-observable', properties=None): """Custom STIX Cyber Observable Object type decorator. diff --git a/stix2/v21/sdo.py b/stix2/v21/sdo.py index 7cd7891..6f7b52d 100644 --- a/stix2/v21/sdo.py +++ b/stix2/v21/sdo.py @@ -215,6 +215,13 @@ class Indicator(STIXDomainObject): ('granular_markings', ListProperty(GranularMarking)), ]) + def __init__(self, *args, **kwargs): + + if kwargs.get('pattern') and kwargs.get('pattern_type') == 'stix' and not kwargs.get('pattern_version'): + kwargs['pattern_version'] = '2.1' + + super(STIXDomainObject, self).__init__(*args, **kwargs) + def _check_object_constraints(self): super(Indicator, self)._check_object_constraints()
oasis-open/cti-python-stix2
d4c01157352552e2ec05bcf7b0f79ef96e34022d
diff --git a/stix2/test/v21/test_bundle.py b/stix2/test/v21/test_bundle.py index 54ef318..4e30c84 100644 --- a/stix2/test/v21/test_bundle.py +++ b/stix2/test/v21/test_bundle.py @@ -22,6 +22,7 @@ EXPECTED_BUNDLE = """{ ], "pattern": "[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']", "pattern_type": "stix", + "pattern_version": "2.1", "valid_from": "2017-01-01T12:34:56Z" }, { @@ -61,6 +62,7 @@ EXPECTED_BUNDLE_DICT = { "modified": "2017-01-01T12:34:56.000Z", "pattern": "[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']", "pattern_type": "stix", + "pattern_version": "2.1", "valid_from": "2017-01-01T12:34:56Z", "indicator_types": [ "malicious-activity", diff --git a/stix2/test/v21/test_indicator.py b/stix2/test/v21/test_indicator.py index ea46d6d..0562dfd 100644 --- a/stix2/test/v21/test_indicator.py +++ b/stix2/test/v21/test_indicator.py @@ -19,6 +19,7 @@ EXPECTED_INDICATOR = """{ ], "pattern": "[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']", "pattern_type": "stix", + "pattern_version": "2.1", "valid_from": "1970-01-01T00:00:01Z" }""" @@ -31,6 +32,7 @@ EXPECTED_INDICATOR_REPR = "Indicator(" + " ".join(""" indicator_types=['malicious-activity'], pattern="[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']", pattern_type='stix', + pattern_version='2.1', valid_from='1970-01-01T00:00:01Z' """.split()) + ")" diff --git a/stix2/test/v21/test_observed_data.py b/stix2/test/v21/test_observed_data.py index 0074bf7..2910ba1 100644 --- a/stix2/test/v21/test_observed_data.py +++ b/stix2/test/v21/test_observed_data.py @@ -1117,6 +1117,28 @@ def test_network_traffic_socket_example(): assert nt.extensions['socket-ext'].socket_type == "SOCK_STREAM" +def test_incorrect_socket_options(): + with pytest.raises(ValueError) as excinfo: + stix2.v21.SocketExt( + is_listening=True, + address_family="AF_INET", + protocol_family="PF_INET", + socket_type="SOCK_STREAM", + options={"RCVTIMEO": 100}, + ) + assert "Incorrect options key" == str(excinfo.value) + + with pytest.raises(ValueError) as excinfo: + stix2.v21.SocketExt( + is_listening=True, + address_family="AF_INET", + protocol_family="PF_INET", + socket_type="SOCK_STREAM", + options={"SO_RCVTIMEO": '100'}, + ) + assert "Options value must be an integer" == str(excinfo.value) + + def test_network_traffic_tcp_example(): h = stix2.v21.TCPExt(src_flags_hex="00000002") nt = stix2.v21.NetworkTraffic( @@ -1366,6 +1388,18 @@ def test_x509_certificate_example(): assert x509.subject == "C=US, ST=Maryland, L=Pasadena, O=Brent Baccala, OU=FreeSoft, CN=www.freesoft.org/[email protected]" # noqa +def test_x509_certificate_error(): + + with pytest.raises(stix2.exceptions.PropertyPresenceError) as excinfo: + stix2.v21.X509Certificate( + defanged=True, + ) + + assert excinfo.value.cls == stix2.v21.X509Certificate + assert "At least one of the" in str(excinfo.value) + assert "properties for X509Certificate must be populated." in str(excinfo.value) + + def test_new_version_with_related_objects(): data = stix2.v21.ObservedData( first_observed="2016-03-12T12:00:00Z", diff --git a/stix2/test/v21/test_properties.py b/stix2/test/v21/test_properties.py index 1fb3cc4..50bce17 100644 --- a/stix2/test/v21/test_properties.py +++ b/stix2/test/v21/test_properties.py @@ -72,6 +72,14 @@ def test_list_property(): p.clean([]) +def test_dictionary_property(): + p = DictionaryProperty(StringProperty) + + assert p.clean({'spec_version': '2.1'}) + with pytest.raises(ValueError): + p.clean({}) + + def test_string_property(): prop = StringProperty() @@ -411,6 +419,7 @@ def test_property_list_of_dictionary(): "value", [ {"sha256": "6db12788c37247f2316052e142f42f4b259d6561751e5f401a1ae2a6df9c674b"}, [('MD5', '2dfb1bcc980200c6706feee399d41b3f'), ('RIPEMD-160', 'b3a8cd8a27c90af79b3c81754f267780f443dfef')], + [('TLSH', '6FF02BEF718027B0160B4391212923ED7F1A463D563B1549B86CF62973B197AD2731F8')], ], ) def test_hashes_property_valid(value): @@ -422,6 +431,7 @@ def test_hashes_property_valid(value): "value", [ {"MD5": "a"}, {"SHA-256": "2dfb1bcc980200c6706feee399d41b3f"}, + {"TLSH": "6FF02BEF718027B0160B4391212923ED7F1A463D563B1549B86CF62973B197AD2731F"}, ], ) def test_hashes_property_invalid(value):
Update to STIX 2.1WD06 Necessary changes I see: * [ ] `indicator.pattern_version`: if stix patterning lang used, default is spec_version of the object * [ ] Empty dictionaries are now prohibited just like empty lists * [ ] `socket-ext.options` now has some requirements around its keys/values * [ ] Add a test to make sure we throw an error when trying to create an x509-certificate with only common properties and no x509-specific properties. * [ ] Add TLSH to `properties.HASHES_REGEX`
0.0
[ "stix2/test/v21/test_bundle.py::test_create_bundle1", "stix2/test/v21/test_bundle.py::test_create_bundle2", "stix2/test/v21/test_bundle.py::test_create_bundle_with_positional_args", "stix2/test/v21/test_bundle.py::test_create_bundle_with_positional_listarg", "stix2/test/v21/test_bundle.py::test_create_bundle_with_listarg_and_positional_arg", "stix2/test/v21/test_bundle.py::test_create_bundle_with_listarg_and_kwarg", "stix2/test/v21/test_bundle.py::test_create_bundle_with_arg_listarg_and_kwarg", "stix2/test/v21/test_indicator.py::test_indicator_with_all_required_properties", "stix2/test/v21/test_observed_data.py::test_incorrect_socket_options", "stix2/test/v21/test_observed_data.py::test_x509_certificate_error", "stix2/test/v21/test_properties.py::test_dictionary_property", "stix2/test/v21/test_properties.py::test_hashes_property_invalid[value2]" ]
[ "stix2/test/v21/test_bundle.py::test_empty_bundle", "stix2/test/v21/test_bundle.py::test_bundle_with_wrong_type", "stix2/test/v21/test_bundle.py::test_bundle_id_must_start_with_bundle", "stix2/test/v21/test_bundle.py::test_create_bundle_invalid", "stix2/test/v21/test_bundle.py::test_parse_bundle[2.1]", "stix2/test/v21/test_bundle.py::test_parse_unknown_type", "stix2/test/v21/test_bundle.py::test_stix_object_property", "stix2/test/v21/test_bundle.py::test_bundle_obj_id_found", "stix2/test/v21/test_bundle.py::test_bundle_objs_ids_found[bundle_data0]", "stix2/test/v21/test_bundle.py::test_bundle_getitem_overload_property_found", "stix2/test/v21/test_bundle.py::test_bundle_getitem_overload_obj_id_found", "stix2/test/v21/test_bundle.py::test_bundle_obj_id_not_found", "stix2/test/v21/test_bundle.py::test_bundle_getitem_overload_obj_id_not_found", "stix2/test/v21/test_indicator.py::test_indicator_autogenerated_properties", "stix2/test/v21/test_indicator.py::test_indicator_type_must_be_indicator", "stix2/test/v21/test_indicator.py::test_indicator_id_must_start_with_indicator", "stix2/test/v21/test_indicator.py::test_indicator_required_properties", "stix2/test/v21/test_indicator.py::test_indicator_required_property_pattern", "stix2/test/v21/test_indicator.py::test_indicator_created_ref_invalid_format", "stix2/test/v21/test_indicator.py::test_indicator_revoked_invalid", "stix2/test/v21/test_indicator.py::test_cannot_assign_to_indicator_attributes", "stix2/test/v21/test_indicator.py::test_invalid_kwarg_to_indicator", "stix2/test/v21/test_indicator.py::test_created_modified_time_are_identical_by_default", "stix2/test/v21/test_indicator.py::test_parse_indicator[{\\n", "stix2/test/v21/test_indicator.py::test_parse_indicator[data1]", "stix2/test/v21/test_indicator.py::test_invalid_indicator_pattern", "stix2/test/v21/test_observed_data.py::test_observed_data_example", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_refs", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_object_refs", "stix2/test/v21/test_observed_data.py::test_observed_data_object_constraint", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_bad_refs", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_non_dictionary", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_empty_dictionary", "stix2/test/v21/test_observed_data.py::test_parse_observed_data[{\\n", "stix2/test/v21/test_observed_data.py::test_parse_observed_data[data1]", "stix2/test/v21/test_observed_data.py::test_parse_artifact_valid[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_artifact_invalid[\"0\":", "stix2/test/v21/test_observed_data.py::test_artifact_example_dependency_error", "stix2/test/v21/test_observed_data.py::test_parse_autonomous_system_valid[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_email_address[{\\n", "stix2/test/v21/test_observed_data.py::test_parse_email_message[\\n", "stix2/test/v21/test_observed_data.py::test_parse_email_message_not_multipart[\\n", "stix2/test/v21/test_observed_data.py::test_parse_file_archive[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_email_message_with_at_least_one_error[\\n", "stix2/test/v21/test_observed_data.py::test_parse_basic_tcp_traffic[\\n", "stix2/test/v21/test_observed_data.py::test_parse_basic_tcp_traffic_with_error[\\n", "stix2/test/v21/test_observed_data.py::test_observed_data_with_process_example", "stix2/test/v21/test_observed_data.py::test_artifact_example", "stix2/test/v21/test_observed_data.py::test_artifact_mutual_exclusion_error", "stix2/test/v21/test_observed_data.py::test_directory_example", "stix2/test/v21/test_observed_data.py::test_directory_example_ref_error", "stix2/test/v21/test_observed_data.py::test_domain_name_example", "stix2/test/v21/test_observed_data.py::test_domain_name_example_invalid_ref_type", "stix2/test/v21/test_observed_data.py::test_file_example", "stix2/test/v21/test_observed_data.py::test_file_example_with_NTFSExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_empty_NTFSExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_PDFExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_PDFExt_Object", "stix2/test/v21/test_observed_data.py::test_file_example_with_RasterImageExt_Object", "stix2/test/v21/test_observed_data.py::test_raster_image_ext_parse", "stix2/test/v21/test_observed_data.py::test_raster_images_ext_create", "stix2/test/v21/test_observed_data.py::test_file_example_with_WindowsPEBinaryExt", "stix2/test/v21/test_observed_data.py::test_file_example_encryption_error", "stix2/test/v21/test_observed_data.py::test_ipv4_address_example", "stix2/test/v21/test_observed_data.py::test_ipv4_address_valid_refs", "stix2/test/v21/test_observed_data.py::test_ipv4_address_example_cidr", "stix2/test/v21/test_observed_data.py::test_ipv6_address_example", "stix2/test/v21/test_observed_data.py::test_mac_address_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_http_request_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_icmp_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_socket_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_tcp_example", "stix2/test/v21/test_observed_data.py::test_mutex_example", "stix2/test/v21/test_observed_data.py::test_process_example", "stix2/test/v21/test_observed_data.py::test_process_example_empty_error", "stix2/test/v21/test_observed_data.py::test_process_example_empty_with_extensions", "stix2/test/v21/test_observed_data.py::test_process_example_windows_process_ext", "stix2/test/v21/test_observed_data.py::test_process_example_windows_process_ext_empty", "stix2/test/v21/test_observed_data.py::test_process_example_extensions_empty", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsProcessExt_Object", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsServiceExt", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsProcessServiceExt", "stix2/test/v21/test_observed_data.py::test_software_example", "stix2/test/v21/test_observed_data.py::test_url_example", "stix2/test/v21/test_observed_data.py::test_user_account_example", "stix2/test/v21/test_observed_data.py::test_user_account_unix_account_ext_example", "stix2/test/v21/test_observed_data.py::test_windows_registry_key_example", "stix2/test/v21/test_observed_data.py::test_x509_certificate_example", "stix2/test/v21/test_observed_data.py::test_new_version_with_related_objects", "stix2/test/v21/test_observed_data.py::test_objects_deprecation", "stix2/test/v21/test_observed_data.py::test_deterministic_id_same_extra_prop_vals", "stix2/test/v21/test_observed_data.py::test_deterministic_id_diff_extra_prop_vals", "stix2/test/v21/test_observed_data.py::test_deterministic_id_diff_contributing_prop_vals", "stix2/test/v21/test_observed_data.py::test_deterministic_id_no_contributing_props", "stix2/test/v21/test_observed_data.py::test_ipv4_resolves_to_refs_deprecation", "stix2/test/v21/test_observed_data.py::test_ipv4_belongs_to_refs_deprecation", "stix2/test/v21/test_observed_data.py::test_ipv6_resolves_to_refs_deprecation", "stix2/test/v21/test_observed_data.py::test_ipv6_belongs_to_refs_deprecation", "stix2/test/v21/test_properties.py::test_property", "stix2/test/v21/test_properties.py::test_basic_clean", "stix2/test/v21/test_properties.py::test_property_default", "stix2/test/v21/test_properties.py::test_fixed_property", "stix2/test/v21/test_properties.py::test_list_property", "stix2/test/v21/test_properties.py::test_string_property", "stix2/test/v21/test_properties.py::test_type_property", "stix2/test/v21/test_properties.py::test_id_property_valid[my-type--232c9d3f-49fc-4440-bb01-607f638778e7]", "stix2/test/v21/test_properties.py::test_id_property_valid[my-type--00000000-0000-4000-8000-000000000000]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[attack-pattern--0c7b5b88-8ff7-4a4d-aa9d-feb398cd0061]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[campaign--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[course-of-action--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[identity--311b2d2d-f010-4473-83ec-1edf84858f4c]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[indicator--a740531e-63ff-4e49-a9e1-a0a3eed0e3e7]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[intrusion-set--4e78f46f-a023-4e5f-bc24-71b3ca22ec29]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[malware--9c4638ec-f1de-4ddb-abf4-1b760417654e]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9_0]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[observed-data--b67d30ff-02ac-498a-92f9-32f845f448cf]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[relationship--df7c87eb-75d2-4948-af81-9d49d246f301]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[report--84e4d88f-44ea-4bcd-bbf3-b2c1c320bcb3]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[sighting--bfbc19db-ec35-4e45-beed-f8bde2a772fb]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[threat-actor--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[tool--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[vulnerability--0c7b5b88-8ff7-4a4d-aa9d-feb398cd0061]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9_1]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[marking-definition--443eb5c3-a76c-4a0a-8caa-e93998e7bc09]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[marking-definition--57fcd772-9c1d-41b0-8d1f-3d47713415d9]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[marking-definition--462bf1a6-03d2-419c-b74e-eee2238b2de4]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[marking-definition--68520ae2-fefe-43a9-84ee-2c2a934d2c7d]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[marking-definition--2802dfb1-1019-40a8-8848-68d0ec0e417f]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[relationship--06520621-5352-4e6a-b976-e8fa3d437ffd]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[relationship--181c9c09-43e6-45dd-9374-3bec192f05ef]", "stix2/test/v21/test_properties.py::test_id_property_valid_for_type[relationship--a0cbb21c-8daf-4a7f-96aa-7155a4ef8f70]", "stix2/test/v21/test_properties.py::test_id_property_wrong_type", "stix2/test/v21/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--foo]", "stix2/test/v21/test_properties.py::test_id_property_not_a_valid_hex_uuid[my-type--00000000-0000-0000-0000-000000000000]", "stix2/test/v21/test_properties.py::test_id_property_default", "stix2/test/v21/test_properties.py::test_integer_property_valid[2]", "stix2/test/v21/test_properties.py::test_integer_property_valid[-1]", "stix2/test/v21/test_properties.py::test_integer_property_valid[3.14]", "stix2/test/v21/test_properties.py::test_integer_property_valid[False]", "stix2/test/v21/test_properties.py::test_integer_property_invalid_min_with_constraints[-1]", "stix2/test/v21/test_properties.py::test_integer_property_invalid_min_with_constraints[-100]", "stix2/test/v21/test_properties.py::test_integer_property_invalid_min_with_constraints[-300]", "stix2/test/v21/test_properties.py::test_integer_property_invalid_max_with_constraints[181]", "stix2/test/v21/test_properties.py::test_integer_property_invalid_max_with_constraints[200]", "stix2/test/v21/test_properties.py::test_integer_property_invalid_max_with_constraints[300]", "stix2/test/v21/test_properties.py::test_integer_property_invalid[something]", "stix2/test/v21/test_properties.py::test_integer_property_invalid[value1]", "stix2/test/v21/test_properties.py::test_float_property_valid[2]", "stix2/test/v21/test_properties.py::test_float_property_valid[-1]", "stix2/test/v21/test_properties.py::test_float_property_valid[3.14]", "stix2/test/v21/test_properties.py::test_float_property_valid[False]", "stix2/test/v21/test_properties.py::test_float_property_invalid[something]", "stix2/test/v21/test_properties.py::test_float_property_invalid[value1]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[True0]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[False0]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[True1]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[False1]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[true]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[false]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[TRUE]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[FALSE]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[T]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[F]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[t]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[f]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[1]", "stix2/test/v21/test_properties.py::test_boolean_property_valid[0]", "stix2/test/v21/test_properties.py::test_boolean_property_invalid[abc]", "stix2/test/v21/test_properties.py::test_boolean_property_invalid[value1]", "stix2/test/v21/test_properties.py::test_boolean_property_invalid[value2]", "stix2/test/v21/test_properties.py::test_boolean_property_invalid[2]", "stix2/test/v21/test_properties.py::test_boolean_property_invalid[-1]", "stix2/test/v21/test_properties.py::test_reference_property", "stix2/test/v21/test_properties.py::test_reference_property_specific_type", "stix2/test/v21/test_properties.py::test_timestamp_property_valid[2017-01-01T12:34:56Z]", "stix2/test/v21/test_properties.py::test_timestamp_property_valid[2017-01-01", "stix2/test/v21/test_properties.py::test_timestamp_property_valid[Jan", "stix2/test/v21/test_properties.py::test_timestamp_property_invalid", "stix2/test/v21/test_properties.py::test_binary_property", "stix2/test/v21/test_properties.py::test_hex_property", "stix2/test/v21/test_properties.py::test_dictionary_property_valid[d0]", "stix2/test/v21/test_properties.py::test_dictionary_property_valid[d1]", "stix2/test/v21/test_properties.py::test_dictionary_no_longer_raises[d0]", "stix2/test/v21/test_properties.py::test_dictionary_property_invalid_key[d0]", "stix2/test/v21/test_properties.py::test_dictionary_property_invalid_key[d1]", "stix2/test/v21/test_properties.py::test_dictionary_property_invalid[d0]", "stix2/test/v21/test_properties.py::test_property_list_of_dictionary", "stix2/test/v21/test_properties.py::test_hashes_property_valid[value1]", "stix2/test/v21/test_properties.py::test_hashes_property_valid[value2]", "stix2/test/v21/test_properties.py::test_hashes_property_invalid[value0]", "stix2/test/v21/test_properties.py::test_hashes_property_invalid[value1]", "stix2/test/v21/test_properties.py::test_embedded_property", "stix2/test/v21/test_properties.py::test_enum_property_valid[value0]", "stix2/test/v21/test_properties.py::test_enum_property_valid[value1]", "stix2/test/v21/test_properties.py::test_enum_property_valid[b]", "stix2/test/v21/test_properties.py::test_enum_property_clean", "stix2/test/v21/test_properties.py::test_enum_property_invalid", "stix2/test/v21/test_properties.py::test_extension_property_valid", "stix2/test/v21/test_properties.py::test_extension_property_invalid1", "stix2/test/v21/test_properties.py::test_extension_property_invalid2", "stix2/test/v21/test_properties.py::test_extension_property_invalid_type", "stix2/test/v21/test_properties.py::test_extension_at_least_one_property_constraint", "stix2/test/v21/test_properties.py::test_marking_property_error" ]
2019-11-22 18:48:38+00:00
4,292
oasis-open__cti-python-stix2-328
diff --git a/stix2/markings/utils.py b/stix2/markings/utils.py index b1c103b..41516cc 100644 --- a/stix2/markings/utils.py +++ b/stix2/markings/utils.py @@ -271,8 +271,8 @@ def check_tlp_marking(marking_obj, spec_version): else: w = ( '{"created": "2017-01-20T00:00:00.000Z", "definition": {"tlp": "white"}, "definition_type": "tlp",' - ' "id": "marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9", "type": "marking-definition",' - ' "spec_version": "2.1"}' + ' "id": "marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9", "name": "TLP:WHITE",' + ' "type": "marking-definition", "spec_version": "2.1"}' ) if marking_obj["id"] != "marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9": raise exceptions.TLPMarkingDefinitionError(marking_obj["id"], w) @@ -288,8 +288,8 @@ def check_tlp_marking(marking_obj, spec_version): else: g = ( '{"created": "2017-01-20T00:00:00.000Z", "definition": {"tlp": "green"}, "definition_type": "tlp",' - ' "id": "marking-definition--34098fce-860f-48ae-8e50-ebd3cc5e41da", "type": "marking-definition",' - ' "spec_version": "2.1"}' + ' "id": "marking-definition--34098fce-860f-48ae-8e50-ebd3cc5e41da", "name": "TLP:GREEN",' + ' "type": "marking-definition", "spec_version": "2.1"}' ) if marking_obj["id"] != "marking-definition--34098fce-860f-48ae-8e50-ebd3cc5e41da": raise exceptions.TLPMarkingDefinitionError(marking_obj["id"], g) @@ -305,8 +305,8 @@ def check_tlp_marking(marking_obj, spec_version): else: a = ( '{"created": "2017-01-20T00:00:00.000Z", "definition": {"tlp": "amber"}, "definition_type": "tlp",' - ' "id": "marking-definition--f88d31f6-486f-44da-b317-01333bde0b82", "type": "marking-definition",' - ' "spec_version": "2.1"}' + ' "id": "marking-definition--f88d31f6-486f-44da-b317-01333bde0b82", "name": "TLP:AMBER",' + ' "type": "marking-definition", "spec_version": "2.1"}' ) if marking_obj["id"] != "marking-definition--f88d31f6-486f-44da-b317-01333bde0b82": raise exceptions.TLPMarkingDefinitionError(marking_obj["id"], a) @@ -322,8 +322,8 @@ def check_tlp_marking(marking_obj, spec_version): else: r = ( '{"created": "2017-01-20T00:00:00.000Z", "definition": {"tlp": "red"}, "definition_type": "tlp",' - ' "id": "marking-definition--5e57c739-391a-4eb3-b6be-7d15ca92d5ed", "type": "marking-definition",' - ' "spec_version": "2.1"}' + ' "id": "marking-definition--5e57c739-391a-4eb3-b6be-7d15ca92d5ed", "name": "TLP:RED",' + ' "type": "marking-definition", "spec_version": "2.1"}' ) if marking_obj["id"] != "marking-definition--5e57c739-391a-4eb3-b6be-7d15ca92d5ed": raise exceptions.TLPMarkingDefinitionError(marking_obj["id"], r) diff --git a/stix2/v21/common.py b/stix2/v21/common.py index 4a71308..cf3a3b3 100644 --- a/stix2/v21/common.py +++ b/stix2/v21/common.py @@ -150,6 +150,7 @@ class MarkingDefinition(_STIXBase, _MarkingsMixin): ('object_marking_refs', ListProperty(ReferenceProperty(valid_types='marking-definition', spec_version='2.1'))), ('granular_markings', ListProperty(GranularMarking)), ('definition_type', StringProperty(required=True)), + ('name', StringProperty()), ('definition', MarkingProperty(required=True)), ]) @@ -207,6 +208,7 @@ TLP_WHITE = MarkingDefinition( id='marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9', created='2017-01-20T00:00:00.000Z', definition_type='tlp', + name='TLP:WHITE', definition=TLPMarking(tlp='white'), ) @@ -214,6 +216,7 @@ TLP_GREEN = MarkingDefinition( id='marking-definition--34098fce-860f-48ae-8e50-ebd3cc5e41da', created='2017-01-20T00:00:00.000Z', definition_type='tlp', + name='TLP:GREEN', definition=TLPMarking(tlp='green'), ) @@ -221,6 +224,7 @@ TLP_AMBER = MarkingDefinition( id='marking-definition--f88d31f6-486f-44da-b317-01333bde0b82', created='2017-01-20T00:00:00.000Z', definition_type='tlp', + name='TLP:AMBER', definition=TLPMarking(tlp='amber'), ) @@ -228,5 +232,6 @@ TLP_RED = MarkingDefinition( id='marking-definition--5e57c739-391a-4eb3-b6be-7d15ca92d5ed', created='2017-01-20T00:00:00.000Z', definition_type='tlp', + name='TLP:RED', definition=TLPMarking(tlp='red'), )
oasis-open/cti-python-stix2
0af1f442c0cb6e30132174b5b657a6a35ef78a08
diff --git a/stix2/test/v21/test_marking_definition.py b/stix2/test/v21/test_marking_definition.py index c497e99..232bdf2 100644 --- a/stix2/test/v21/test_marking_definition.py +++ b/stix2/test/v21/test_marking_definition.py @@ -12,6 +12,7 @@ def test_bad_id_marking_tlp_white(): MarkingDefinition( id='marking-definition--4c9faac1-3558-43d2-919e-95c88d3bc332', definition_type='tlp', + name='TLP:WHITE', definition=TLPMarking(tlp='white'), ) @@ -21,6 +22,7 @@ def test_bad_id_marking_tlp_green(): MarkingDefinition( id='marking-definition--93023361-d3cf-4666-bca2-8c017948dc3d', definition_type='tlp', + name='TLP:GREEN', definition=TLPMarking(tlp='green'), ) @@ -30,6 +32,7 @@ def test_bad_id_marking_tlp_amber(): MarkingDefinition( id='marking-definition--05e32101-a940-42ba-8fe9-39283b999ce4', definition_type='tlp', + name='TLP:AMBER', definition=TLPMarking(tlp='amber'), ) @@ -39,6 +42,7 @@ def test_bad_id_marking_tlp_red(): MarkingDefinition( id='marking-definition--9eceb00c-c158-43f4-87f8-1e3648de17e2', definition_type='tlp', + name='TLP:RED', definition=TLPMarking(tlp='red'), ) @@ -48,6 +52,7 @@ def test_bad_created_marking_tlp_white(): MarkingDefinition( id='marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9', definition_type='tlp', + name='TLP:WHITE', definition=TLPMarking(tlp='white'), ) @@ -57,6 +62,7 @@ def test_bad_created_marking_tlp_green(): MarkingDefinition( id='marking-definition--34098fce-860f-48ae-8e50-ebd3cc5e41da', definition_type='tlp', + name='TLP:GREEN', definition=TLPMarking(tlp='green'), ) @@ -66,6 +72,7 @@ def test_bad_created_marking_tlp_amber(): MarkingDefinition( id='marking-definition--f88d31f6-486f-44da-b317-01333bde0b82', definition_type='tlp', + name='TLP:AMBER', definition=TLPMarking(tlp='amber'), ) @@ -75,6 +82,7 @@ def test_bad_created_marking_tlp_red(): MarkingDefinition( id='marking-definition--5e57c739-391a-4eb3-b6be-7d15ca92d5ed', definition_type='tlp', + name='TLP:RED', definition=TLPMarking(tlp='red'), ) @@ -86,6 +94,7 @@ def test_successful_tlp_white(): id='marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9', created='2017-01-20T00:00:00.000Z', definition_type='tlp', + name='TLP:WHITE', definition=TLPMarking(tlp='white'), ) @@ -97,6 +106,7 @@ def test_successful_tlp_green(): id='marking-definition--34098fce-860f-48ae-8e50-ebd3cc5e41da', created='2017-01-20T00:00:00.000Z', definition_type='tlp', + name='TLP:GREEN', definition=TLPMarking(tlp='green'), ) @@ -108,6 +118,7 @@ def test_successful_tlp_amber(): id='marking-definition--f88d31f6-486f-44da-b317-01333bde0b82', created='2017-01-20T00:00:00.000Z', definition_type='tlp', + name='TLP:AMBER', definition=TLPMarking(tlp='amber'), ) @@ -119,6 +130,7 @@ def test_successful_tlp_red(): id='marking-definition--5e57c739-391a-4eb3-b6be-7d15ca92d5ed', created='2017-01-20T00:00:00.000Z', definition_type='tlp', + name='TLP:RED', definition=TLPMarking(tlp='red'), ) diff --git a/stix2/test/v21/test_markings.py b/stix2/test/v21/test_markings.py index 1f9f5e8..a2fca51 100644 --- a/stix2/test/v21/test_markings.py +++ b/stix2/test/v21/test_markings.py @@ -16,6 +16,7 @@ EXPECTED_TLP_MARKING_DEFINITION = """{ "id": "marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9", "created": "2017-01-20T00:00:00.000Z", "definition_type": "tlp", + "name": "TLP:WHITE", "definition": { "tlp": "white" }
`name` field missing from MarkingDefinition object Super quick one: MarkingDefinition object should have an optional `name` field as per the current spec. Believe it needs adding to `common.py`.
0.0
[ "stix2/test/v21/test_marking_definition.py::test_bad_id_marking_tlp_white", "stix2/test/v21/test_marking_definition.py::test_bad_id_marking_tlp_green", "stix2/test/v21/test_marking_definition.py::test_bad_id_marking_tlp_amber", "stix2/test/v21/test_marking_definition.py::test_bad_id_marking_tlp_red", "stix2/test/v21/test_marking_definition.py::test_bad_created_marking_tlp_white", "stix2/test/v21/test_marking_definition.py::test_bad_created_marking_tlp_green", "stix2/test/v21/test_marking_definition.py::test_bad_created_marking_tlp_amber", "stix2/test/v21/test_marking_definition.py::test_bad_created_marking_tlp_red", "stix2/test/v21/test_marking_definition.py::test_successful_tlp_white", "stix2/test/v21/test_marking_definition.py::test_successful_tlp_green", "stix2/test/v21/test_marking_definition.py::test_successful_tlp_amber", "stix2/test/v21/test_marking_definition.py::test_successful_tlp_red", "stix2/test/v21/test_markings.py::test_marking_def_example_with_tlp", "stix2/test/v21/test_markings.py::test_parse_marking_definition[{\\n" ]
[ "stix2/test/v21/test_marking_definition.py::test_unknown_tlp_marking", "stix2/test/v21/test_markings.py::test_marking_def_example_with_statement_positional_argument", "stix2/test/v21/test_markings.py::test_marking_def_example_with_kwargs_statement", "stix2/test/v21/test_markings.py::test_marking_def_invalid_type", "stix2/test/v21/test_markings.py::test_campaign_with_markings_example", "stix2/test/v21/test_markings.py::test_granular_example", "stix2/test/v21/test_markings.py::test_granular_example_with_bad_selector", "stix2/test/v21/test_markings.py::test_campaign_with_granular_markings_example", "stix2/test/v21/test_markings.py::test_parse_marking_definition[data1]", "stix2/test/v21/test_markings.py::test_registered_custom_marking", "stix2/test/v21/test_markings.py::test_registered_custom_marking_raises_exception", "stix2/test/v21/test_markings.py::test_not_registered_marking_raises_exception", "stix2/test/v21/test_markings.py::test_marking_wrong_type_construction", "stix2/test/v21/test_markings.py::test_campaign_add_markings", "stix2/test/v21/test_markings.py::test_campaign_with_granular_lang_markings_example" ]
2020-01-28 18:27:14+00:00
4,293
oasis-open__cti-python-stix2-337
diff --git a/stix2/core.py b/stix2/core.py index aa9044d..0d1fee5 100644 --- a/stix2/core.py +++ b/stix2/core.py @@ -58,6 +58,47 @@ def parse(data, allow_custom=False, version=None): return obj +def _detect_spec_version(stix_dict): + """ + Given a dict representing a STIX object, try to detect what spec version + it is likely to comply with. + + :param stix_dict: A dict with some STIX content. Must at least have a + "type" property. + :return: A string in "vXX" format, where "XX" indicates the spec version, + e.g. "v20", "v21", etc. + """ + + obj_type = stix_dict["type"] + + if 'spec_version' in stix_dict: + # For STIX 2.0, applies to bundles only. + # For STIX 2.1+, applies to SCOs, SDOs, SROs, and markings only. + v = 'v' + stix_dict['spec_version'].replace('.', '') + elif "id" not in stix_dict: + # Only 2.0 SCOs don't have ID properties + v = "v20" + elif obj_type == 'bundle': + # Bundle without a spec_version property: must be 2.1. But to + # future-proof, use max version over all contained SCOs, with 2.1 + # minimum. + v = max( + "v21", + max( + _detect_spec_version(obj) for obj in stix_dict["objects"] + ), + ) + elif obj_type in STIX2_OBJ_MAPS["v21"]["observables"]: + # Non-bundle object with an ID and without spec_version. Could be a + # 2.1 SCO or 2.0 SDO/SRO/marking. Check for 2.1 SCO... + v = "v21" + else: + # Not a 2.1 SCO; must be a 2.0 object. + v = "v20" + + return v + + def dict_to_stix2(stix_dict, allow_custom=False, version=None): """convert dictionary to full python-stix2 object @@ -93,21 +134,8 @@ def dict_to_stix2(stix_dict, allow_custom=False, version=None): if version: # If the version argument was passed, override other approaches. v = 'v' + version.replace('.', '') - elif 'spec_version' in stix_dict: - # For STIX 2.0, applies to bundles only. - # For STIX 2.1+, applies to SDOs, SROs, and markings only. - v = 'v' + stix_dict['spec_version'].replace('.', '') - elif stix_dict['type'] == 'bundle': - # bundles without spec_version are ambiguous. - if any('spec_version' in x for x in stix_dict['objects']): - # Only on 2.1 we are allowed to have 'spec_version' in SDOs/SROs. - v = 'v21' - else: - v = 'v' + stix2.DEFAULT_VERSION.replace('.', '') else: - # The spec says that SDO/SROs without spec_version will default to a - # '2.0' representation. - v = 'v20' + v = _detect_spec_version(stix_dict) OBJ_MAP = dict(STIX2_OBJ_MAPS[v]['objects'], **STIX2_OBJ_MAPS[v]['observables']) @@ -142,6 +170,10 @@ def parse_observable(data, _valid_refs=None, allow_custom=False, version=None): """ obj = _get_dict(data) + + if 'type' not in obj: + raise ParseError("Can't parse observable with no 'type' property: %s" % str(obj)) + # get deep copy since we are going modify the dict and might # modify the original dict as _get_dict() does not return new # dict when passed a dict @@ -153,11 +185,8 @@ def parse_observable(data, _valid_refs=None, allow_custom=False, version=None): # If the version argument was passed, override other approaches. v = 'v' + version.replace('.', '') else: - # Use default version (latest) if no version was provided. - v = 'v' + stix2.DEFAULT_VERSION.replace('.', '') + v = _detect_spec_version(obj) - if 'type' not in obj: - raise ParseError("Can't parse observable with no 'type' property: %s" % str(obj)) try: OBJ_MAP_OBSERVABLE = STIX2_OBJ_MAPS[v]['observables'] obj_class = OBJ_MAP_OBSERVABLE[obj['type']]
oasis-open/cti-python-stix2
c96b74294a5b9c4f3d066211d8f99ae1a97c0d9d
diff --git a/stix2/test/test_spec_version_detect.py b/stix2/test/test_spec_version_detect.py new file mode 100644 index 0000000..d2a9da8 --- /dev/null +++ b/stix2/test/test_spec_version_detect.py @@ -0,0 +1,212 @@ +from __future__ import unicode_literals + +import pytest + +from stix2.core import _detect_spec_version + + [email protected]( + "obj_dict, expected_ver", [ + # STIX 2.0 examples + ( + { + "type": "identity", + "id": "identity--d7f72e8d-657a-43ec-9324-b3ec67a97486", + "created": "1972-05-21T05:33:09.000Z", + "modified": "1973-05-28T02:10:54.000Z", + "name": "alice", + "identity_class": "individual", + }, + "v20", + ), + ( + { + "type": "relationship", + "id": "relationship--63b0f1b7-925e-4795-ac9b-61fb9f235f1a", + "created": "1981-08-11T13:48:19.000Z", + "modified": "2000-02-16T15:33:15.000Z", + "source_ref": "attack-pattern--9391504a-ef29-4a41-a257-5634d9edc391", + "target_ref": "identity--ba18dde2-56d3-4a34-aa0b-fc56f5be568f", + "relationship_type": "targets", + }, + "v20", + ), + ( + { + "type": "file", + "name": "notes.txt", + }, + "v20", + ), + ( + { + "type": "marking-definition", + "id": "marking-definition--2a13090f-a493-4b70-85fe-fa021d91dcd2", + "created": "1998-03-27T19:44:53.000Z", + "definition_type": "statement", + "definition": { + "statement": "Copyright (c) ACME Corp.", + }, + }, + "v20", + ), + ( + { + "type": "bundle", + "id": "bundle--8379cb02-8131-47c8-8a7c-9a1f0e0986b1", + "spec_version": "2.0", + "objects": [ + { + "type": "identity", + "id": "identity--d7f72e8d-657a-43ec-9324-b3ec67a97486", + "created": "1972-05-21T05:33:09.000Z", + "modified": "1973-05-28T02:10:54.000Z", + "name": "alice", + "identity_class": "individual", + }, + { + "type": "marking-definition", + "id": "marking-definition--2a13090f-a493-4b70-85fe-fa021d91dcd2", + "created": "1998-03-27T19:44:53.000Z", + "definition_type": "statement", + "definition": { + "statement": "Copyright (c) ACME Corp.", + }, + }, + ], + }, + "v20", + ), + # STIX 2.1 examples + ( + { + "type": "identity", + "id": "identity--22299b4c-bc38-4485-ad7d-8222f01c58c7", + "spec_version": "2.1", + "created": "1995-07-24T04:07:48.000Z", + "modified": "2001-07-01T09:33:17.000Z", + "name": "alice", + }, + "v21", + ), + ( + { + "type": "relationship", + "id": "relationship--0eec232d-e1ea-4f85-8e78-0de6ae9d09f0", + "spec_version": "2.1", + "created": "1975-04-05T10:47:22.000Z", + "modified": "1983-04-25T20:56:00.000Z", + "source_ref": "attack-pattern--9391504a-ef29-4a41-a257-5634d9edc391", + "target_ref": "identity--ba18dde2-56d3-4a34-aa0b-fc56f5be568f", + "relationship_type": "targets", + }, + "v21", + ), + ( + { + "type": "file", + "id": "file--5eef3404-6a94-4db3-9a1a-5684cbea0dfe", + "spec_version": "2.1", + "name": "notes.txt", + }, + "v21", + ), + ( + { + "type": "file", + "id": "file--5eef3404-6a94-4db3-9a1a-5684cbea0dfe", + "name": "notes.txt", + }, + "v21", + ), + ( + { + "type": "marking-definition", + "spec_version": "2.1", + "id": "marking-definition--34098fce-860f-48ae-8e50-ebd3cc5e41da", + "created": "2017-01-20T00:00:00.000Z", + "definition_type": "tlp", + "name": "TLP:GREEN", + "definition": { + "tlp": "green", + }, + }, + "v21", + ), + ( + { + "type": "bundle", + "id": "bundle--d5787acd-1ffd-4630-ada3-6857698f6287", + "objects": [ + { + "type": "identity", + "id": "identity--22299b4c-bc38-4485-ad7d-8222f01c58c7", + "spec_version": "2.1", + "created": "1995-07-24T04:07:48.000Z", + "modified": "2001-07-01T09:33:17.000Z", + "name": "alice", + }, + { + "type": "file", + "id": "file--5eef3404-6a94-4db3-9a1a-5684cbea0dfe", + "name": "notes.txt", + }, + ], + }, + "v21", + ), + # Mixed spec examples + ( + { + "type": "bundle", + "id": "bundle--e1a01e29-3432-401a-ab9f-c1082b056605", + "objects": [ + { + "type": "identity", + "id": "identity--d7f72e8d-657a-43ec-9324-b3ec67a97486", + "created": "1972-05-21T05:33:09.000Z", + "modified": "1973-05-28T02:10:54.000Z", + "name": "alice", + "identity_class": "individual", + }, + { + "type": "relationship", + "id": "relationship--63b0f1b7-925e-4795-ac9b-61fb9f235f1a", + "created": "1981-08-11T13:48:19.000Z", + "modified": "2000-02-16T15:33:15.000Z", + "source_ref": "attack-pattern--9391504a-ef29-4a41-a257-5634d9edc391", + "target_ref": "identity--ba18dde2-56d3-4a34-aa0b-fc56f5be568f", + "relationship_type": "targets", + }, + ], + }, + "v21", + ), + ( + { + "type": "bundle", + "id": "bundle--eecad3d9-bb9a-4263-93f6-1c0ccc984574", + "objects": [ + { + "type": "identity", + "id": "identity--d7f72e8d-657a-43ec-9324-b3ec67a97486", + "created": "1972-05-21T05:33:09.000Z", + "modified": "1973-05-28T02:10:54.000Z", + "name": "alice", + "identity_class": "individual", + }, + { + "type": "file", + "id": "file--5eef3404-6a94-4db3-9a1a-5684cbea0dfe", + "name": "notes.txt", + }, + ], + }, + "v21", + ), + ], +) +def test_spec_version_detect(obj_dict, expected_ver): + detected_ver = _detect_spec_version(obj_dict) + + assert detected_ver == expected_ver
version arg is not passed down with the call to parse in STIXObjectProperty.clean If the version argument is passed in on the original call to parse, it should be passed down also in any recursive calls. This was not the case here: https://github.com/oasis-open/cti-python-stix2/blob/e3c2a3a57b83da8ce914ba7ea738d2e2813d551e/stix2/properties.py#L685.
0.0
[ "stix2/test/test_spec_version_detect.py::test_spec_version_detect[obj_dict0-v20]", "stix2/test/test_spec_version_detect.py::test_spec_version_detect[obj_dict1-v20]", "stix2/test/test_spec_version_detect.py::test_spec_version_detect[obj_dict2-v20]", "stix2/test/test_spec_version_detect.py::test_spec_version_detect[obj_dict3-v20]", "stix2/test/test_spec_version_detect.py::test_spec_version_detect[obj_dict4-v20]", "stix2/test/test_spec_version_detect.py::test_spec_version_detect[obj_dict5-v21]", "stix2/test/test_spec_version_detect.py::test_spec_version_detect[obj_dict6-v21]", "stix2/test/test_spec_version_detect.py::test_spec_version_detect[obj_dict7-v21]", "stix2/test/test_spec_version_detect.py::test_spec_version_detect[obj_dict8-v21]", "stix2/test/test_spec_version_detect.py::test_spec_version_detect[obj_dict9-v21]", "stix2/test/test_spec_version_detect.py::test_spec_version_detect[obj_dict10-v21]", "stix2/test/test_spec_version_detect.py::test_spec_version_detect[obj_dict11-v21]", "stix2/test/test_spec_version_detect.py::test_spec_version_detect[obj_dict12-v21]" ]
[]
2020-02-07 23:46:51+00:00
4,294
oasis-open__cti-python-stix2-342
diff --git a/stix2/datastore/memory.py b/stix2/datastore/memory.py index 52bf4c8..52da168 100644 --- a/stix2/datastore/memory.py +++ b/stix2/datastore/memory.py @@ -10,7 +10,6 @@ from stix2.base import _STIXBase from stix2.core import parse from stix2.datastore import DataSink, DataSource, DataStoreMixin from stix2.datastore.filters import FilterSet, apply_common_filters -from stix2.utils import is_marking def _add(store, stix_data, allow_custom=True, version=None): @@ -47,12 +46,10 @@ def _add(store, stix_data, allow_custom=True, version=None): else: stix_obj = parse(stix_data, allow_custom, version) - # Map ID directly to the object, if it is a marking. Otherwise, - # map to a family, so we can track multiple versions. - if is_marking(stix_obj): - store._data[stix_obj["id"]] = stix_obj - - else: + # Map ID to a _ObjectFamily if the object is versioned, so we can track + # multiple versions. Otherwise, map directly to the object. All + # versioned objects should have a "modified" property. + if "modified" in stix_obj: if stix_obj["id"] in store._data: obj_family = store._data[stix_obj["id"]] else: @@ -61,6 +58,9 @@ def _add(store, stix_data, allow_custom=True, version=None): obj_family.add(stix_obj) + else: + store._data[stix_obj["id"]] = stix_obj + class _ObjectFamily(object): """ @@ -267,12 +267,12 @@ class MemorySource(DataSource): """ stix_obj = None - if is_marking(stix_id): - stix_obj = self._data.get(stix_id) - else: - object_family = self._data.get(stix_id) - if object_family: - stix_obj = object_family.latest_version + mapped_value = self._data.get(stix_id) + if mapped_value: + if isinstance(mapped_value, _ObjectFamily): + stix_obj = mapped_value.latest_version + else: + stix_obj = mapped_value if stix_obj: all_filters = list( @@ -300,17 +300,13 @@ class MemorySource(DataSource): """ results = [] - stix_objs_to_filter = None - if is_marking(stix_id): - stix_obj = self._data.get(stix_id) - if stix_obj: - stix_objs_to_filter = [stix_obj] - else: - object_family = self._data.get(stix_id) - if object_family: - stix_objs_to_filter = object_family.all_versions.values() + mapped_value = self._data.get(stix_id) + if mapped_value: + if isinstance(mapped_value, _ObjectFamily): + stix_objs_to_filter = mapped_value.all_versions.values() + else: + stix_objs_to_filter = [mapped_value] - if stix_objs_to_filter: all_filters = list( itertools.chain( _composite_filters or [],
oasis-open/cti-python-stix2
fdb00c4a8cfe7327bbac609f029b3ff2366b8ccd
diff --git a/stix2/test/v20/test_datastore_memory.py b/stix2/test/v20/test_datastore_memory.py index fba96dd..7852746 100644 --- a/stix2/test/v20/test_datastore_memory.py +++ b/stix2/test/v20/test_datastore_memory.py @@ -423,3 +423,24 @@ def test_object_family_internal_components(mem_source): assert "latest=2017-01-27 13:49:53.936000+00:00>>" in str_representation assert "latest=2017-01-27 13:49:53.936000+00:00>>" in repr_representation + + +def test_unversioned_objects(mem_store): + marking = { + "type": "marking-definition", + "id": "marking-definition--48e83cde-e902-4404-85b3-6e81f75ccb62", + "created": "1988-01-02T16:44:04.000Z", + "definition_type": "statement", + "definition": { + "statement": "Copyright (C) ACME Corp.", + }, + } + + mem_store.add(marking) + + obj = mem_store.get(marking["id"]) + assert obj["id"] == marking["id"] + + objs = mem_store.all_versions(marking["id"]) + assert len(objs) == 1 + assert objs[0]["id"] == marking["id"] diff --git a/stix2/test/v21/test_datastore_memory.py b/stix2/test/v21/test_datastore_memory.py index 4f63a06..e07943c 100644 --- a/stix2/test/v21/test_datastore_memory.py +++ b/stix2/test/v21/test_datastore_memory.py @@ -438,3 +438,38 @@ def test_object_family_internal_components(mem_source): assert "latest=2017-01-27 13:49:53.936000+00:00>>" in str_representation assert "latest=2017-01-27 13:49:53.936000+00:00>>" in repr_representation + + +def test_unversioned_objects(mem_store): + marking = { + "type": "marking-definition", + "spec_version": "2.1", + "id": "marking-definition--48e83cde-e902-4404-85b3-6e81f75ccb62", + "created": "1988-01-02T16:44:04.000Z", + "definition_type": "statement", + "definition": { + "statement": "Copyright (C) ACME Corp.", + }, + } + + file_sco = { + "type": "file", + "id": "file--bbd59c0c-1aa4-44f1-96de-80b8325372c7", + "name": "cats.png", + } + + mem_store.add([marking, file_sco]) + + obj = mem_store.get(marking["id"]) + assert obj["id"] == marking["id"] + + obj = mem_store.get(file_sco["id"]) + assert obj["id"] == file_sco["id"] + + objs = mem_store.all_versions(marking["id"]) + assert len(objs) == 1 + assert objs[0]["id"] == marking["id"] + + objs = mem_store.all_versions(file_sco["id"]) + assert len(objs) == 1 + assert objs[0]["id"] == file_sco["id"]
Adding SCO to the MemoryStore results in error Below an example of how to trigger the problem: ``` python from stix2.v21 import observables from stix2 import MemoryStore mem_store = MemoryStore() file_observable = observables.File( name="example.exe", size=68 * 1000, magic_number_hex="50000000", hashes={ "SHA-256": "841a8921140aba50671ebb0770fecc4ee308c4952cfeff8de154ab14eeef4649" } ) mem_store.add(file_observable) ``` I obtain the following traceback: ``` Traceback (most recent call last): File "C:/Users/user-1/example_project/mem_store.py", line 98, in <module> example() File "C:/Users/user-1/example_project/mem_store.py", line 94, in example mem_store.add(file_observable) File "C:\Users\user-1\venv\lib\site-packages\stix2\datastore\__init__.py", line 216, in add return self.sink.add(*args, **kwargs) File "C:\Users\user-1\venv\lib\site-packages\stix2\datastore\memory.py", line 185, in add _add(self, stix_data, self.allow_custom, version) File "C:\Users\user-1\venv\lib\site-packages\stix2\datastore\memory.py", line 62, in _add obj_family.add(stix_obj) File "C:\Users\user-1\venv\lib\site-packages\stix2\datastore\memory.py", line 77, in add self.all_versions[obj["modified"]] = obj File "C:\Users\user-1\venv\lib\site-packages\stix2\base.py", line 195, in __getitem__ return self._inner[key] KeyError: 'modified' ```
0.0
[ "stix2/test/v21/test_datastore_memory.py::test_unversioned_objects" ]
[ "stix2/test/v20/test_datastore_memory.py::test_memory_source_get", "stix2/test/v20/test_datastore_memory.py::test_memory_source_get_nonexistant_object", "stix2/test/v20/test_datastore_memory.py::test_memory_store_all_versions", "stix2/test/v20/test_datastore_memory.py::test_memory_store_query", "stix2/test/v20/test_datastore_memory.py::test_memory_store_query_single_filter", "stix2/test/v20/test_datastore_memory.py::test_memory_store_query_empty_query", "stix2/test/v20/test_datastore_memory.py::test_memory_store_query_multiple_filters", "stix2/test/v20/test_datastore_memory.py::test_memory_store_save_load_file", "stix2/test/v20/test_datastore_memory.py::test_memory_store_save_load_file_no_name_provided", "stix2/test/v20/test_datastore_memory.py::test_memory_store_add_invalid_object", "stix2/test/v20/test_datastore_memory.py::test_memory_store_object_with_custom_property", "stix2/test/v20/test_datastore_memory.py::test_memory_store_object_creator_of_present", "stix2/test/v20/test_datastore_memory.py::test_memory_store_object_creator_of_missing", "stix2/test/v20/test_datastore_memory.py::test_memory_store_object_with_custom_property_in_bundle", "stix2/test/v20/test_datastore_memory.py::test_memory_store_custom_object", "stix2/test/v20/test_datastore_memory.py::test_relationships", "stix2/test/v20/test_datastore_memory.py::test_relationships_by_type", "stix2/test/v20/test_datastore_memory.py::test_relationships_by_source", "stix2/test/v20/test_datastore_memory.py::test_relationships_by_target", "stix2/test/v20/test_datastore_memory.py::test_relationships_by_target_and_type", "stix2/test/v20/test_datastore_memory.py::test_relationships_by_target_and_source", "stix2/test/v20/test_datastore_memory.py::test_related_to", "stix2/test/v20/test_datastore_memory.py::test_related_to_by_source", "stix2/test/v20/test_datastore_memory.py::test_related_to_by_target", "stix2/test/v20/test_datastore_memory.py::test_object_family_internal_components", "stix2/test/v20/test_datastore_memory.py::test_unversioned_objects", "stix2/test/v21/test_datastore_memory.py::test_memory_source_get", "stix2/test/v21/test_datastore_memory.py::test_memory_source_get_nonexistant_object", "stix2/test/v21/test_datastore_memory.py::test_memory_store_all_versions", "stix2/test/v21/test_datastore_memory.py::test_memory_store_query", "stix2/test/v21/test_datastore_memory.py::test_memory_store_query_single_filter", "stix2/test/v21/test_datastore_memory.py::test_memory_store_query_empty_query", "stix2/test/v21/test_datastore_memory.py::test_memory_store_query_multiple_filters", "stix2/test/v21/test_datastore_memory.py::test_memory_store_save_load_file", "stix2/test/v21/test_datastore_memory.py::test_memory_store_save_load_file_no_name_provided", "stix2/test/v21/test_datastore_memory.py::test_memory_store_add_invalid_object", "stix2/test/v21/test_datastore_memory.py::test_memory_store_object_with_custom_property", "stix2/test/v21/test_datastore_memory.py::test_memory_store_object_creator_of_present", "stix2/test/v21/test_datastore_memory.py::test_memory_store_object_creator_of_missing", "stix2/test/v21/test_datastore_memory.py::test_memory_store_object_with_custom_property_in_bundle", "stix2/test/v21/test_datastore_memory.py::test_memory_store_custom_object", "stix2/test/v21/test_datastore_memory.py::test_relationships", "stix2/test/v21/test_datastore_memory.py::test_relationships_by_type", "stix2/test/v21/test_datastore_memory.py::test_relationships_by_source", "stix2/test/v21/test_datastore_memory.py::test_relationships_by_target", "stix2/test/v21/test_datastore_memory.py::test_relationships_by_target_and_type", "stix2/test/v21/test_datastore_memory.py::test_relationships_by_target_and_source", "stix2/test/v21/test_datastore_memory.py::test_related_to", "stix2/test/v21/test_datastore_memory.py::test_related_to_by_source", "stix2/test/v21/test_datastore_memory.py::test_related_to_by_target", "stix2/test/v21/test_datastore_memory.py::test_object_family_internal_components" ]
2020-02-13 22:34:44+00:00
4,295
oasis-open__cti-python-stix2-344
diff --git a/stix2/base.py b/stix2/base.py index a283902..4248075 100644 --- a/stix2/base.py +++ b/stix2/base.py @@ -388,14 +388,12 @@ class _Observable(_STIXBase): temp_deep_copy = copy.deepcopy(dict(kwargs[key])) _recursive_stix_to_dict(temp_deep_copy) streamlined_obj_vals.append(temp_deep_copy) - elif isinstance(kwargs[key], list) and isinstance(kwargs[key][0], _STIXBase): - for obj in kwargs[key]: - temp_deep_copy = copy.deepcopy(dict(obj)) - _recursive_stix_to_dict(temp_deep_copy) - streamlined_obj_vals.append(temp_deep_copy) + elif isinstance(kwargs[key], list): + temp_deep_copy = copy.deepcopy(kwargs[key]) + _recursive_stix_list_to_dict(temp_deep_copy) + streamlined_obj_vals.append(temp_deep_copy) else: streamlined_obj_vals.append(kwargs[key]) - if streamlined_obj_vals: data = canonicalize(streamlined_obj_vals, utf8=False) @@ -448,5 +446,20 @@ def _recursive_stix_to_dict(input_dict): # There may stil be nested _STIXBase objects _recursive_stix_to_dict(input_dict[key]) + elif isinstance(input_dict[key], list): + _recursive_stix_list_to_dict(input_dict[key]) else: - return + pass + + +def _recursive_stix_list_to_dict(input_list): + for i in range(len(input_list)): + if isinstance(input_list[i], _STIXBase): + input_list[i] = dict(input_list[i]) + elif isinstance(input_list[i], dict): + pass + elif isinstance(input_list[i], list): + _recursive_stix_list_to_dict(input_list[i]) + else: + continue + _recursive_stix_to_dict(input_list[i]) diff --git a/stix2/pattern_visitor.py b/stix2/pattern_visitor.py index b2d7a53..6ac3e98 100644 --- a/stix2/pattern_visitor.py +++ b/stix2/pattern_visitor.py @@ -1,16 +1,12 @@ import importlib import inspect -from antlr4 import CommonTokenStream, InputStream -from antlr4.tree.Trees import Trees -import six from stix2patterns.exceptions import ParseException -from stix2patterns.grammars.STIXPatternLexer import STIXPatternLexer from stix2patterns.grammars.STIXPatternParser import ( STIXPatternParser, TerminalNode, ) from stix2patterns.grammars.STIXPatternVisitor import STIXPatternVisitor -from stix2patterns.validator import STIXPatternErrorListener +from stix2patterns.v20.pattern import Pattern from .patterns import * from .patterns import _BooleanExpression @@ -328,41 +324,9 @@ class STIXPatternVisitorForSTIX2(STIXPatternVisitor): def create_pattern_object(pattern, module_suffix="", module_name=""): """ - Validates a pattern against the STIX Pattern grammar. Error messages are - returned in a list. The test passed if the returned list is empty. + Create a STIX pattern AST from a pattern string. """ - start = '' - if isinstance(pattern, six.string_types): - start = pattern[:2] - pattern = InputStream(pattern) - - if not start: - start = pattern.readline()[:2] - pattern.seek(0) - - parseErrListener = STIXPatternErrorListener() - - lexer = STIXPatternLexer(pattern) - # it always adds a console listener by default... remove it. - lexer.removeErrorListeners() - - stream = CommonTokenStream(lexer) - - parser = STIXPatternParser(stream) - - parser.buildParseTrees = True - # it always adds a console listener by default... remove it. - parser.removeErrorListeners() - parser.addErrorListener(parseErrListener) - - # To improve error messages, replace "<INVALID>" in the literal - # names with symbolic names. This is a hack, but seemed like - # the simplest workaround. - for i, lit_name in enumerate(parser.literalNames): - if lit_name == u"<INVALID>": - parser.literalNames[i] = parser.symbolicNames[i] - - tree = parser.pattern() + pattern_obj = Pattern(pattern) builder = STIXPatternVisitorForSTIX2(module_suffix, module_name) - return builder.visit(tree) + return pattern_obj.visit(builder) diff --git a/stix2/v21/observables.py b/stix2/v21/observables.py index 1703263..ed560a6 100644 --- a/stix2/v21/observables.py +++ b/stix2/v21/observables.py @@ -7,13 +7,10 @@ Observable and do not have a ``_type`` attribute. from collections import OrderedDict import itertools -import warnings from ..base import _Extension, _Observable, _STIXBase from ..custom import _custom_extension_builder, _custom_observable_builder -from ..exceptions import ( - AtLeastOnePropertyError, DependentPropertiesError, STIXDeprecationWarning, -) +from ..exceptions import AtLeastOnePropertyError, DependentPropertiesError from ..properties import ( BinaryProperty, BooleanProperty, DictionaryProperty, EmbeddedObjectProperty, EnumProperty, ExtensionsProperty, FloatProperty, @@ -122,14 +119,6 @@ class DomainName(_Observable): ]) _id_contributing_properties = ["value"] - def _check_object_constraints(self): - if self.get('resolves_to_refs'): - warnings.warn( - "The 'resolves_to_refs' property of domain-name is deprecated in " - "STIX 2.1. Use the 'resolves-to' relationship type instead", - STIXDeprecationWarning, - ) - class EmailAddress(_Observable): # TODO: Add link @@ -421,21 +410,6 @@ class IPv4Address(_Observable): ]) _id_contributing_properties = ["value"] - def _check_object_constraints(self): - if self.get('resolves_to_refs'): - warnings.warn( - "The 'resolves_to_refs' property of ipv4-addr is deprecated in " - "STIX 2.1. Use the 'resolves-to' relationship type instead", - STIXDeprecationWarning, - ) - - if self.get('belongs_to_refs'): - warnings.warn( - "The 'belongs_to_refs' property of ipv4-addr is deprecated in " - "STIX 2.1. Use the 'belongs-to' relationship type instead", - STIXDeprecationWarning, - ) - class IPv6Address(_Observable): # TODO: Add link @@ -458,21 +432,6 @@ class IPv6Address(_Observable): ]) _id_contributing_properties = ["value"] - def _check_object_constraints(self): - if self.get('resolves_to_refs'): - warnings.warn( - "The 'resolves_to_refs' property of ipv6-addr is deprecated in " - "STIX 2.1. Use the 'resolves-to' relationship type instead", - STIXDeprecationWarning, - ) - - if self.get('belongs_to_refs'): - warnings.warn( - "The 'belongs_to_refs' property of ipv6-addr is deprecated in " - "STIX 2.1. Use the 'belongs-to' relationship type instead", - STIXDeprecationWarning, - ) - class MACAddress(_Observable): # TODO: Add link
oasis-open/cti-python-stix2
8aca39a0b037647f055ad11c85e0f289835f9f3d
diff --git a/stix2/test/v21/test_indicator.py b/stix2/test/v21/test_indicator.py index 152f253..23bad29 100644 --- a/stix2/test/v21/test_indicator.py +++ b/stix2/test/v21/test_indicator.py @@ -271,7 +271,7 @@ def test_indicator_stix20_invalid_pattern(): ) assert excinfo.value.cls == stix2.v21.Indicator - assert "FAIL: The same qualifier is used more than once" in str(excinfo.value) + assert "FAIL: Duplicate qualifier type encountered" in str(excinfo.value) ind = stix2.v21.Indicator( type="indicator", diff --git a/stix2/test/v21/test_observed_data.py b/stix2/test/v21/test_observed_data.py index 371018c..71bad46 100644 --- a/stix2/test/v21/test_observed_data.py +++ b/stix2/test/v21/test_observed_data.py @@ -1540,37 +1540,45 @@ def test_deterministic_id_no_contributing_props(): assert uuid_obj_2.version == 4 -def test_ipv4_resolves_to_refs_deprecation(): - with pytest.warns(stix2.exceptions.STIXDeprecationWarning): - - stix2.v21.IPv4Address( - value="26.09.19.70", - resolves_to_refs=["mac-addr--08900593-0265-52fc-93c0-5b4a942f5887"], - ) - - -def test_ipv4_belongs_to_refs_deprecation(): - with pytest.warns(stix2.exceptions.STIXDeprecationWarning): - - stix2.v21.IPv4Address( - value="21.12.19.64", - belongs_to_refs=["autonomous-system--52e0a49d-d683-5801-a7b8-145765a1e116"], - ) - - -def test_ipv6_resolves_to_refs_deprecation(): - with pytest.warns(stix2.exceptions.STIXDeprecationWarning): +def test_id_gen_recursive_dict_conversion_1(): + file_observable = stix2.v21.File( + name="example.exe", + size=68 * 1000, + magic_number_hex="50000000", + hashes={ + "SHA-256": "841a8921140aba50671ebb0770fecc4ee308c4952cfeff8de154ab14eeef4649", + }, + extensions={ + "windows-pebinary-ext": stix2.v21.WindowsPEBinaryExt( + pe_type="exe", + machine_hex="014c", + sections=[ + stix2.v21.WindowsPESection( + name=".data", + size=4096, + entropy=7.980693, + hashes={"SHA-256": "6e3b6f3978e5cd96ba7abee35c24e867b7e64072e2ecb22d0ee7a6e6af6894d0"}, + ), + ], + ), + }, + ) - stix2.v21.IPv6Address( - value="2001:0db8:85a3:0000:0000:8a2e:0370:7334", - resolves_to_refs=["mac-addr--08900593-0265-52fc-93c0-5b4a942f5887"], - ) + assert file_observable.id == "file--5219d93d-13c1-5f1f-896b-039f10ec67ea" -def test_ipv6_belongs_to_refs_deprecation(): - with pytest.warns(stix2.exceptions.STIXDeprecationWarning): +def test_id_gen_recursive_dict_conversion_2(): + wrko = stix2.v21.WindowsRegistryKey( + values=[ + stix2.v21.WindowsRegistryValueType( + name="Foo", + data="qwerty", + ), + stix2.v21.WindowsRegistryValueType( + name="Bar", + data="42", + ), + ], + ) - stix2.v21.IPv6Address( - value="2001:0db8:85a3:0000:0000:8a2e:0370:7334", - belongs_to_refs=["autonomous-system--52e0a49d-d683-5801-a7b8-145765a1e116"], - ) + assert wrko.id == "windows-registry-key--c087d9fe-a03e-5922-a1cd-da116e5b8a7b" diff --git a/stix2/test/v21/test_pattern_expressions.py b/stix2/test/v21/test_pattern_expressions.py index 76880be..0c298f8 100644 --- a/stix2/test/v21/test_pattern_expressions.py +++ b/stix2/test/v21/test_pattern_expressions.py @@ -1,6 +1,7 @@ import datetime import pytest +from stix2patterns.exceptions import ParseException import stix2 from stix2.pattern_visitor import create_pattern_object @@ -515,3 +516,8 @@ def test_list_constant(): def test_parsing_multiple_slashes_quotes(): patt_obj = create_pattern_object("[ file:name = 'weird_name\\'' ]") assert str(patt_obj) == "[file:name = 'weird_name\\'']" + + +def test_parse_error(): + with pytest.raises(ParseException): + create_pattern_object("[ file: name = 'weirdname]")
Incorrect Pattern Error Propagation When using `stix2/pattern_visitor.py/create_pattern_object()` with a pattern that does not include matching single quotes (e.g. "[ file: name = 'weirdname]" ), the stix2 library returns an unhelpful and unclear error. This is in comparison to the more useful error message provided by the pattern validator if the pattern was supplied to it directly. Thus, there should be a way for the error(s) generated by the pattern validator to be propagated back through stix2. See below stacktrace for more details. (Based off of https://github.com/oasis-open/cti-python-stix2/issues/303) ![stacktrace](https://user-images.githubusercontent.com/43383927/73215354-f2b69680-4121-11ea-89ef-8d949202e2ed.png)
0.0
[ "stix2/test/v21/test_observed_data.py::test_id_gen_recursive_dict_conversion_1", "stix2/test/v21/test_observed_data.py::test_id_gen_recursive_dict_conversion_2", "stix2/test/v21/test_pattern_expressions.py::test_parse_error" ]
[ "stix2/test/v21/test_indicator.py::test_indicator_with_all_required_properties", "stix2/test/v21/test_indicator.py::test_indicator_autogenerated_properties", "stix2/test/v21/test_indicator.py::test_indicator_type_must_be_indicator", "stix2/test/v21/test_indicator.py::test_indicator_id_must_start_with_indicator", "stix2/test/v21/test_indicator.py::test_indicator_required_properties", "stix2/test/v21/test_indicator.py::test_indicator_required_property_pattern", "stix2/test/v21/test_indicator.py::test_indicator_created_ref_invalid_format", "stix2/test/v21/test_indicator.py::test_indicator_revoked_invalid", "stix2/test/v21/test_indicator.py::test_cannot_assign_to_indicator_attributes", "stix2/test/v21/test_indicator.py::test_invalid_kwarg_to_indicator", "stix2/test/v21/test_indicator.py::test_created_modified_time_are_identical_by_default", "stix2/test/v21/test_indicator.py::test_parse_indicator[{\\n", "stix2/test/v21/test_indicator.py::test_parse_indicator[data1]", "stix2/test/v21/test_indicator.py::test_invalid_indicator_pattern", "stix2/test/v21/test_indicator.py::test_indicator_with_custom_embedded_objs", "stix2/test/v21/test_indicator.py::test_indicator_with_custom_embed_objs_extra_props_error", "stix2/test/v21/test_indicator.py::test_indicator_stix20_invalid_pattern", "stix2/test/v21/test_observed_data.py::test_observed_data_example", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_refs", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_object_refs", "stix2/test/v21/test_observed_data.py::test_observed_data_object_constraint", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_bad_refs", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_non_dictionary", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_empty_dictionary", "stix2/test/v21/test_observed_data.py::test_parse_observed_data[{\\n", "stix2/test/v21/test_observed_data.py::test_parse_observed_data[data1]", "stix2/test/v21/test_observed_data.py::test_parse_artifact_valid[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_artifact_invalid[\"0\":", "stix2/test/v21/test_observed_data.py::test_artifact_example_dependency_error", "stix2/test/v21/test_observed_data.py::test_parse_autonomous_system_valid[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_email_address[{\\n", "stix2/test/v21/test_observed_data.py::test_parse_email_message[\\n", "stix2/test/v21/test_observed_data.py::test_parse_email_message_not_multipart[\\n", "stix2/test/v21/test_observed_data.py::test_parse_file_archive[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_email_message_with_at_least_one_error[\\n", "stix2/test/v21/test_observed_data.py::test_parse_basic_tcp_traffic[\\n", "stix2/test/v21/test_observed_data.py::test_parse_basic_tcp_traffic_with_error[\\n", "stix2/test/v21/test_observed_data.py::test_observed_data_with_process_example", "stix2/test/v21/test_observed_data.py::test_artifact_example", "stix2/test/v21/test_observed_data.py::test_artifact_mutual_exclusion_error", "stix2/test/v21/test_observed_data.py::test_directory_example", "stix2/test/v21/test_observed_data.py::test_directory_example_ref_error", "stix2/test/v21/test_observed_data.py::test_domain_name_example", "stix2/test/v21/test_observed_data.py::test_domain_name_example_invalid_ref_type", "stix2/test/v21/test_observed_data.py::test_file_example", "stix2/test/v21/test_observed_data.py::test_file_example_with_NTFSExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_empty_NTFSExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_PDFExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_PDFExt_Object", "stix2/test/v21/test_observed_data.py::test_file_example_with_RasterImageExt_Object", "stix2/test/v21/test_observed_data.py::test_raster_image_ext_parse", "stix2/test/v21/test_observed_data.py::test_raster_images_ext_create", "stix2/test/v21/test_observed_data.py::test_file_example_with_WindowsPEBinaryExt", "stix2/test/v21/test_observed_data.py::test_file_example_encryption_error", "stix2/test/v21/test_observed_data.py::test_ipv4_address_example", "stix2/test/v21/test_observed_data.py::test_ipv4_address_valid_refs", "stix2/test/v21/test_observed_data.py::test_ipv4_address_example_cidr", "stix2/test/v21/test_observed_data.py::test_ipv6_address_example", "stix2/test/v21/test_observed_data.py::test_mac_address_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_http_request_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_icmp_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_socket_example", "stix2/test/v21/test_observed_data.py::test_correct_socket_options", "stix2/test/v21/test_observed_data.py::test_incorrect_socket_options", "stix2/test/v21/test_observed_data.py::test_network_traffic_tcp_example", "stix2/test/v21/test_observed_data.py::test_mutex_example", "stix2/test/v21/test_observed_data.py::test_process_example", "stix2/test/v21/test_observed_data.py::test_process_example_empty_error", "stix2/test/v21/test_observed_data.py::test_process_example_empty_with_extensions", "stix2/test/v21/test_observed_data.py::test_process_example_windows_process_ext", "stix2/test/v21/test_observed_data.py::test_process_example_windows_process_ext_empty", "stix2/test/v21/test_observed_data.py::test_process_example_extensions_empty", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsProcessExt_Object", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsServiceExt", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsProcessServiceExt", "stix2/test/v21/test_observed_data.py::test_software_example", "stix2/test/v21/test_observed_data.py::test_url_example", "stix2/test/v21/test_observed_data.py::test_user_account_example", "stix2/test/v21/test_observed_data.py::test_user_account_unix_account_ext_example", "stix2/test/v21/test_observed_data.py::test_windows_registry_key_example", "stix2/test/v21/test_observed_data.py::test_x509_certificate_example", "stix2/test/v21/test_observed_data.py::test_x509_certificate_error", "stix2/test/v21/test_observed_data.py::test_new_version_with_related_objects", "stix2/test/v21/test_observed_data.py::test_objects_deprecation", "stix2/test/v21/test_observed_data.py::test_deterministic_id_same_extra_prop_vals", "stix2/test/v21/test_observed_data.py::test_deterministic_id_diff_extra_prop_vals", "stix2/test/v21/test_observed_data.py::test_deterministic_id_diff_contributing_prop_vals", "stix2/test/v21/test_observed_data.py::test_deterministic_id_no_contributing_props", "stix2/test/v21/test_pattern_expressions.py::test_create_comparison_expression", "stix2/test/v21/test_pattern_expressions.py::test_boolean_expression", "stix2/test/v21/test_pattern_expressions.py::test_boolean_expression_with_parentheses", "stix2/test/v21/test_pattern_expressions.py::test_hash_followed_by_registryKey_expression_python_constant", "stix2/test/v21/test_pattern_expressions.py::test_hash_followed_by_registryKey_expression", "stix2/test/v21/test_pattern_expressions.py::test_file_observable_expression", "stix2/test/v21/test_pattern_expressions.py::test_multiple_file_observable_expression[AndObservationExpression-AND]", "stix2/test/v21/test_pattern_expressions.py::test_multiple_file_observable_expression[OrObservationExpression-OR]", "stix2/test/v21/test_pattern_expressions.py::test_root_types", "stix2/test/v21/test_pattern_expressions.py::test_artifact_payload", "stix2/test/v21/test_pattern_expressions.py::test_greater_than_python_constant", "stix2/test/v21/test_pattern_expressions.py::test_greater_than", "stix2/test/v21/test_pattern_expressions.py::test_less_than", "stix2/test/v21/test_pattern_expressions.py::test_greater_than_or_equal", "stix2/test/v21/test_pattern_expressions.py::test_less_than_or_equal", "stix2/test/v21/test_pattern_expressions.py::test_not", "stix2/test/v21/test_pattern_expressions.py::test_and_observable_expression", "stix2/test/v21/test_pattern_expressions.py::test_invalid_and_observable_expression", "stix2/test/v21/test_pattern_expressions.py::test_hex", "stix2/test/v21/test_pattern_expressions.py::test_multiple_qualifiers", "stix2/test/v21/test_pattern_expressions.py::test_set_op", "stix2/test/v21/test_pattern_expressions.py::test_timestamp", "stix2/test/v21/test_pattern_expressions.py::test_boolean", "stix2/test/v21/test_pattern_expressions.py::test_binary", "stix2/test/v21/test_pattern_expressions.py::test_list", "stix2/test/v21/test_pattern_expressions.py::test_list2", "stix2/test/v21/test_pattern_expressions.py::test_invalid_constant_type", "stix2/test/v21/test_pattern_expressions.py::test_invalid_integer_constant", "stix2/test/v21/test_pattern_expressions.py::test_invalid_timestamp_constant", "stix2/test/v21/test_pattern_expressions.py::test_invalid_float_constant", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[True-True0]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[False-False0]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[True-True1]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[False-False1]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[true-True]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[false-False]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[t-True]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[f-False]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[T-True]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[F-False]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[1-True]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[0-False]", "stix2/test/v21/test_pattern_expressions.py::test_invalid_boolean_constant", "stix2/test/v21/test_pattern_expressions.py::test_invalid_hash_constant[MD5-zzz]", "stix2/test/v21/test_pattern_expressions.py::test_invalid_hash_constant[ssdeep-zzz==]", "stix2/test/v21/test_pattern_expressions.py::test_invalid_hex_constant", "stix2/test/v21/test_pattern_expressions.py::test_invalid_binary_constant", "stix2/test/v21/test_pattern_expressions.py::test_escape_quotes_and_backslashes", "stix2/test/v21/test_pattern_expressions.py::test_like", "stix2/test/v21/test_pattern_expressions.py::test_issuperset", "stix2/test/v21/test_pattern_expressions.py::test_repeat_qualifier", "stix2/test/v21/test_pattern_expressions.py::test_invalid_repeat_qualifier", "stix2/test/v21/test_pattern_expressions.py::test_invalid_within_qualifier", "stix2/test/v21/test_pattern_expressions.py::test_startstop_qualifier", "stix2/test/v21/test_pattern_expressions.py::test_invalid_startstop_qualifier", "stix2/test/v21/test_pattern_expressions.py::test_make_constant_already_a_constant", "stix2/test/v21/test_pattern_expressions.py::test_parsing_comparison_expression", "stix2/test/v21/test_pattern_expressions.py::test_parsing_qualified_expression", "stix2/test/v21/test_pattern_expressions.py::test_list_constant", "stix2/test/v21/test_pattern_expressions.py::test_parsing_multiple_slashes_quotes" ]
2020-02-18 00:50:29+00:00
4,296
oasis-open__cti-python-stix2-348
diff --git a/stix2/base.py b/stix2/base.py index a283902..4248075 100644 --- a/stix2/base.py +++ b/stix2/base.py @@ -388,14 +388,12 @@ class _Observable(_STIXBase): temp_deep_copy = copy.deepcopy(dict(kwargs[key])) _recursive_stix_to_dict(temp_deep_copy) streamlined_obj_vals.append(temp_deep_copy) - elif isinstance(kwargs[key], list) and isinstance(kwargs[key][0], _STIXBase): - for obj in kwargs[key]: - temp_deep_copy = copy.deepcopy(dict(obj)) - _recursive_stix_to_dict(temp_deep_copy) - streamlined_obj_vals.append(temp_deep_copy) + elif isinstance(kwargs[key], list): + temp_deep_copy = copy.deepcopy(kwargs[key]) + _recursive_stix_list_to_dict(temp_deep_copy) + streamlined_obj_vals.append(temp_deep_copy) else: streamlined_obj_vals.append(kwargs[key]) - if streamlined_obj_vals: data = canonicalize(streamlined_obj_vals, utf8=False) @@ -448,5 +446,20 @@ def _recursive_stix_to_dict(input_dict): # There may stil be nested _STIXBase objects _recursive_stix_to_dict(input_dict[key]) + elif isinstance(input_dict[key], list): + _recursive_stix_list_to_dict(input_dict[key]) else: - return + pass + + +def _recursive_stix_list_to_dict(input_list): + for i in range(len(input_list)): + if isinstance(input_list[i], _STIXBase): + input_list[i] = dict(input_list[i]) + elif isinstance(input_list[i], dict): + pass + elif isinstance(input_list[i], list): + _recursive_stix_list_to_dict(input_list[i]) + else: + continue + _recursive_stix_to_dict(input_list[i])
oasis-open/cti-python-stix2
148d672b24552917d1666da379fbb3d7e85e1bc8
diff --git a/stix2/test/v21/test_observed_data.py b/stix2/test/v21/test_observed_data.py index 6f36d88..71bad46 100644 --- a/stix2/test/v21/test_observed_data.py +++ b/stix2/test/v21/test_observed_data.py @@ -1538,3 +1538,47 @@ def test_deterministic_id_no_contributing_props(): uuid_obj_2 = uuid.UUID(email_msg_2.id[-36:]) assert uuid_obj_2.variant == uuid.RFC_4122 assert uuid_obj_2.version == 4 + + +def test_id_gen_recursive_dict_conversion_1(): + file_observable = stix2.v21.File( + name="example.exe", + size=68 * 1000, + magic_number_hex="50000000", + hashes={ + "SHA-256": "841a8921140aba50671ebb0770fecc4ee308c4952cfeff8de154ab14eeef4649", + }, + extensions={ + "windows-pebinary-ext": stix2.v21.WindowsPEBinaryExt( + pe_type="exe", + machine_hex="014c", + sections=[ + stix2.v21.WindowsPESection( + name=".data", + size=4096, + entropy=7.980693, + hashes={"SHA-256": "6e3b6f3978e5cd96ba7abee35c24e867b7e64072e2ecb22d0ee7a6e6af6894d0"}, + ), + ], + ), + }, + ) + + assert file_observable.id == "file--5219d93d-13c1-5f1f-896b-039f10ec67ea" + + +def test_id_gen_recursive_dict_conversion_2(): + wrko = stix2.v21.WindowsRegistryKey( + values=[ + stix2.v21.WindowsRegistryValueType( + name="Foo", + data="qwerty", + ), + stix2.v21.WindowsRegistryValueType( + name="Bar", + data="42", + ), + ], + ) + + assert wrko.id == "windows-registry-key--c087d9fe-a03e-5922-a1cd-da116e5b8a7b"
File SCO with WindowsPEBinary using WindowsPESection causes JSON serialization error Below an example of how to trigger the problem: ``` python from stix2.v21 import observables directory_observable = observables.Directory(path="/home/user-1/") file_observable = observables.File( name="example.exe", parent_directory_ref=directory_observable["id"], size=68 * 1000, magic_number_hex="50000000", hashes={ "SHA-256": "841a8921140aba50671ebb0770fecc4ee308c4952cfeff8de154ab14eeef4649" }, extensions={"windows-pebinary-ext": observables.WindowsPEBinaryExt(pe_type="exe", machine_hex="014c", sections=[observables.WindowsPESection(name=".data", size=4096, entropy=7.980693, hashes={"SHA-256": "6e3b6f3978e5cd96ba7abee35c24e867b7e64072e2ecb22d0ee7a6e6af6894d0"})])} ) print(directory_observable, file_observable) ``` I obtain the following error: ``` Traceback (most recent call last): File "C:/Users/user-1/home/example_project/exe_report.py", line 69, in <module> exe_report() File "C:/Users/user-1/home/example_project/exe_report.py", line 45, in exe_report extensions={"windows-pebinary-ext": observables.WindowsPEBinaryExt(pe_type="exe", machine_hex="014c", sections=[observables.WindowsPESection(name=".data", size=4096, entropy=7.980693, hashes={"SHA-256": "6e3b6f3978e5cd96ba7abee35c24e867b7e64072e2ecb22d0ee7a6e6af6894d0"})])} File "C:\Users\user-1\venv\lib\site-packages\stix2\base.py", line 317, in __init__ possible_id = self._generate_id(kwargs) File "C:\Users\user-1\venv\lib\site-packages\stix2\base.py", line 395, in _generate_id data = canonicalize(streamlined_obj_vals, utf8=False) File "C:\Users\user-1\venv\lib\site-packages\stix2\canonicalization\Canonicalize.py", line 502, in canonicalize textVal = JSONEncoder(sort_keys=True).encode(obj) File "C:\Users\user-1\venv\lib\site-packages\stix2\canonicalization\Canonicalize.py", line 233, in encode chunks = list(chunks) File "C:\Users\user-1\venv\lib\site-packages\stix2\canonicalization\Canonicalize.py", line 478, in _iterencode for thing in _iterencode_list(o, _current_indent_level): File "C:\Users\user-1\venv\lib\site-packages\stix2\canonicalization\Canonicalize.py", line 367, in _iterencode_list for chunk in chunks: File "C:\Users\user-1\venv\lib\site-packages\stix2\canonicalization\Canonicalize.py", line 450, in _iterencode_dict for chunk in chunks: File "C:\Users\user-1\venv\lib\site-packages\stix2\canonicalization\Canonicalize.py", line 450, in _iterencode_dict for chunk in chunks: File "C:\Users\user-1\venv\lib\site-packages\stix2\canonicalization\Canonicalize.py", line 367, in _iterencode_list for chunk in chunks: File "C:\Users\user-1\venv\lib\site-packages\stix2\canonicalization\Canonicalize.py", line 491, in _iterencode o = _default(o) File "C:\Users\user-1\venv\lib\site-packages\stix2\canonicalization\Canonicalize.py", line 211, in default o.__class__.__name__, TypeError: Object of type 'WindowsPESection' is not JSON serializable ```
0.0
[ "stix2/test/v21/test_observed_data.py::test_id_gen_recursive_dict_conversion_1", "stix2/test/v21/test_observed_data.py::test_id_gen_recursive_dict_conversion_2" ]
[ "stix2/test/v21/test_observed_data.py::test_observed_data_example", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_refs", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_object_refs", "stix2/test/v21/test_observed_data.py::test_observed_data_object_constraint", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_bad_refs", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_non_dictionary", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_empty_dictionary", "stix2/test/v21/test_observed_data.py::test_parse_observed_data[{\\n", "stix2/test/v21/test_observed_data.py::test_parse_observed_data[data1]", "stix2/test/v21/test_observed_data.py::test_parse_artifact_valid[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_artifact_invalid[\"0\":", "stix2/test/v21/test_observed_data.py::test_artifact_example_dependency_error", "stix2/test/v21/test_observed_data.py::test_parse_autonomous_system_valid[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_email_address[{\\n", "stix2/test/v21/test_observed_data.py::test_parse_email_message[\\n", "stix2/test/v21/test_observed_data.py::test_parse_email_message_not_multipart[\\n", "stix2/test/v21/test_observed_data.py::test_parse_file_archive[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_email_message_with_at_least_one_error[\\n", "stix2/test/v21/test_observed_data.py::test_parse_basic_tcp_traffic[\\n", "stix2/test/v21/test_observed_data.py::test_parse_basic_tcp_traffic_with_error[\\n", "stix2/test/v21/test_observed_data.py::test_observed_data_with_process_example", "stix2/test/v21/test_observed_data.py::test_artifact_example", "stix2/test/v21/test_observed_data.py::test_artifact_mutual_exclusion_error", "stix2/test/v21/test_observed_data.py::test_directory_example", "stix2/test/v21/test_observed_data.py::test_directory_example_ref_error", "stix2/test/v21/test_observed_data.py::test_domain_name_example", "stix2/test/v21/test_observed_data.py::test_domain_name_example_invalid_ref_type", "stix2/test/v21/test_observed_data.py::test_file_example", "stix2/test/v21/test_observed_data.py::test_file_example_with_NTFSExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_empty_NTFSExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_PDFExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_PDFExt_Object", "stix2/test/v21/test_observed_data.py::test_file_example_with_RasterImageExt_Object", "stix2/test/v21/test_observed_data.py::test_raster_image_ext_parse", "stix2/test/v21/test_observed_data.py::test_raster_images_ext_create", "stix2/test/v21/test_observed_data.py::test_file_example_with_WindowsPEBinaryExt", "stix2/test/v21/test_observed_data.py::test_file_example_encryption_error", "stix2/test/v21/test_observed_data.py::test_ipv4_address_example", "stix2/test/v21/test_observed_data.py::test_ipv4_address_valid_refs", "stix2/test/v21/test_observed_data.py::test_ipv4_address_example_cidr", "stix2/test/v21/test_observed_data.py::test_ipv6_address_example", "stix2/test/v21/test_observed_data.py::test_mac_address_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_http_request_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_icmp_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_socket_example", "stix2/test/v21/test_observed_data.py::test_correct_socket_options", "stix2/test/v21/test_observed_data.py::test_incorrect_socket_options", "stix2/test/v21/test_observed_data.py::test_network_traffic_tcp_example", "stix2/test/v21/test_observed_data.py::test_mutex_example", "stix2/test/v21/test_observed_data.py::test_process_example", "stix2/test/v21/test_observed_data.py::test_process_example_empty_error", "stix2/test/v21/test_observed_data.py::test_process_example_empty_with_extensions", "stix2/test/v21/test_observed_data.py::test_process_example_windows_process_ext", "stix2/test/v21/test_observed_data.py::test_process_example_windows_process_ext_empty", "stix2/test/v21/test_observed_data.py::test_process_example_extensions_empty", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsProcessExt_Object", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsServiceExt", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsProcessServiceExt", "stix2/test/v21/test_observed_data.py::test_software_example", "stix2/test/v21/test_observed_data.py::test_url_example", "stix2/test/v21/test_observed_data.py::test_user_account_example", "stix2/test/v21/test_observed_data.py::test_user_account_unix_account_ext_example", "stix2/test/v21/test_observed_data.py::test_windows_registry_key_example", "stix2/test/v21/test_observed_data.py::test_x509_certificate_example", "stix2/test/v21/test_observed_data.py::test_x509_certificate_error", "stix2/test/v21/test_observed_data.py::test_new_version_with_related_objects", "stix2/test/v21/test_observed_data.py::test_objects_deprecation", "stix2/test/v21/test_observed_data.py::test_deterministic_id_same_extra_prop_vals", "stix2/test/v21/test_observed_data.py::test_deterministic_id_diff_extra_prop_vals", "stix2/test/v21/test_observed_data.py::test_deterministic_id_diff_contributing_prop_vals", "stix2/test/v21/test_observed_data.py::test_deterministic_id_no_contributing_props" ]
2020-02-19 21:29:49+00:00
4,297
oasis-open__cti-python-stix2-354
diff --git a/stix2/custom.py b/stix2/custom.py index a00498b..802fd07 100644 --- a/stix2/custom.py +++ b/stix2/custom.py @@ -53,7 +53,10 @@ def _custom_marking_builder(cls, type, properties, version): return _CustomMarking -def _custom_observable_builder(cls, type, properties, version): +def _custom_observable_builder(cls, type, properties, version, id_contrib_props=None): + if id_contrib_props is None: + id_contrib_props = [] + class _CustomObservable(cls, _Observable): if not re.match(TYPE_REGEX, type): @@ -98,6 +101,8 @@ def _custom_observable_builder(cls, type, properties, version): _type = type _properties = OrderedDict(properties) + if version != '2.0': + _id_contributing_properties = id_contrib_props def __init__(self, **kwargs): _Observable.__init__(self, **kwargs) diff --git a/stix2/v21/observables.py b/stix2/v21/observables.py index ed560a6..e8c1925 100644 --- a/stix2/v21/observables.py +++ b/stix2/v21/observables.py @@ -966,7 +966,7 @@ class X509Certificate(_Observable): self._check_at_least_one_property(att_list) -def CustomObservable(type='x-custom-observable', properties=None): +def CustomObservable(type='x-custom-observable', properties=None, id_contrib_props=None): """Custom STIX Cyber Observable Object type decorator. Example: @@ -987,7 +987,7 @@ def CustomObservable(type='x-custom-observable', properties=None): properties, [('extensions', ExtensionsProperty(spec_version='2.1', enclosing_type=type))], ])) - return _custom_observable_builder(cls, type, _properties, '2.1') + return _custom_observable_builder(cls, type, _properties, '2.1', id_contrib_props) return wrapper
oasis-open/cti-python-stix2
30a59ad77669cda8260640f99d6d8ff3a7574640
diff --git a/stix2/test/v21/test_custom.py b/stix2/test/v21/test_custom.py index 9c650eb..b46288d 100644 --- a/stix2/test/v21/test_custom.py +++ b/stix2/test/v21/test_custom.py @@ -1,3 +1,5 @@ +import uuid + import pytest import stix2 @@ -665,6 +667,76 @@ def test_observed_data_with_custom_observable_object(): assert ob_data.objects['0'].property1 == 'something' +def test_custom_observable_object_det_id_1(): + @stix2.v21.CustomObservable( + 'x-det-id-observable-1', [ + ('property1', stix2.properties.StringProperty(required=True)), + ('property2', stix2.properties.IntegerProperty()), + ], [ + 'property1', + ], + ) + class DetIdObs1(): + pass + + dio_1 = DetIdObs1(property1='I am property1!', property2=42) + dio_2 = DetIdObs1(property1='I am property1!', property2=24) + assert dio_1.property1 == dio_2.property1 == 'I am property1!' + assert dio_1.id == dio_2.id + + uuid_obj = uuid.UUID(dio_1.id[-36:]) + assert uuid_obj.variant == uuid.RFC_4122 + assert uuid_obj.version == 5 + + dio_3 = DetIdObs1(property1='I am property1!', property2=42) + dio_4 = DetIdObs1(property1='I am also property1!', property2=24) + assert dio_3.property1 == 'I am property1!' + assert dio_4.property1 == 'I am also property1!' + assert dio_3.id != dio_4.id + + +def test_custom_observable_object_det_id_2(): + @stix2.v21.CustomObservable( + 'x-det-id-observable-2', [ + ('property1', stix2.properties.StringProperty(required=True)), + ('property2', stix2.properties.IntegerProperty()), + ], [ + 'property1', 'property2', + ], + ) + class DetIdObs2(): + pass + + dio_1 = DetIdObs2(property1='I am property1!', property2=42) + dio_2 = DetIdObs2(property1='I am property1!', property2=42) + assert dio_1.property1 == dio_2.property1 == 'I am property1!' + assert dio_1.property2 == dio_2.property2 == 42 + assert dio_1.id == dio_2.id + + dio_3 = DetIdObs2(property1='I am property1!', property2=42) + dio_4 = DetIdObs2(property1='I am also property1!', property2=42) + assert dio_3.property1 == 'I am property1!' + assert dio_4.property1 == 'I am also property1!' + assert dio_3.property2 == dio_4.property2 == 42 + assert dio_3.id != dio_4.id + + +def test_custom_observable_object_no_id_contrib_props(): + @stix2.v21.CustomObservable( + 'x-det-id-observable-3', [ + ('property1', stix2.properties.StringProperty(required=True)), + ], + ) + class DetIdObs3(): + pass + + dio = DetIdObs3(property1="I am property1!") + + uuid_obj = uuid.UUID(dio.id[-36:]) + assert uuid_obj.variant == uuid.RFC_4122 + assert uuid_obj.version == 4 + + @stix2.v21.CustomExtension( stix2.v21.DomainName, 'x-new-ext', [ ('property1', stix2.properties.StringProperty(required=True)),
Custom SCOs don't support `_id_contributing_properties` When creating custom SCOs, cannot specify the `_id_contributing_properties` property to define which properties should be used for the custom SCOs' deterministic IDs
0.0
[ "stix2/test/v21/test_custom.py::test_custom_observable_object_det_id_1", "stix2/test/v21/test_custom.py::test_custom_observable_object_det_id_2" ]
[ "stix2/test/v21/test_custom.py::test_identity_custom_property", "stix2/test/v21/test_custom.py::test_identity_custom_property_invalid", "stix2/test/v21/test_custom.py::test_identity_custom_property_allowed", "stix2/test/v21/test_custom.py::test_parse_identity_custom_property[{\\n", "stix2/test/v21/test_custom.py::test_custom_property_object_in_bundled_object", "stix2/test/v21/test_custom.py::test_custom_properties_object_in_bundled_object", "stix2/test/v21/test_custom.py::test_custom_property_dict_in_bundled_object", "stix2/test/v21/test_custom.py::test_custom_properties_dict_in_bundled_object", "stix2/test/v21/test_custom.py::test_custom_property_in_observed_data", "stix2/test/v21/test_custom.py::test_custom_property_object_in_observable_extension", "stix2/test/v21/test_custom.py::test_custom_property_dict_in_observable_extension", "stix2/test/v21/test_custom.py::test_identity_custom_property_revoke", "stix2/test/v21/test_custom.py::test_identity_custom_property_edit_markings", "stix2/test/v21/test_custom.py::test_custom_marking_no_init_1", "stix2/test/v21/test_custom.py::test_custom_marking_no_init_2", "stix2/test/v21/test_custom.py::test_custom_object_raises_exception", "stix2/test/v21/test_custom.py::test_custom_object_type", "stix2/test/v21/test_custom.py::test_custom_object_no_init_1", "stix2/test/v21/test_custom.py::test_custom_object_no_init_2", "stix2/test/v21/test_custom.py::test_custom_object_invalid_type_name", "stix2/test/v21/test_custom.py::test_parse_custom_object_type", "stix2/test/v21/test_custom.py::test_parse_unregistered_custom_object_type", "stix2/test/v21/test_custom.py::test_parse_unregistered_custom_object_type_w_allow_custom", "stix2/test/v21/test_custom.py::test_custom_observable_object_1", "stix2/test/v21/test_custom.py::test_custom_observable_object_2", "stix2/test/v21/test_custom.py::test_custom_observable_object_3", "stix2/test/v21/test_custom.py::test_custom_observable_raises_exception", "stix2/test/v21/test_custom.py::test_custom_observable_object_no_init_1", "stix2/test/v21/test_custom.py::test_custom_observable_object_no_init_2", "stix2/test/v21/test_custom.py::test_custom_observable_object_invalid_type_name", "stix2/test/v21/test_custom.py::test_custom_observable_object_invalid_ref_property", "stix2/test/v21/test_custom.py::test_custom_observable_object_invalid_refs_property", "stix2/test/v21/test_custom.py::test_custom_observable_object_invalid_refs_list_property", "stix2/test/v21/test_custom.py::test_custom_no_properties_raises_exception", "stix2/test/v21/test_custom.py::test_custom_wrong_properties_arg_raises_exception", "stix2/test/v21/test_custom.py::test_parse_custom_observable_object", "stix2/test/v21/test_custom.py::test_parse_unregistered_custom_observable_object", "stix2/test/v21/test_custom.py::test_parse_unregistered_custom_observable_object_with_no_type", "stix2/test/v21/test_custom.py::test_parse_observed_data_with_custom_observable", "stix2/test/v21/test_custom.py::test_parse_invalid_custom_observable_object", "stix2/test/v21/test_custom.py::test_observable_custom_property", "stix2/test/v21/test_custom.py::test_observable_custom_property_invalid", "stix2/test/v21/test_custom.py::test_observable_custom_property_allowed", "stix2/test/v21/test_custom.py::test_observed_data_with_custom_observable_object", "stix2/test/v21/test_custom.py::test_custom_observable_object_no_id_contrib_props", "stix2/test/v21/test_custom.py::test_custom_extension_raises_exception", "stix2/test/v21/test_custom.py::test_custom_extension", "stix2/test/v21/test_custom.py::test_custom_extension_wrong_observable_type", "stix2/test/v21/test_custom.py::test_custom_extension_with_list_and_dict_properties_observable_type[{\\n", "stix2/test/v21/test_custom.py::test_custom_extension_invalid_observable", "stix2/test/v21/test_custom.py::test_custom_extension_invalid_type_name", "stix2/test/v21/test_custom.py::test_custom_extension_no_properties", "stix2/test/v21/test_custom.py::test_custom_extension_empty_properties", "stix2/test/v21/test_custom.py::test_custom_extension_dict_properties", "stix2/test/v21/test_custom.py::test_custom_extension_no_init_1", "stix2/test/v21/test_custom.py::test_custom_extension_no_init_2", "stix2/test/v21/test_custom.py::test_parse_observable_with_custom_extension", "stix2/test/v21/test_custom.py::test_custom_and_spec_extension_mix", "stix2/test/v21/test_custom.py::test_parse_observable_with_unregistered_custom_extension[{\\n", "stix2/test/v21/test_custom.py::test_register_custom_object", "stix2/test/v21/test_custom.py::test_extension_property_location", "stix2/test/v21/test_custom.py::test_custom_object_nested_dictionary[{\\n" ]
2020-02-25 02:13:07+00:00
4,298
oasis-open__cti-python-stix2-360
diff --git a/CHANGELOG b/CHANGELOG index b764735..dc0d91e 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,6 +1,19 @@ CHANGELOG ========= +1.3.1 - 2020-03-06 + +* #322 Adds encoding option FileSystemSource and MemorySource +* #354 Adds ability to specify id-contributing properties on custom SCOs +* #346 Certain SCO properties are no longer deprecated +* #327 Fixes missing 'name' property on Marking Definitions +* #303 Fixes bug with escaping quotes in patterns +* #331 Fixes crashing bug of property names that conflict with Mapping methods +* #337 Fixes bug with detecting STIX version of content when parsing +* #342, #343 Fixes bug when adding SCOs to Memory or FileSystem Stores +* #348 Fixes bug with generating deterministic IDs for SCOs +* #344 Fixes bug with propagating errors from the pattern validator + 1.3.0 - 2020-01-04 * #305 Updates support of STIX 2.1 to WD06 diff --git a/setup.cfg b/setup.cfg index 659a1cd..7e89c66 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 1.3.0 +current_version = 1.3.1 commit = True tag = True diff --git a/stix2/v21/common.py b/stix2/v21/common.py index cf3a3b3..ac8daf1 100644 --- a/stix2/v21/common.py +++ b/stix2/v21/common.py @@ -4,6 +4,7 @@ from collections import OrderedDict from ..base import _STIXBase from ..custom import _custom_marking_builder +from ..exceptions import InvalidValueError from ..markings import _MarkingsMixin from ..markings.utils import check_tlp_marking from ..properties import ( @@ -28,10 +29,26 @@ class ExternalReference(_STIXBase): ('external_id', StringProperty()), ]) + # This is hash-algorithm-ov + _LEGAL_HASHES = { + "MD5", "SHA-1", "SHA-256", "SHA-512", "SHA3-256", "SHA3-512", "SSDEEP", + "TLSH", + } + def _check_object_constraints(self): super(ExternalReference, self)._check_object_constraints() self._check_at_least_one_property(['description', 'external_id', 'url']) + if "hashes" in self: + if any( + hash_ not in self._LEGAL_HASHES + for hash_ in self["hashes"] + ): + raise InvalidValueError( + ExternalReference, "hashes", + "Hash algorithm names must be members of hash-algorithm-ov", + ) + class KillChainPhase(_STIXBase): # TODO: Add link diff --git a/stix2/v21/observables.py b/stix2/v21/observables.py index e8c1925..622e933 100644 --- a/stix2/v21/observables.py +++ b/stix2/v21/observables.py @@ -760,6 +760,7 @@ class Software(_Observable): ('id', IDProperty(_type, spec_version='2.1')), ('name', StringProperty(required=True)), ('cpe', StringProperty()), + ('swid', StringProperty()), ('languages', ListProperty(StringProperty)), ('vendor', StringProperty()), ('version', StringProperty()), diff --git a/stix2/v21/sdo.py b/stix2/v21/sdo.py index 1d97261..c0bdf30 100644 --- a/stix2/v21/sdo.py +++ b/stix2/v21/sdo.py @@ -173,7 +173,7 @@ class Identity(STIXDomainObject): ('name', StringProperty(required=True)), ('description', StringProperty()), ('roles', ListProperty(StringProperty)), - ('identity_class', StringProperty(required=True)), + ('identity_class', StringProperty()), ('sectors', ListProperty(StringProperty)), ('contact_information', StringProperty()), ('revoked', BooleanProperty(default=lambda: False)), @@ -202,7 +202,7 @@ class Indicator(STIXDomainObject): ('modified', TimestampProperty(default=lambda: NOW, precision='millisecond')), ('name', StringProperty()), ('description', StringProperty()), - ('indicator_types', ListProperty(StringProperty, required=True)), + ('indicator_types', ListProperty(StringProperty)), ('pattern', PatternProperty(required=True)), ('pattern_type', StringProperty(required=True)), ('pattern_version', StringProperty()), @@ -269,7 +269,7 @@ class Infrastructure(STIXDomainObject): ('granular_markings', ListProperty(GranularMarking)), ('name', StringProperty(required=True)), ('description', StringProperty()), - ('infrastructure_types', ListProperty(StringProperty, required=True)), + ('infrastructure_types', ListProperty(StringProperty)), ('aliases', ListProperty(StringProperty)), ('kill_chain_phases', ListProperty(KillChainPhase)), ('first_seen', TimestampProperty()), @@ -454,7 +454,7 @@ class Malware(STIXDomainObject): ('modified', TimestampProperty(default=lambda: NOW, precision='millisecond')), ('name', StringProperty()), ('description', StringProperty()), - ('malware_types', ListProperty(StringProperty, required=True)), + ('malware_types', ListProperty(StringProperty)), ('is_family', BooleanProperty(required=True)), ('aliases', ListProperty(StringProperty)), ('kill_chain_phases', ListProperty(KillChainPhase)), @@ -524,14 +524,16 @@ class MalwareAnalysis(STIXDomainObject): ('submitted', TimestampProperty()), ('analysis_started', TimestampProperty()), ('analysis_ended', TimestampProperty()), - ('av_result', StringProperty()), + ('result_name', StringProperty()), + ('result', StringProperty()), ('analysis_sco_refs', ListProperty(ReferenceProperty(valid_types="SCO", spec_version='2.1'))), + ('sample_ref', ReferenceProperty(valid_types="SCO", spec_version="2.1")), ]) def _check_object_constraints(self): super(MalwareAnalysis, self)._check_object_constraints() - self._check_at_least_one_property(["av_result", "analysis_sco_refs"]) + self._check_at_least_one_property(["result", "analysis_sco_refs"]) class Note(STIXDomainObject): @@ -672,7 +674,7 @@ class Report(STIXDomainObject): ('modified', TimestampProperty(default=lambda: NOW, precision='millisecond')), ('name', StringProperty(required=True)), ('description', StringProperty()), - ('report_types', ListProperty(StringProperty, required=True)), + ('report_types', ListProperty(StringProperty)), ('published', TimestampProperty(required=True)), ('object_refs', ListProperty(ReferenceProperty(valid_types=["SCO", "SDO", "SRO"], spec_version='2.1'), required=True)), ('revoked', BooleanProperty(default=lambda: False)), @@ -701,7 +703,7 @@ class ThreatActor(STIXDomainObject): ('modified', TimestampProperty(default=lambda: NOW, precision='millisecond')), ('name', StringProperty(required=True)), ('description', StringProperty()), - ('threat_actor_types', ListProperty(StringProperty, required=True)), + ('threat_actor_types', ListProperty(StringProperty)), ('aliases', ListProperty(StringProperty)), ('first_seen', TimestampProperty()), ('last_seen', TimestampProperty()), @@ -748,7 +750,7 @@ class Tool(STIXDomainObject): ('modified', TimestampProperty(default=lambda: NOW, precision='millisecond')), ('name', StringProperty(required=True)), ('description', StringProperty()), - ('tool_types', ListProperty(StringProperty, required=True)), + ('tool_types', ListProperty(StringProperty)), ('aliases', ListProperty(StringProperty)), ('kill_chain_phases', ListProperty(KillChainPhase)), ('tool_version', StringProperty()), diff --git a/stix2/version.py b/stix2/version.py index 67bc602..9c73af2 100644 --- a/stix2/version.py +++ b/stix2/version.py @@ -1,1 +1,1 @@ -__version__ = "1.3.0" +__version__ = "1.3.1"
oasis-open/cti-python-stix2
3803e4bdd7877af8e11211f42261f324b2c92255
diff --git a/stix2/test/v21/test_external_reference.py b/stix2/test/v21/test_external_reference.py index d192a11..f347191 100644 --- a/stix2/test/v21/test_external_reference.py +++ b/stix2/test/v21/test_external_reference.py @@ -120,3 +120,14 @@ def test_external_reference_source_required(): assert excinfo.value.cls == stix2.v21.ExternalReference assert excinfo.value.properties == ["source_name"] + + +def test_external_reference_bad_hash(): + with pytest.raises(stix2.exceptions.InvalidValueError): + stix2.v21.ExternalReference( + source_name="ACME Threat Intel", + description="Threat report", + hashes={ + "SHA-123": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + }, + ) diff --git a/stix2/test/v21/test_indicator.py b/stix2/test/v21/test_indicator.py index d7d7e47..76fe86b 100644 --- a/stix2/test/v21/test_indicator.py +++ b/stix2/test/v21/test_indicator.py @@ -14,9 +14,6 @@ EXPECTED_INDICATOR = """{ "id": "indicator--a740531e-63ff-4e49-a9e1-a0a3eed0e3e7", "created": "2017-01-01T00:00:01.000Z", "modified": "2017-01-01T00:00:01.000Z", - "indicator_types": [ - "malicious-activity" - ], "pattern": "[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']", "pattern_type": "stix", "pattern_version": "2.1", @@ -29,7 +26,6 @@ EXPECTED_INDICATOR_REPR = "Indicator(" + " ".join(""" id='indicator--a740531e-63ff-4e49-a9e1-a0a3eed0e3e7', created='2017-01-01T00:00:01.000Z', modified='2017-01-01T00:00:01.000Z', - indicator_types=['malicious-activity'], pattern="[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']", pattern_type='stix', pattern_version='2.1', @@ -49,7 +45,6 @@ def test_indicator_with_all_required_properties(): pattern="[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']", pattern_type="stix", valid_from=epoch, - indicator_types=['malicious-activity'], ) assert ind.revoked is False @@ -103,8 +98,8 @@ def test_indicator_required_properties(): stix2.v21.Indicator() assert excinfo.value.cls == stix2.v21.Indicator - assert excinfo.value.properties == ["indicator_types", "pattern", "pattern_type", "valid_from"] - assert str(excinfo.value) == "No values for required properties for Indicator: (indicator_types, pattern, pattern_type, valid_from)." + assert excinfo.value.properties == ["pattern", "pattern_type", "valid_from"] + assert str(excinfo.value) == "No values for required properties for Indicator: (pattern, pattern_type, valid_from)." def test_indicator_required_property_pattern(): @@ -163,9 +158,6 @@ def test_created_modified_time_are_identical_by_default(): "id": INDICATOR_ID, "created": "2017-01-01T00:00:01Z", "modified": "2017-01-01T00:00:01Z", - "indicator_types": [ - "malicious-activity", - ], "pattern": "[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']", "pattern_type": "stix", "valid_from": "1970-01-01T00:00:01Z", @@ -181,7 +173,6 @@ def test_parse_indicator(data): assert idctr.created == dt.datetime(2017, 1, 1, 0, 0, 1, tzinfo=pytz.utc) assert idctr.modified == dt.datetime(2017, 1, 1, 0, 0, 1, tzinfo=pytz.utc) assert idctr.valid_from == dt.datetime(1970, 1, 1, 0, 0, 1, tzinfo=pytz.utc) - assert idctr.indicator_types[0] == "malicious-activity" assert idctr.pattern == "[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']" diff --git a/stix2/test/v21/test_infrastructure.py b/stix2/test/v21/test_infrastructure.py index 30632bb..3e9feb7 100644 --- a/stix2/test/v21/test_infrastructure.py +++ b/stix2/test/v21/test_infrastructure.py @@ -13,10 +13,7 @@ EXPECTED_INFRASTRUCTURE = """{ "id": "infrastructure--3000ae1b-784c-f03d-8abc-0a625b2ff018", "created": "2017-01-01T12:34:56.000Z", "modified": "2017-01-01T12:34:56.000Z", - "name": "Poison Ivy C2", - "infrastructure_types": [ - "command-and-control" - ] + "name": "Poison Ivy C2" }""" @@ -29,7 +26,6 @@ def test_infrastructure_with_all_required_properties(): created=now, modified=now, name="Poison Ivy C2", - infrastructure_types=["command-and-control"], ) assert str(infra) == EXPECTED_INFRASTRUCTURE @@ -76,7 +72,7 @@ def test_infrastructure_required_properties(): stix2.v21.Infrastructure() assert excinfo.value.cls == stix2.v21.Infrastructure - assert excinfo.value.properties == ["infrastructure_types", "name"] + assert excinfo.value.properties == ["name"] def test_infrastructure_required_property_name(): @@ -105,7 +101,6 @@ def test_invalid_kwarg_to_infrastructure(): "id": INFRASTRUCTURE_ID, "created": "2017-01-01T12:34:56.000Z", "modified": "2017-01-01T12:34:56.000Z", - "infrastructure_types": ["command-and-control"], "name": "Poison Ivy C2", }, ], @@ -118,7 +113,6 @@ def test_parse_infrastructure(data): assert infra.id == INFRASTRUCTURE_ID assert infra.created == dt.datetime(2017, 1, 1, 12, 34, 56, tzinfo=pytz.utc) assert infra.modified == dt.datetime(2017, 1, 1, 12, 34, 56, tzinfo=pytz.utc) - assert infra.infrastructure_types == ['command-and-control'] assert infra.name == 'Poison Ivy C2' diff --git a/stix2/test/v21/test_malware.py b/stix2/test/v21/test_malware.py index 53838c9..a9158cf 100644 --- a/stix2/test/v21/test_malware.py +++ b/stix2/test/v21/test_malware.py @@ -1,5 +1,5 @@ import datetime as dt -import re +import json import pytest import pytz @@ -16,9 +16,6 @@ EXPECTED_MALWARE = """{ "created": "2016-05-12T08:17:27.000Z", "modified": "2016-05-12T08:17:27.000Z", "name": "Cryptolocker", - "malware_types": [ - "ransomware" - ], "is_family": false }""" @@ -31,7 +28,6 @@ def test_malware_with_all_required_properties(): id=MALWARE_ID, created=now, modified=now, - malware_types=["ransomware"], name="Cryptolocker", is_family=False, ) @@ -80,7 +76,7 @@ def test_malware_required_properties(): stix2.v21.Malware() assert excinfo.value.cls == stix2.v21.Malware - assert excinfo.value.properties == ["is_family", "malware_types"] + assert excinfo.value.properties == ["is_family"] def test_malware_required_property_name(): @@ -116,7 +112,6 @@ def test_invalid_kwarg_to_malware(): "id": MALWARE_ID, "created": "2016-05-12T08:17:27.000Z", "modified": "2016-05-12T08:17:27.000Z", - "malware_types": ["ransomware"], "name": "Cryptolocker", "is_family": False, }, @@ -130,13 +125,14 @@ def test_parse_malware(data): assert mal.id == MALWARE_ID assert mal.created == dt.datetime(2016, 5, 12, 8, 17, 27, tzinfo=pytz.utc) assert mal.modified == dt.datetime(2016, 5, 12, 8, 17, 27, tzinfo=pytz.utc) - assert mal.malware_types == ['ransomware'] assert mal.name == 'Cryptolocker' assert not mal.is_family -def test_parse_malware_invalid_labels(): - data = re.compile('\\[.+\\]', re.DOTALL).sub('1', EXPECTED_MALWARE) +def test_parse_malware_invalid_types(): + data = json.loads(EXPECTED_MALWARE) + data["malware_types"] = 1 # Oops, not a list + data = json.dumps(data) with pytest.raises(InvalidValueError) as excinfo: stix2.parse(data) assert "Invalid value for Malware 'malware_types'" in str(excinfo.value) diff --git a/stix2/test/v21/test_malware_analysis.py b/stix2/test/v21/test_malware_analysis.py index bfb4ff4..22f4171 100644 --- a/stix2/test/v21/test_malware_analysis.py +++ b/stix2/test/v21/test_malware_analysis.py @@ -34,11 +34,13 @@ MALWARE_ANALYSIS_JSON = """{ "submitted": "2018-11-23T06:45:55.747Z", "analysis_started": "2018-11-29T07:30:03.895Z", "analysis_ended": "2018-11-29T08:30:03.895Z", - "av_result": "malicious", + "result_name": "MegaRansom", + "result": "malicious", "analysis_sco_refs": [ "file--fc27e371-6c88-4c5c-868a-4dda0e60b167", "url--6f7a74cd-8eb2-4b88-a4da-aa878e50ac2e" - ] + ], + "sample_ref": "email-addr--499a32d7-74c1-4276-ace9-725ac933e243" }""" diff --git a/stix2/test/v21/test_observed_data.py b/stix2/test/v21/test_observed_data.py index 71bad46..abcbb7b 100644 --- a/stix2/test/v21/test_observed_data.py +++ b/stix2/test/v21/test_observed_data.py @@ -1300,6 +1300,7 @@ def test_software_example(): s = stix2.v21.Software( name="Word", cpe="cpe:2.3:a:microsoft:word:2000:*:*:*:*:*:*:*", + swid="com.acme.rms-ce-v4-1-5-0", version="2002", vendor="Microsoft", )
Enforce hash keys in 2.1 external-references Came out of https://github.com/oasis-tcs/cti-stix2/issues/192
0.0
[ "stix2/test/v21/test_external_reference.py::test_external_reference_bad_hash", "stix2/test/v21/test_indicator.py::test_indicator_with_all_required_properties", "stix2/test/v21/test_indicator.py::test_indicator_required_properties", "stix2/test/v21/test_indicator.py::test_parse_indicator[{\\n", "stix2/test/v21/test_indicator.py::test_parse_indicator[data1]", "stix2/test/v21/test_infrastructure.py::test_infrastructure_with_all_required_properties", "stix2/test/v21/test_infrastructure.py::test_infrastructure_required_properties", "stix2/test/v21/test_infrastructure.py::test_parse_infrastructure[{\\n", "stix2/test/v21/test_infrastructure.py::test_parse_infrastructure[data1]", "stix2/test/v21/test_infrastructure.py::test_parse_infrastructure_kill_chain_phases", "stix2/test/v21/test_infrastructure.py::test_parse_infrastructure_clean_kill_chain_phases", "stix2/test/v21/test_malware.py::test_malware_with_all_required_properties", "stix2/test/v21/test_malware.py::test_malware_required_properties", "stix2/test/v21/test_malware.py::test_parse_malware[{\\n", "stix2/test/v21/test_malware.py::test_parse_malware[data1]", "stix2/test/v21/test_malware.py::test_parse_malware_kill_chain_phases", "stix2/test/v21/test_malware.py::test_parse_malware_clean_kill_chain_phases", "stix2/test/v21/test_malware_analysis.py::test_malware_analysis_example", "stix2/test/v21/test_malware_analysis.py::test_parse_malware_analysis[{\\n", "stix2/test/v21/test_malware_analysis.py::test_parse_malware_analysis[data1]", "stix2/test/v21/test_observed_data.py::test_software_example" ]
[ "stix2/test/v21/test_external_reference.py::test_external_reference_veris", "stix2/test/v21/test_external_reference.py::test_external_reference_capec", "stix2/test/v21/test_external_reference.py::test_external_reference_capec_url", "stix2/test/v21/test_external_reference.py::test_external_reference_threat_report", "stix2/test/v21/test_external_reference.py::test_external_reference_bugzilla", "stix2/test/v21/test_external_reference.py::test_external_reference_offline", "stix2/test/v21/test_external_reference.py::test_external_reference_source_required", "stix2/test/v21/test_indicator.py::test_indicator_autogenerated_properties", "stix2/test/v21/test_indicator.py::test_indicator_type_must_be_indicator", "stix2/test/v21/test_indicator.py::test_indicator_id_must_start_with_indicator", "stix2/test/v21/test_indicator.py::test_indicator_required_property_pattern", "stix2/test/v21/test_indicator.py::test_indicator_created_ref_invalid_format", "stix2/test/v21/test_indicator.py::test_indicator_revoked_invalid", "stix2/test/v21/test_indicator.py::test_cannot_assign_to_indicator_attributes", "stix2/test/v21/test_indicator.py::test_invalid_kwarg_to_indicator", "stix2/test/v21/test_indicator.py::test_created_modified_time_are_identical_by_default", "stix2/test/v21/test_indicator.py::test_invalid_indicator_pattern", "stix2/test/v21/test_indicator.py::test_indicator_with_custom_embedded_objs", "stix2/test/v21/test_indicator.py::test_indicator_with_custom_embed_objs_extra_props_error", "stix2/test/v21/test_indicator.py::test_indicator_stix20_invalid_pattern", "stix2/test/v21/test_infrastructure.py::test_infrastructure_autogenerated_properties", "stix2/test/v21/test_infrastructure.py::test_infrastructure_type_must_be_infrastructure", "stix2/test/v21/test_infrastructure.py::test_infrastructure_id_must_start_with_infrastructure", "stix2/test/v21/test_infrastructure.py::test_infrastructure_required_property_name", "stix2/test/v21/test_infrastructure.py::test_invalid_kwarg_to_infrastructure", "stix2/test/v21/test_infrastructure.py::test_infrastructure_invalid_last_before_first", "stix2/test/v21/test_malware.py::test_malware_autogenerated_properties", "stix2/test/v21/test_malware.py::test_malware_type_must_be_malware", "stix2/test/v21/test_malware.py::test_malware_id_must_start_with_malware", "stix2/test/v21/test_malware.py::test_malware_required_property_name", "stix2/test/v21/test_malware.py::test_cannot_assign_to_malware_attributes", "stix2/test/v21/test_malware.py::test_invalid_kwarg_to_malware", "stix2/test/v21/test_malware.py::test_parse_malware_invalid_types", "stix2/test/v21/test_malware.py::test_malware_invalid_last_before_first", "stix2/test/v21/test_malware.py::test_malware_family_no_name", "stix2/test/v21/test_malware.py::test_malware_non_family_no_name", "stix2/test/v21/test_malware_analysis.py::test_malware_analysis_constraint", "stix2/test/v21/test_observed_data.py::test_observed_data_example", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_refs", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_object_refs", "stix2/test/v21/test_observed_data.py::test_observed_data_object_constraint", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_bad_refs", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_non_dictionary", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_empty_dictionary", "stix2/test/v21/test_observed_data.py::test_parse_observed_data[{\\n", "stix2/test/v21/test_observed_data.py::test_parse_observed_data[data1]", "stix2/test/v21/test_observed_data.py::test_parse_artifact_valid[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_artifact_invalid[\"0\":", "stix2/test/v21/test_observed_data.py::test_artifact_example_dependency_error", "stix2/test/v21/test_observed_data.py::test_parse_autonomous_system_valid[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_email_address[{\\n", "stix2/test/v21/test_observed_data.py::test_parse_email_message[\\n", "stix2/test/v21/test_observed_data.py::test_parse_email_message_not_multipart[\\n", "stix2/test/v21/test_observed_data.py::test_parse_file_archive[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_email_message_with_at_least_one_error[\\n", "stix2/test/v21/test_observed_data.py::test_parse_basic_tcp_traffic[\\n", "stix2/test/v21/test_observed_data.py::test_parse_basic_tcp_traffic_with_error[\\n", "stix2/test/v21/test_observed_data.py::test_observed_data_with_process_example", "stix2/test/v21/test_observed_data.py::test_artifact_example", "stix2/test/v21/test_observed_data.py::test_artifact_mutual_exclusion_error", "stix2/test/v21/test_observed_data.py::test_directory_example", "stix2/test/v21/test_observed_data.py::test_directory_example_ref_error", "stix2/test/v21/test_observed_data.py::test_domain_name_example", "stix2/test/v21/test_observed_data.py::test_domain_name_example_invalid_ref_type", "stix2/test/v21/test_observed_data.py::test_file_example", "stix2/test/v21/test_observed_data.py::test_file_example_with_NTFSExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_empty_NTFSExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_PDFExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_PDFExt_Object", "stix2/test/v21/test_observed_data.py::test_file_example_with_RasterImageExt_Object", "stix2/test/v21/test_observed_data.py::test_raster_image_ext_parse", "stix2/test/v21/test_observed_data.py::test_raster_images_ext_create", "stix2/test/v21/test_observed_data.py::test_file_example_with_WindowsPEBinaryExt", "stix2/test/v21/test_observed_data.py::test_file_example_encryption_error", "stix2/test/v21/test_observed_data.py::test_ipv4_address_example", "stix2/test/v21/test_observed_data.py::test_ipv4_address_valid_refs", "stix2/test/v21/test_observed_data.py::test_ipv4_address_example_cidr", "stix2/test/v21/test_observed_data.py::test_ipv6_address_example", "stix2/test/v21/test_observed_data.py::test_mac_address_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_http_request_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_icmp_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_socket_example", "stix2/test/v21/test_observed_data.py::test_correct_socket_options", "stix2/test/v21/test_observed_data.py::test_incorrect_socket_options", "stix2/test/v21/test_observed_data.py::test_network_traffic_tcp_example", "stix2/test/v21/test_observed_data.py::test_mutex_example", "stix2/test/v21/test_observed_data.py::test_process_example", "stix2/test/v21/test_observed_data.py::test_process_example_empty_error", "stix2/test/v21/test_observed_data.py::test_process_example_empty_with_extensions", "stix2/test/v21/test_observed_data.py::test_process_example_windows_process_ext", "stix2/test/v21/test_observed_data.py::test_process_example_windows_process_ext_empty", "stix2/test/v21/test_observed_data.py::test_process_example_extensions_empty", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsProcessExt_Object", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsServiceExt", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsProcessServiceExt", "stix2/test/v21/test_observed_data.py::test_url_example", "stix2/test/v21/test_observed_data.py::test_user_account_example", "stix2/test/v21/test_observed_data.py::test_user_account_unix_account_ext_example", "stix2/test/v21/test_observed_data.py::test_windows_registry_key_example", "stix2/test/v21/test_observed_data.py::test_x509_certificate_example", "stix2/test/v21/test_observed_data.py::test_x509_certificate_error", "stix2/test/v21/test_observed_data.py::test_new_version_with_related_objects", "stix2/test/v21/test_observed_data.py::test_objects_deprecation", "stix2/test/v21/test_observed_data.py::test_deterministic_id_same_extra_prop_vals", "stix2/test/v21/test_observed_data.py::test_deterministic_id_diff_extra_prop_vals", "stix2/test/v21/test_observed_data.py::test_deterministic_id_diff_contributing_prop_vals", "stix2/test/v21/test_observed_data.py::test_deterministic_id_no_contributing_props", "stix2/test/v21/test_observed_data.py::test_id_gen_recursive_dict_conversion_1", "stix2/test/v21/test_observed_data.py::test_id_gen_recursive_dict_conversion_2" ]
2020-03-05 22:49:48+00:00
4,299
oasis-open__cti-python-stix2-369
diff --git a/stix2/v21/common.py b/stix2/v21/common.py index cf3a3b3..ac8daf1 100644 --- a/stix2/v21/common.py +++ b/stix2/v21/common.py @@ -4,6 +4,7 @@ from collections import OrderedDict from ..base import _STIXBase from ..custom import _custom_marking_builder +from ..exceptions import InvalidValueError from ..markings import _MarkingsMixin from ..markings.utils import check_tlp_marking from ..properties import ( @@ -28,10 +29,26 @@ class ExternalReference(_STIXBase): ('external_id', StringProperty()), ]) + # This is hash-algorithm-ov + _LEGAL_HASHES = { + "MD5", "SHA-1", "SHA-256", "SHA-512", "SHA3-256", "SHA3-512", "SSDEEP", + "TLSH", + } + def _check_object_constraints(self): super(ExternalReference, self)._check_object_constraints() self._check_at_least_one_property(['description', 'external_id', 'url']) + if "hashes" in self: + if any( + hash_ not in self._LEGAL_HASHES + for hash_ in self["hashes"] + ): + raise InvalidValueError( + ExternalReference, "hashes", + "Hash algorithm names must be members of hash-algorithm-ov", + ) + class KillChainPhase(_STIXBase): # TODO: Add link diff --git a/stix2/v21/observables.py b/stix2/v21/observables.py index e8c1925..622e933 100644 --- a/stix2/v21/observables.py +++ b/stix2/v21/observables.py @@ -760,6 +760,7 @@ class Software(_Observable): ('id', IDProperty(_type, spec_version='2.1')), ('name', StringProperty(required=True)), ('cpe', StringProperty()), + ('swid', StringProperty()), ('languages', ListProperty(StringProperty)), ('vendor', StringProperty()), ('version', StringProperty()), diff --git a/stix2/v21/sdo.py b/stix2/v21/sdo.py index 1d97261..a431b42 100644 --- a/stix2/v21/sdo.py +++ b/stix2/v21/sdo.py @@ -173,7 +173,7 @@ class Identity(STIXDomainObject): ('name', StringProperty(required=True)), ('description', StringProperty()), ('roles', ListProperty(StringProperty)), - ('identity_class', StringProperty(required=True)), + ('identity_class', StringProperty()), ('sectors', ListProperty(StringProperty)), ('contact_information', StringProperty()), ('revoked', BooleanProperty(default=lambda: False)), @@ -202,7 +202,7 @@ class Indicator(STIXDomainObject): ('modified', TimestampProperty(default=lambda: NOW, precision='millisecond')), ('name', StringProperty()), ('description', StringProperty()), - ('indicator_types', ListProperty(StringProperty, required=True)), + ('indicator_types', ListProperty(StringProperty)), ('pattern', PatternProperty(required=True)), ('pattern_type', StringProperty(required=True)), ('pattern_version', StringProperty()), @@ -269,7 +269,7 @@ class Infrastructure(STIXDomainObject): ('granular_markings', ListProperty(GranularMarking)), ('name', StringProperty(required=True)), ('description', StringProperty()), - ('infrastructure_types', ListProperty(StringProperty, required=True)), + ('infrastructure_types', ListProperty(StringProperty)), ('aliases', ListProperty(StringProperty)), ('kill_chain_phases', ListProperty(KillChainPhase)), ('first_seen', TimestampProperty()), @@ -454,13 +454,13 @@ class Malware(STIXDomainObject): ('modified', TimestampProperty(default=lambda: NOW, precision='millisecond')), ('name', StringProperty()), ('description', StringProperty()), - ('malware_types', ListProperty(StringProperty, required=True)), + ('malware_types', ListProperty(StringProperty)), ('is_family', BooleanProperty(required=True)), ('aliases', ListProperty(StringProperty)), ('kill_chain_phases', ListProperty(KillChainPhase)), ('first_seen', TimestampProperty()), ('last_seen', TimestampProperty()), - ('os_execution_envs', ListProperty(StringProperty)), + ('operating_system_refs', ListProperty(ReferenceProperty(valid_types='software', spec_version='2.1'))), ('architecture_execution_envs', ListProperty(StringProperty)), ('implementation_languages', ListProperty(StringProperty)), ('capabilities', ListProperty(StringProperty)), @@ -524,14 +524,16 @@ class MalwareAnalysis(STIXDomainObject): ('submitted', TimestampProperty()), ('analysis_started', TimestampProperty()), ('analysis_ended', TimestampProperty()), - ('av_result', StringProperty()), + ('result_name', StringProperty()), + ('result', StringProperty()), ('analysis_sco_refs', ListProperty(ReferenceProperty(valid_types="SCO", spec_version='2.1'))), + ('sample_ref', ReferenceProperty(valid_types="SCO", spec_version="2.1")), ]) def _check_object_constraints(self): super(MalwareAnalysis, self)._check_object_constraints() - self._check_at_least_one_property(["av_result", "analysis_sco_refs"]) + self._check_at_least_one_property(["result", "analysis_sco_refs"]) class Note(STIXDomainObject): @@ -672,7 +674,7 @@ class Report(STIXDomainObject): ('modified', TimestampProperty(default=lambda: NOW, precision='millisecond')), ('name', StringProperty(required=True)), ('description', StringProperty()), - ('report_types', ListProperty(StringProperty, required=True)), + ('report_types', ListProperty(StringProperty)), ('published', TimestampProperty(required=True)), ('object_refs', ListProperty(ReferenceProperty(valid_types=["SCO", "SDO", "SRO"], spec_version='2.1'), required=True)), ('revoked', BooleanProperty(default=lambda: False)), @@ -701,7 +703,7 @@ class ThreatActor(STIXDomainObject): ('modified', TimestampProperty(default=lambda: NOW, precision='millisecond')), ('name', StringProperty(required=True)), ('description', StringProperty()), - ('threat_actor_types', ListProperty(StringProperty, required=True)), + ('threat_actor_types', ListProperty(StringProperty)), ('aliases', ListProperty(StringProperty)), ('first_seen', TimestampProperty()), ('last_seen', TimestampProperty()), @@ -748,7 +750,7 @@ class Tool(STIXDomainObject): ('modified', TimestampProperty(default=lambda: NOW, precision='millisecond')), ('name', StringProperty(required=True)), ('description', StringProperty()), - ('tool_types', ListProperty(StringProperty, required=True)), + ('tool_types', ListProperty(StringProperty)), ('aliases', ListProperty(StringProperty)), ('kill_chain_phases', ListProperty(KillChainPhase)), ('tool_version', StringProperty()),
oasis-open/cti-python-stix2
380926cff59f9e0d70914c2de933e4651f13259d
diff --git a/stix2/test/v21/test_external_reference.py b/stix2/test/v21/test_external_reference.py index d192a11..f347191 100644 --- a/stix2/test/v21/test_external_reference.py +++ b/stix2/test/v21/test_external_reference.py @@ -120,3 +120,14 @@ def test_external_reference_source_required(): assert excinfo.value.cls == stix2.v21.ExternalReference assert excinfo.value.properties == ["source_name"] + + +def test_external_reference_bad_hash(): + with pytest.raises(stix2.exceptions.InvalidValueError): + stix2.v21.ExternalReference( + source_name="ACME Threat Intel", + description="Threat report", + hashes={ + "SHA-123": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + }, + ) diff --git a/stix2/test/v21/test_indicator.py b/stix2/test/v21/test_indicator.py index d7d7e47..76fe86b 100644 --- a/stix2/test/v21/test_indicator.py +++ b/stix2/test/v21/test_indicator.py @@ -14,9 +14,6 @@ EXPECTED_INDICATOR = """{ "id": "indicator--a740531e-63ff-4e49-a9e1-a0a3eed0e3e7", "created": "2017-01-01T00:00:01.000Z", "modified": "2017-01-01T00:00:01.000Z", - "indicator_types": [ - "malicious-activity" - ], "pattern": "[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']", "pattern_type": "stix", "pattern_version": "2.1", @@ -29,7 +26,6 @@ EXPECTED_INDICATOR_REPR = "Indicator(" + " ".join(""" id='indicator--a740531e-63ff-4e49-a9e1-a0a3eed0e3e7', created='2017-01-01T00:00:01.000Z', modified='2017-01-01T00:00:01.000Z', - indicator_types=['malicious-activity'], pattern="[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']", pattern_type='stix', pattern_version='2.1', @@ -49,7 +45,6 @@ def test_indicator_with_all_required_properties(): pattern="[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']", pattern_type="stix", valid_from=epoch, - indicator_types=['malicious-activity'], ) assert ind.revoked is False @@ -103,8 +98,8 @@ def test_indicator_required_properties(): stix2.v21.Indicator() assert excinfo.value.cls == stix2.v21.Indicator - assert excinfo.value.properties == ["indicator_types", "pattern", "pattern_type", "valid_from"] - assert str(excinfo.value) == "No values for required properties for Indicator: (indicator_types, pattern, pattern_type, valid_from)." + assert excinfo.value.properties == ["pattern", "pattern_type", "valid_from"] + assert str(excinfo.value) == "No values for required properties for Indicator: (pattern, pattern_type, valid_from)." def test_indicator_required_property_pattern(): @@ -163,9 +158,6 @@ def test_created_modified_time_are_identical_by_default(): "id": INDICATOR_ID, "created": "2017-01-01T00:00:01Z", "modified": "2017-01-01T00:00:01Z", - "indicator_types": [ - "malicious-activity", - ], "pattern": "[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']", "pattern_type": "stix", "valid_from": "1970-01-01T00:00:01Z", @@ -181,7 +173,6 @@ def test_parse_indicator(data): assert idctr.created == dt.datetime(2017, 1, 1, 0, 0, 1, tzinfo=pytz.utc) assert idctr.modified == dt.datetime(2017, 1, 1, 0, 0, 1, tzinfo=pytz.utc) assert idctr.valid_from == dt.datetime(1970, 1, 1, 0, 0, 1, tzinfo=pytz.utc) - assert idctr.indicator_types[0] == "malicious-activity" assert idctr.pattern == "[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']" diff --git a/stix2/test/v21/test_infrastructure.py b/stix2/test/v21/test_infrastructure.py index 30632bb..3e9feb7 100644 --- a/stix2/test/v21/test_infrastructure.py +++ b/stix2/test/v21/test_infrastructure.py @@ -13,10 +13,7 @@ EXPECTED_INFRASTRUCTURE = """{ "id": "infrastructure--3000ae1b-784c-f03d-8abc-0a625b2ff018", "created": "2017-01-01T12:34:56.000Z", "modified": "2017-01-01T12:34:56.000Z", - "name": "Poison Ivy C2", - "infrastructure_types": [ - "command-and-control" - ] + "name": "Poison Ivy C2" }""" @@ -29,7 +26,6 @@ def test_infrastructure_with_all_required_properties(): created=now, modified=now, name="Poison Ivy C2", - infrastructure_types=["command-and-control"], ) assert str(infra) == EXPECTED_INFRASTRUCTURE @@ -76,7 +72,7 @@ def test_infrastructure_required_properties(): stix2.v21.Infrastructure() assert excinfo.value.cls == stix2.v21.Infrastructure - assert excinfo.value.properties == ["infrastructure_types", "name"] + assert excinfo.value.properties == ["name"] def test_infrastructure_required_property_name(): @@ -105,7 +101,6 @@ def test_invalid_kwarg_to_infrastructure(): "id": INFRASTRUCTURE_ID, "created": "2017-01-01T12:34:56.000Z", "modified": "2017-01-01T12:34:56.000Z", - "infrastructure_types": ["command-and-control"], "name": "Poison Ivy C2", }, ], @@ -118,7 +113,6 @@ def test_parse_infrastructure(data): assert infra.id == INFRASTRUCTURE_ID assert infra.created == dt.datetime(2017, 1, 1, 12, 34, 56, tzinfo=pytz.utc) assert infra.modified == dt.datetime(2017, 1, 1, 12, 34, 56, tzinfo=pytz.utc) - assert infra.infrastructure_types == ['command-and-control'] assert infra.name == 'Poison Ivy C2' diff --git a/stix2/test/v21/test_malware.py b/stix2/test/v21/test_malware.py index 53838c9..f111826 100644 --- a/stix2/test/v21/test_malware.py +++ b/stix2/test/v21/test_malware.py @@ -1,5 +1,5 @@ import datetime as dt -import re +import json import pytest import pytz @@ -16,9 +16,6 @@ EXPECTED_MALWARE = """{ "created": "2016-05-12T08:17:27.000Z", "modified": "2016-05-12T08:17:27.000Z", "name": "Cryptolocker", - "malware_types": [ - "ransomware" - ], "is_family": false }""" @@ -31,7 +28,6 @@ def test_malware_with_all_required_properties(): id=MALWARE_ID, created=now, modified=now, - malware_types=["ransomware"], name="Cryptolocker", is_family=False, ) @@ -80,7 +76,7 @@ def test_malware_required_properties(): stix2.v21.Malware() assert excinfo.value.cls == stix2.v21.Malware - assert excinfo.value.properties == ["is_family", "malware_types"] + assert excinfo.value.properties == ["is_family"] def test_malware_required_property_name(): @@ -116,7 +112,6 @@ def test_invalid_kwarg_to_malware(): "id": MALWARE_ID, "created": "2016-05-12T08:17:27.000Z", "modified": "2016-05-12T08:17:27.000Z", - "malware_types": ["ransomware"], "name": "Cryptolocker", "is_family": False, }, @@ -130,13 +125,14 @@ def test_parse_malware(data): assert mal.id == MALWARE_ID assert mal.created == dt.datetime(2016, 5, 12, 8, 17, 27, tzinfo=pytz.utc) assert mal.modified == dt.datetime(2016, 5, 12, 8, 17, 27, tzinfo=pytz.utc) - assert mal.malware_types == ['ransomware'] assert mal.name == 'Cryptolocker' assert not mal.is_family -def test_parse_malware_invalid_labels(): - data = re.compile('\\[.+\\]', re.DOTALL).sub('1', EXPECTED_MALWARE) +def test_parse_malware_invalid_types(): + data = json.loads(EXPECTED_MALWARE) + data["malware_types"] = 1 # Oops, not a list + data = json.dumps(data) with pytest.raises(InvalidValueError) as excinfo: stix2.parse(data) assert "Invalid value for Malware 'malware_types'" in str(excinfo.value) @@ -197,3 +193,22 @@ def test_malware_non_family_no_name(): "is_family": False, "malware_types": ["something"], }) + + +def test_malware_with_os_refs(): + software = stix2.parse({ + "type": "software", + "name": "SuperOS", + "spec_version": "2.1", + }) + + malware = stix2.parse({ + "type": "malware", + "id": MALWARE_ID, + "spec_version": "2.1", + "is_family": False, + "malware_types": ["something"], + "operating_system_refs": [software], + }) + + assert malware["operating_system_refs"][0] == software["id"] diff --git a/stix2/test/v21/test_malware_analysis.py b/stix2/test/v21/test_malware_analysis.py index bfb4ff4..22f4171 100644 --- a/stix2/test/v21/test_malware_analysis.py +++ b/stix2/test/v21/test_malware_analysis.py @@ -34,11 +34,13 @@ MALWARE_ANALYSIS_JSON = """{ "submitted": "2018-11-23T06:45:55.747Z", "analysis_started": "2018-11-29T07:30:03.895Z", "analysis_ended": "2018-11-29T08:30:03.895Z", - "av_result": "malicious", + "result_name": "MegaRansom", + "result": "malicious", "analysis_sco_refs": [ "file--fc27e371-6c88-4c5c-868a-4dda0e60b167", "url--6f7a74cd-8eb2-4b88-a4da-aa878e50ac2e" - ] + ], + "sample_ref": "email-addr--499a32d7-74c1-4276-ace9-725ac933e243" }""" diff --git a/stix2/test/v21/test_observed_data.py b/stix2/test/v21/test_observed_data.py index 71bad46..abcbb7b 100644 --- a/stix2/test/v21/test_observed_data.py +++ b/stix2/test/v21/test_observed_data.py @@ -1300,6 +1300,7 @@ def test_software_example(): s = stix2.v21.Software( name="Word", cpe="cpe:2.3:a:microsoft:word:2000:*:*:*:*:*:*:*", + swid="com.acme.rms-ce-v4-1-5-0", version="2002", vendor="Microsoft", )
Malware os_execution_envs changes This property was renamed to operating_system_refs, is now list of Software SCO identifiers instead of strings, and no longer SHOULD be a CPE entry.
0.0
[ "stix2/test/v21/test_external_reference.py::test_external_reference_bad_hash", "stix2/test/v21/test_indicator.py::test_indicator_with_all_required_properties", "stix2/test/v21/test_indicator.py::test_indicator_required_properties", "stix2/test/v21/test_indicator.py::test_parse_indicator[{\\n", "stix2/test/v21/test_indicator.py::test_parse_indicator[data1]", "stix2/test/v21/test_infrastructure.py::test_infrastructure_with_all_required_properties", "stix2/test/v21/test_infrastructure.py::test_infrastructure_required_properties", "stix2/test/v21/test_infrastructure.py::test_parse_infrastructure[{\\n", "stix2/test/v21/test_infrastructure.py::test_parse_infrastructure[data1]", "stix2/test/v21/test_infrastructure.py::test_parse_infrastructure_kill_chain_phases", "stix2/test/v21/test_infrastructure.py::test_parse_infrastructure_clean_kill_chain_phases", "stix2/test/v21/test_malware.py::test_malware_with_all_required_properties", "stix2/test/v21/test_malware.py::test_malware_required_properties", "stix2/test/v21/test_malware.py::test_parse_malware[{\\n", "stix2/test/v21/test_malware.py::test_parse_malware[data1]", "stix2/test/v21/test_malware.py::test_parse_malware_kill_chain_phases", "stix2/test/v21/test_malware.py::test_parse_malware_clean_kill_chain_phases", "stix2/test/v21/test_malware.py::test_malware_with_os_refs", "stix2/test/v21/test_malware_analysis.py::test_malware_analysis_example", "stix2/test/v21/test_malware_analysis.py::test_parse_malware_analysis[{\\n", "stix2/test/v21/test_malware_analysis.py::test_parse_malware_analysis[data1]", "stix2/test/v21/test_observed_data.py::test_software_example" ]
[ "stix2/test/v21/test_external_reference.py::test_external_reference_veris", "stix2/test/v21/test_external_reference.py::test_external_reference_capec", "stix2/test/v21/test_external_reference.py::test_external_reference_capec_url", "stix2/test/v21/test_external_reference.py::test_external_reference_threat_report", "stix2/test/v21/test_external_reference.py::test_external_reference_bugzilla", "stix2/test/v21/test_external_reference.py::test_external_reference_offline", "stix2/test/v21/test_external_reference.py::test_external_reference_source_required", "stix2/test/v21/test_indicator.py::test_indicator_autogenerated_properties", "stix2/test/v21/test_indicator.py::test_indicator_type_must_be_indicator", "stix2/test/v21/test_indicator.py::test_indicator_id_must_start_with_indicator", "stix2/test/v21/test_indicator.py::test_indicator_required_property_pattern", "stix2/test/v21/test_indicator.py::test_indicator_created_ref_invalid_format", "stix2/test/v21/test_indicator.py::test_indicator_revoked_invalid", "stix2/test/v21/test_indicator.py::test_cannot_assign_to_indicator_attributes", "stix2/test/v21/test_indicator.py::test_invalid_kwarg_to_indicator", "stix2/test/v21/test_indicator.py::test_created_modified_time_are_identical_by_default", "stix2/test/v21/test_indicator.py::test_invalid_indicator_pattern", "stix2/test/v21/test_indicator.py::test_indicator_with_custom_embedded_objs", "stix2/test/v21/test_indicator.py::test_indicator_with_custom_embed_objs_extra_props_error", "stix2/test/v21/test_indicator.py::test_indicator_stix20_invalid_pattern", "stix2/test/v21/test_infrastructure.py::test_infrastructure_autogenerated_properties", "stix2/test/v21/test_infrastructure.py::test_infrastructure_type_must_be_infrastructure", "stix2/test/v21/test_infrastructure.py::test_infrastructure_id_must_start_with_infrastructure", "stix2/test/v21/test_infrastructure.py::test_infrastructure_required_property_name", "stix2/test/v21/test_infrastructure.py::test_invalid_kwarg_to_infrastructure", "stix2/test/v21/test_infrastructure.py::test_infrastructure_invalid_last_before_first", "stix2/test/v21/test_malware.py::test_malware_autogenerated_properties", "stix2/test/v21/test_malware.py::test_malware_type_must_be_malware", "stix2/test/v21/test_malware.py::test_malware_id_must_start_with_malware", "stix2/test/v21/test_malware.py::test_malware_required_property_name", "stix2/test/v21/test_malware.py::test_cannot_assign_to_malware_attributes", "stix2/test/v21/test_malware.py::test_invalid_kwarg_to_malware", "stix2/test/v21/test_malware.py::test_parse_malware_invalid_types", "stix2/test/v21/test_malware.py::test_malware_invalid_last_before_first", "stix2/test/v21/test_malware.py::test_malware_family_no_name", "stix2/test/v21/test_malware.py::test_malware_non_family_no_name", "stix2/test/v21/test_malware_analysis.py::test_malware_analysis_constraint", "stix2/test/v21/test_observed_data.py::test_observed_data_example", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_refs", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_object_refs", "stix2/test/v21/test_observed_data.py::test_observed_data_object_constraint", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_bad_refs", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_non_dictionary", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_empty_dictionary", "stix2/test/v21/test_observed_data.py::test_parse_observed_data[{\\n", "stix2/test/v21/test_observed_data.py::test_parse_observed_data[data1]", "stix2/test/v21/test_observed_data.py::test_parse_artifact_valid[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_artifact_invalid[\"0\":", "stix2/test/v21/test_observed_data.py::test_artifact_example_dependency_error", "stix2/test/v21/test_observed_data.py::test_parse_autonomous_system_valid[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_email_address[{\\n", "stix2/test/v21/test_observed_data.py::test_parse_email_message[\\n", "stix2/test/v21/test_observed_data.py::test_parse_email_message_not_multipart[\\n", "stix2/test/v21/test_observed_data.py::test_parse_file_archive[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_email_message_with_at_least_one_error[\\n", "stix2/test/v21/test_observed_data.py::test_parse_basic_tcp_traffic[\\n", "stix2/test/v21/test_observed_data.py::test_parse_basic_tcp_traffic_with_error[\\n", "stix2/test/v21/test_observed_data.py::test_observed_data_with_process_example", "stix2/test/v21/test_observed_data.py::test_artifact_example", "stix2/test/v21/test_observed_data.py::test_artifact_mutual_exclusion_error", "stix2/test/v21/test_observed_data.py::test_directory_example", "stix2/test/v21/test_observed_data.py::test_directory_example_ref_error", "stix2/test/v21/test_observed_data.py::test_domain_name_example", "stix2/test/v21/test_observed_data.py::test_domain_name_example_invalid_ref_type", "stix2/test/v21/test_observed_data.py::test_file_example", "stix2/test/v21/test_observed_data.py::test_file_example_with_NTFSExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_empty_NTFSExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_PDFExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_PDFExt_Object", "stix2/test/v21/test_observed_data.py::test_file_example_with_RasterImageExt_Object", "stix2/test/v21/test_observed_data.py::test_raster_image_ext_parse", "stix2/test/v21/test_observed_data.py::test_raster_images_ext_create", "stix2/test/v21/test_observed_data.py::test_file_example_with_WindowsPEBinaryExt", "stix2/test/v21/test_observed_data.py::test_file_example_encryption_error", "stix2/test/v21/test_observed_data.py::test_ipv4_address_example", "stix2/test/v21/test_observed_data.py::test_ipv4_address_valid_refs", "stix2/test/v21/test_observed_data.py::test_ipv4_address_example_cidr", "stix2/test/v21/test_observed_data.py::test_ipv6_address_example", "stix2/test/v21/test_observed_data.py::test_mac_address_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_http_request_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_icmp_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_socket_example", "stix2/test/v21/test_observed_data.py::test_correct_socket_options", "stix2/test/v21/test_observed_data.py::test_incorrect_socket_options", "stix2/test/v21/test_observed_data.py::test_network_traffic_tcp_example", "stix2/test/v21/test_observed_data.py::test_mutex_example", "stix2/test/v21/test_observed_data.py::test_process_example", "stix2/test/v21/test_observed_data.py::test_process_example_empty_error", "stix2/test/v21/test_observed_data.py::test_process_example_empty_with_extensions", "stix2/test/v21/test_observed_data.py::test_process_example_windows_process_ext", "stix2/test/v21/test_observed_data.py::test_process_example_windows_process_ext_empty", "stix2/test/v21/test_observed_data.py::test_process_example_extensions_empty", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsProcessExt_Object", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsServiceExt", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsProcessServiceExt", "stix2/test/v21/test_observed_data.py::test_url_example", "stix2/test/v21/test_observed_data.py::test_user_account_example", "stix2/test/v21/test_observed_data.py::test_user_account_unix_account_ext_example", "stix2/test/v21/test_observed_data.py::test_windows_registry_key_example", "stix2/test/v21/test_observed_data.py::test_x509_certificate_example", "stix2/test/v21/test_observed_data.py::test_x509_certificate_error", "stix2/test/v21/test_observed_data.py::test_new_version_with_related_objects", "stix2/test/v21/test_observed_data.py::test_objects_deprecation", "stix2/test/v21/test_observed_data.py::test_deterministic_id_same_extra_prop_vals", "stix2/test/v21/test_observed_data.py::test_deterministic_id_diff_extra_prop_vals", "stix2/test/v21/test_observed_data.py::test_deterministic_id_diff_contributing_prop_vals", "stix2/test/v21/test_observed_data.py::test_deterministic_id_no_contributing_props", "stix2/test/v21/test_observed_data.py::test_id_gen_recursive_dict_conversion_1", "stix2/test/v21/test_observed_data.py::test_id_gen_recursive_dict_conversion_2" ]
2020-03-06 23:53:44+00:00
4,300
oasis-open__cti-python-stix2-393
diff --git a/stix2/patterns.py b/stix2/patterns.py index f0cceb8..a44f68e 100644 --- a/stix2/patterns.py +++ b/stix2/patterns.py @@ -121,21 +121,21 @@ class BooleanConstant(_Constant): _HASH_REGEX = { - "MD5": ("^[a-fA-F0-9]{32}$", "MD5"), - "MD6": ("^[a-fA-F0-9]{32}|[a-fA-F0-9]{40}|[a-fA-F0-9]{56}|[a-fA-F0-9]{64}|[a-fA-F0-9]{96}|[a-fA-F0-9]{128}$", "MD6"), - "RIPEMD160": ("^[a-fA-F0-9]{40}$", "RIPEMD-160"), - "SHA1": ("^[a-fA-F0-9]{40}$", "SHA-1"), - "SHA224": ("^[a-fA-F0-9]{56}$", "SHA-224"), - "SHA256": ("^[a-fA-F0-9]{64}$", "SHA-256"), - "SHA384": ("^[a-fA-F0-9]{96}$", "SHA-384"), - "SHA512": ("^[a-fA-F0-9]{128}$", "SHA-512"), - "SHA3224": ("^[a-fA-F0-9]{56}$", "SHA3-224"), - "SHA3256": ("^[a-fA-F0-9]{64}$", "SHA3-256"), - "SHA3384": ("^[a-fA-F0-9]{96}$", "SHA3-384"), - "SHA3512": ("^[a-fA-F0-9]{128}$", "SHA3-512"), - "SSDEEP": ("^[a-zA-Z0-9/+:.]{1,128}$", "ssdeep"), - "WHIRLPOOL": ("^[a-fA-F0-9]{128}$", "WHIRLPOOL"), - "TLSH": ("^[a-fA-F0-9]{70}$", "TLSH"), + "MD5": (r"^[a-fA-F0-9]{32}$", "MD5"), + "MD6": (r"^[a-fA-F0-9]{32}|[a-fA-F0-9]{40}|[a-fA-F0-9]{56}|[a-fA-F0-9]{64}|[a-fA-F0-9]{96}|[a-fA-F0-9]{128}$", "MD6"), + "RIPEMD160": (r"^[a-fA-F0-9]{40}$", "RIPEMD-160"), + "SHA1": (r"^[a-fA-F0-9]{40}$", "SHA-1"), + "SHA224": (r"^[a-fA-F0-9]{56}$", "SHA-224"), + "SHA256": (r"^[a-fA-F0-9]{64}$", "SHA-256"), + "SHA384": (r"^[a-fA-F0-9]{96}$", "SHA-384"), + "SHA512": (r"^[a-fA-F0-9]{128}$", "SHA-512"), + "SHA3224": (r"^[a-fA-F0-9]{56}$", "SHA3-224"), + "SHA3256": (r"^[a-fA-F0-9]{64}$", "SHA3-256"), + "SHA3384": (r"^[a-fA-F0-9]{96}$", "SHA3-384"), + "SHA3512": (r"^[a-fA-F0-9]{128}$", "SHA3-512"), + "SSDEEP": (r"^[a-zA-Z0-9/+:.]{1,128}$", "SSDEEP"), + "WHIRLPOOL": (r"^[a-fA-F0-9]{128}$", "WHIRLPOOL"), + "TLSH": (r"^[a-fA-F0-9]{70}$", "TLSH"), } diff --git a/stix2/properties.py b/stix2/properties.py index a1bab6d..c876c11 100644 --- a/stix2/properties.py +++ b/stix2/properties.py @@ -417,7 +417,7 @@ HASHES_REGEX = { "SHA3256": (r"^[a-fA-F0-9]{64}$", "SHA3-256"), "SHA3384": (r"^[a-fA-F0-9]{96}$", "SHA3-384"), "SHA3512": (r"^[a-fA-F0-9]{128}$", "SHA3-512"), - "SSDEEP": (r"^[a-zA-Z0-9/+:.]{1,128}$", "ssdeep"), + "SSDEEP": (r"^[a-zA-Z0-9/+:.]{1,128}$", "SSDEEP"), "WHIRLPOOL": (r"^[a-fA-F0-9]{128}$", "WHIRLPOOL"), "TLSH": (r"^[a-fA-F0-9]{70}$", "TLSH"), } @@ -431,6 +431,8 @@ class HashesProperty(DictionaryProperty): key = k.upper().replace('-', '') if key in HASHES_REGEX: vocab_key = HASHES_REGEX[key][1] + if vocab_key == "SSDEEP" and self.spec_version == "2.0": + vocab_key = vocab_key.lower() if not re.match(HASHES_REGEX[key][0], v): raise ValueError("'{0}' is not a valid {1} hash".format(v, vocab_key)) if k != vocab_key:
oasis-open/cti-python-stix2
658e70bf04b2145e8b108ea7117867288a31e2a7
diff --git a/stix2/test/v20/test_observed_data.py b/stix2/test/v20/test_observed_data.py index bfe9c34..354d70c 100644 --- a/stix2/test/v20/test_observed_data.py +++ b/stix2/test/v20/test_observed_data.py @@ -714,6 +714,22 @@ def test_file_example(): assert f.decryption_key == "fred" # does the key have a format we can test for? +def test_file_ssdeep_example(): + f = stix2.v20.File( + name="example.dll", + hashes={ + "SHA-256": "ceafbfd424be2ca4a5f0402cae090dda2fb0526cf521b60b60077c0f622b285a", + "ssdeep": "96:gS/mFkCpXTWLr/PbKQHbr/S/mFkCpXTWLr/PbKQHbrB:Tu6SXTWGQHbeu6SXTWGQHbV", + }, + size=1024, + ) + + assert f.name == "example.dll" + assert f.size == 1024 + assert f.hashes["SHA-256"] == "ceafbfd424be2ca4a5f0402cae090dda2fb0526cf521b60b60077c0f622b285a" + assert f.hashes["ssdeep"] == "96:gS/mFkCpXTWLr/PbKQHbr/S/mFkCpXTWLr/PbKQHbrB:Tu6SXTWGQHbeu6SXTWGQHbV" + + def test_file_example_with_NTFSExt(): f = stix2.v20.File( name="abc.txt", diff --git a/stix2/test/v21/test_observed_data.py b/stix2/test/v21/test_observed_data.py index b8732be..c13148a 100644 --- a/stix2/test/v21/test_observed_data.py +++ b/stix2/test/v21/test_observed_data.py @@ -785,6 +785,22 @@ def test_file_example(): assert f.atime == dt.datetime(2016, 12, 21, 20, 0, 0, tzinfo=pytz.utc) +def test_file_ssdeep_example(): + f = stix2.v21.File( + name="example.dll", + hashes={ + "SHA-256": "ceafbfd424be2ca4a5f0402cae090dda2fb0526cf521b60b60077c0f622b285a", + "SSDEEP": "96:gS/mFkCpXTWLr/PbKQHbr/S/mFkCpXTWLr/PbKQHbrB:Tu6SXTWGQHbeu6SXTWGQHbV", + }, + size=1024, + ) + + assert f.name == "example.dll" + assert f.size == 1024 + assert f.hashes["SHA-256"] == "ceafbfd424be2ca4a5f0402cae090dda2fb0526cf521b60b60077c0f622b285a" + assert f.hashes["SSDEEP"] == "96:gS/mFkCpXTWLr/PbKQHbr/S/mFkCpXTWLr/PbKQHbrB:Tu6SXTWGQHbeu6SXTWGQHbV" + + def test_file_example_with_NTFSExt(): f = stix2.v21.File( name="abc.txt", diff --git a/stix2/test/v21/test_pattern_expressions.py b/stix2/test/v21/test_pattern_expressions.py index 198edac..8294a41 100644 --- a/stix2/test/v21/test_pattern_expressions.py +++ b/stix2/test/v21/test_pattern_expressions.py @@ -518,7 +518,7 @@ def test_invalid_boolean_constant(): @pytest.mark.parametrize( "hashtype, data", [ ('MD5', 'zzz'), - ('ssdeep', 'zzz=='), + ('SSDEEP', 'zzz=='), ], ) def test_invalid_hash_constant(hashtype, data):
SSDEEP Hashing algorithm case mismatch Currently if an `ssdeep` hash is added to an object it will change it to its lowercase variant (not aligned with Section 10.6 STIX 2.1 https://docs.oasis-open.org/cti/stix/v2.1/cs01/stix-v2.1-cs01.html#_tumklw3o2gyz) because stix2 will "clean" the field name. This causes the validator to emit a warning on a "unrecognized hash". Validator: ``` [!] Warning: file--xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx: {241} Object 'file--xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' has a 'hashes' dictionary with a hash of type 'ssdeep', which is not a value in the hash-algorithm-ov vocabulary nor a custom value prepended with 'x_'. ``` https://github.com/oasis-open/cti-python-stix2/blob/df92770d255d66bd614d4975fc4602c7407998fb/stix2/properties.py#L420
0.0
[ "stix2/test/v21/test_observed_data.py::test_file_ssdeep_example" ]
[ "stix2/test/v20/test_observed_data.py::test_observed_data_example", "stix2/test/v20/test_observed_data.py::test_observed_data_example_with_refs", "stix2/test/v20/test_observed_data.py::test_observed_data_example_with_bad_refs", "stix2/test/v20/test_observed_data.py::test_observed_data_example_with_non_dictionary", "stix2/test/v20/test_observed_data.py::test_observed_data_example_with_empty_dictionary", "stix2/test/v20/test_observed_data.py::test_parse_observed_data[{\\n", "stix2/test/v20/test_observed_data.py::test_parse_observed_data[data1]", "stix2/test/v20/test_observed_data.py::test_parse_artifact_valid[\"0\":", "stix2/test/v20/test_observed_data.py::test_parse_artifact_invalid[\"0\":", "stix2/test/v20/test_observed_data.py::test_artifact_example_dependency_error", "stix2/test/v20/test_observed_data.py::test_parse_autonomous_system_valid[\"0\":", "stix2/test/v20/test_observed_data.py::test_parse_email_address[{\\n", "stix2/test/v20/test_observed_data.py::test_parse_email_message[\\n", "stix2/test/v20/test_observed_data.py::test_parse_email_message_not_multipart[\\n", "stix2/test/v20/test_observed_data.py::test_parse_file_archive[\"0\":", "stix2/test/v20/test_observed_data.py::test_parse_email_message_with_at_least_one_error[\\n", "stix2/test/v20/test_observed_data.py::test_parse_basic_tcp_traffic[\\n", "stix2/test/v20/test_observed_data.py::test_parse_basic_tcp_traffic_with_error[\\n", "stix2/test/v20/test_observed_data.py::test_observed_data_with_process_example", "stix2/test/v20/test_observed_data.py::test_artifact_example", "stix2/test/v20/test_observed_data.py::test_artifact_mutual_exclusion_error", "stix2/test/v20/test_observed_data.py::test_directory_example", "stix2/test/v20/test_observed_data.py::test_directory_example_ref_error", "stix2/test/v20/test_observed_data.py::test_domain_name_example", "stix2/test/v20/test_observed_data.py::test_domain_name_example_invalid_ref_type", "stix2/test/v20/test_observed_data.py::test_file_example", "stix2/test/v20/test_observed_data.py::test_file_ssdeep_example", "stix2/test/v20/test_observed_data.py::test_file_example_with_NTFSExt", "stix2/test/v20/test_observed_data.py::test_file_example_with_empty_NTFSExt", "stix2/test/v20/test_observed_data.py::test_file_example_with_PDFExt", "stix2/test/v20/test_observed_data.py::test_file_example_with_PDFExt_Object", "stix2/test/v20/test_observed_data.py::test_file_example_with_RasterImageExt_Object", "stix2/test/v20/test_observed_data.py::test_raster_image_ext_parse", "stix2/test/v20/test_observed_data.py::test_raster_images_ext_create", "stix2/test/v20/test_observed_data.py::test_file_example_with_WindowsPEBinaryExt", "stix2/test/v20/test_observed_data.py::test_file_example_encryption_error", "stix2/test/v20/test_observed_data.py::test_ip4_address_example", "stix2/test/v20/test_observed_data.py::test_ip4_address_valid_refs", "stix2/test/v20/test_observed_data.py::test_ip4_address_example_cidr", "stix2/test/v20/test_observed_data.py::test_ip6_address_example", "stix2/test/v20/test_observed_data.py::test_mac_address_example", "stix2/test/v20/test_observed_data.py::test_network_traffic_example", "stix2/test/v20/test_observed_data.py::test_network_traffic_http_request_example", "stix2/test/v20/test_observed_data.py::test_network_traffic_icmp_example", "stix2/test/v20/test_observed_data.py::test_network_traffic_socket_example", "stix2/test/v20/test_observed_data.py::test_network_traffic_tcp_example", "stix2/test/v20/test_observed_data.py::test_mutex_example", "stix2/test/v20/test_observed_data.py::test_process_example", "stix2/test/v20/test_observed_data.py::test_process_example_empty_error", "stix2/test/v20/test_observed_data.py::test_process_example_empty_with_extensions", "stix2/test/v20/test_observed_data.py::test_process_example_windows_process_ext", "stix2/test/v20/test_observed_data.py::test_process_example_windows_process_ext_empty", "stix2/test/v20/test_observed_data.py::test_process_example_extensions_empty", "stix2/test/v20/test_observed_data.py::test_process_example_with_WindowsProcessExt_Object", "stix2/test/v20/test_observed_data.py::test_process_example_with_WindowsServiceExt", "stix2/test/v20/test_observed_data.py::test_process_example_with_WindowsProcessServiceExt", "stix2/test/v20/test_observed_data.py::test_software_example", "stix2/test/v20/test_observed_data.py::test_url_example", "stix2/test/v20/test_observed_data.py::test_user_account_example", "stix2/test/v20/test_observed_data.py::test_user_account_unix_account_ext_example", "stix2/test/v20/test_observed_data.py::test_windows_registry_key_example", "stix2/test/v20/test_observed_data.py::test_x509_certificate_example", "stix2/test/v20/test_observed_data.py::test_new_version_with_related_objects", "stix2/test/v21/test_observed_data.py::test_observed_data_example", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_refs", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_object_refs", "stix2/test/v21/test_observed_data.py::test_observed_data_object_constraint", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_bad_refs", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_non_dictionary", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_empty_dictionary", "stix2/test/v21/test_observed_data.py::test_parse_observed_data[{\\n", "stix2/test/v21/test_observed_data.py::test_parse_observed_data[data1]", "stix2/test/v21/test_observed_data.py::test_parse_artifact_valid[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_artifact_invalid[\"0\":", "stix2/test/v21/test_observed_data.py::test_artifact_example_dependency_error", "stix2/test/v21/test_observed_data.py::test_parse_autonomous_system_valid[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_email_address[{\\n", "stix2/test/v21/test_observed_data.py::test_parse_email_message[\\n", "stix2/test/v21/test_observed_data.py::test_parse_email_message_not_multipart[\\n", "stix2/test/v21/test_observed_data.py::test_parse_file_archive[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_email_message_with_at_least_one_error[\\n", "stix2/test/v21/test_observed_data.py::test_parse_basic_tcp_traffic[\\n", "stix2/test/v21/test_observed_data.py::test_parse_basic_tcp_traffic_with_error[\\n", "stix2/test/v21/test_observed_data.py::test_observed_data_with_process_example", "stix2/test/v21/test_observed_data.py::test_artifact_example", "stix2/test/v21/test_observed_data.py::test_artifact_mutual_exclusion_error", "stix2/test/v21/test_observed_data.py::test_directory_example", "stix2/test/v21/test_observed_data.py::test_directory_example_ref_error", "stix2/test/v21/test_observed_data.py::test_domain_name_example", "stix2/test/v21/test_observed_data.py::test_domain_name_example_invalid_ref_type", "stix2/test/v21/test_observed_data.py::test_file_example", "stix2/test/v21/test_observed_data.py::test_file_example_with_NTFSExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_empty_NTFSExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_PDFExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_PDFExt_Object", "stix2/test/v21/test_observed_data.py::test_file_example_with_RasterImageExt_Object", "stix2/test/v21/test_observed_data.py::test_raster_image_ext_parse", "stix2/test/v21/test_observed_data.py::test_raster_images_ext_create", "stix2/test/v21/test_observed_data.py::test_file_example_with_WindowsPEBinaryExt", "stix2/test/v21/test_observed_data.py::test_file_example_encryption_error", "stix2/test/v21/test_observed_data.py::test_ipv4_address_example", "stix2/test/v21/test_observed_data.py::test_ipv4_address_valid_refs", "stix2/test/v21/test_observed_data.py::test_ipv4_address_example_cidr", "stix2/test/v21/test_observed_data.py::test_ipv6_address_example", "stix2/test/v21/test_observed_data.py::test_mac_address_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_http_request_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_icmp_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_socket_example", "stix2/test/v21/test_observed_data.py::test_correct_socket_options", "stix2/test/v21/test_observed_data.py::test_incorrect_socket_options", "stix2/test/v21/test_observed_data.py::test_network_traffic_tcp_example", "stix2/test/v21/test_observed_data.py::test_mutex_example", "stix2/test/v21/test_observed_data.py::test_process_example", "stix2/test/v21/test_observed_data.py::test_process_example_empty_error", "stix2/test/v21/test_observed_data.py::test_process_example_empty_with_extensions", "stix2/test/v21/test_observed_data.py::test_process_example_windows_process_ext", "stix2/test/v21/test_observed_data.py::test_process_example_windows_process_ext_empty", "stix2/test/v21/test_observed_data.py::test_process_example_extensions_empty", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsProcessExt_Object", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsServiceExt", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsProcessServiceExt", "stix2/test/v21/test_observed_data.py::test_software_example", "stix2/test/v21/test_observed_data.py::test_url_example", "stix2/test/v21/test_observed_data.py::test_user_account_example", "stix2/test/v21/test_observed_data.py::test_user_account_unix_account_ext_example", "stix2/test/v21/test_observed_data.py::test_windows_registry_key_example", "stix2/test/v21/test_observed_data.py::test_x509_certificate_example", "stix2/test/v21/test_observed_data.py::test_x509_certificate_error", "stix2/test/v21/test_observed_data.py::test_new_version_with_related_objects", "stix2/test/v21/test_observed_data.py::test_objects_deprecation", "stix2/test/v21/test_observed_data.py::test_deterministic_id_same_extra_prop_vals", "stix2/test/v21/test_observed_data.py::test_deterministic_id_diff_extra_prop_vals", "stix2/test/v21/test_observed_data.py::test_deterministic_id_diff_contributing_prop_vals", "stix2/test/v21/test_observed_data.py::test_deterministic_id_no_contributing_props", "stix2/test/v21/test_observed_data.py::test_id_gen_recursive_dict_conversion_1", "stix2/test/v21/test_observed_data.py::test_id_gen_recursive_dict_conversion_2", "stix2/test/v21/test_pattern_expressions.py::test_create_comparison_expression", "stix2/test/v21/test_pattern_expressions.py::test_boolean_expression", "stix2/test/v21/test_pattern_expressions.py::test_boolean_expression_with_parentheses", "stix2/test/v21/test_pattern_expressions.py::test_hash_followed_by_registryKey_expression_python_constant", "stix2/test/v21/test_pattern_expressions.py::test_hash_followed_by_registryKey_expression", "stix2/test/v21/test_pattern_expressions.py::test_file_observable_expression", "stix2/test/v21/test_pattern_expressions.py::test_multiple_file_observable_expression[AndObservationExpression-AND]", "stix2/test/v21/test_pattern_expressions.py::test_multiple_file_observable_expression[OrObservationExpression-OR]", "stix2/test/v21/test_pattern_expressions.py::test_root_types", "stix2/test/v21/test_pattern_expressions.py::test_artifact_payload", "stix2/test/v21/test_pattern_expressions.py::test_greater_than_python_constant", "stix2/test/v21/test_pattern_expressions.py::test_greater_than", "stix2/test/v21/test_pattern_expressions.py::test_parsing_greater_than", "stix2/test/v21/test_pattern_expressions.py::test_less_than", "stix2/test/v21/test_pattern_expressions.py::test_parsing_less_than", "stix2/test/v21/test_pattern_expressions.py::test_greater_than_or_equal", "stix2/test/v21/test_pattern_expressions.py::test_parsing_greater_than_or_equal", "stix2/test/v21/test_pattern_expressions.py::test_less_than_or_equal", "stix2/test/v21/test_pattern_expressions.py::test_parsing_less_than_or_equal", "stix2/test/v21/test_pattern_expressions.py::test_parsing_issubset", "stix2/test/v21/test_pattern_expressions.py::test_parsing_issuperset", "stix2/test/v21/test_pattern_expressions.py::test_parsing_like", "stix2/test/v21/test_pattern_expressions.py::test_parsing_match", "stix2/test/v21/test_pattern_expressions.py::test_parsing_followed_by", "stix2/test/v21/test_pattern_expressions.py::test_not", "stix2/test/v21/test_pattern_expressions.py::test_and_observable_expression", "stix2/test/v21/test_pattern_expressions.py::test_parsing_and_observable_expression", "stix2/test/v21/test_pattern_expressions.py::test_or_observable_expression", "stix2/test/v21/test_pattern_expressions.py::test_parsing_or_observable_expression", "stix2/test/v21/test_pattern_expressions.py::test_invalid_and_observable_expression", "stix2/test/v21/test_pattern_expressions.py::test_hex", "stix2/test/v21/test_pattern_expressions.py::test_parsing_hex", "stix2/test/v21/test_pattern_expressions.py::test_multiple_qualifiers", "stix2/test/v21/test_pattern_expressions.py::test_set_op", "stix2/test/v21/test_pattern_expressions.py::test_timestamp", "stix2/test/v21/test_pattern_expressions.py::test_boolean", "stix2/test/v21/test_pattern_expressions.py::test_binary", "stix2/test/v21/test_pattern_expressions.py::test_parsing_binary", "stix2/test/v21/test_pattern_expressions.py::test_list", "stix2/test/v21/test_pattern_expressions.py::test_list2", "stix2/test/v21/test_pattern_expressions.py::test_invalid_constant_type", "stix2/test/v21/test_pattern_expressions.py::test_invalid_integer_constant", "stix2/test/v21/test_pattern_expressions.py::test_invalid_timestamp_constant", "stix2/test/v21/test_pattern_expressions.py::test_invalid_float_constant", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[True-True0]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[False-False0]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[True-True1]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[False-False1]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[true-True]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[false-False]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[t-True]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[f-False]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[T-True]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[F-False]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[1-True]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[0-False]", "stix2/test/v21/test_pattern_expressions.py::test_invalid_boolean_constant", "stix2/test/v21/test_pattern_expressions.py::test_invalid_hash_constant[MD5-zzz]", "stix2/test/v21/test_pattern_expressions.py::test_invalid_hash_constant[SSDEEP-zzz==]", "stix2/test/v21/test_pattern_expressions.py::test_invalid_hex_constant", "stix2/test/v21/test_pattern_expressions.py::test_invalid_binary_constant", "stix2/test/v21/test_pattern_expressions.py::test_escape_quotes_and_backslashes", "stix2/test/v21/test_pattern_expressions.py::test_like", "stix2/test/v21/test_pattern_expressions.py::test_issuperset", "stix2/test/v21/test_pattern_expressions.py::test_repeat_qualifier", "stix2/test/v21/test_pattern_expressions.py::test_invalid_repeat_qualifier", "stix2/test/v21/test_pattern_expressions.py::test_invalid_within_qualifier", "stix2/test/v21/test_pattern_expressions.py::test_startstop_qualifier", "stix2/test/v21/test_pattern_expressions.py::test_invalid_startstop_qualifier", "stix2/test/v21/test_pattern_expressions.py::test_make_constant_already_a_constant", "stix2/test/v21/test_pattern_expressions.py::test_parsing_comparison_expression", "stix2/test/v21/test_pattern_expressions.py::test_parsing_repeat_and_within_qualified_expression", "stix2/test/v21/test_pattern_expressions.py::test_parsing_start_stop_qualified_expression", "stix2/test/v21/test_pattern_expressions.py::test_list_constant", "stix2/test/v21/test_pattern_expressions.py::test_parsing_boolean", "stix2/test/v21/test_pattern_expressions.py::test_parsing_multiple_slashes_quotes", "stix2/test/v21/test_pattern_expressions.py::test_parse_error" ]
2020-05-13 22:20:13+00:00
4,301
oasis-open__cti-python-stix2-402
diff --git a/stix2/base.py b/stix2/base.py index ef3fcb8..7336285 100644 --- a/stix2/base.py +++ b/stix2/base.py @@ -334,23 +334,20 @@ class _Observable(_STIXBase): def __init__(self, **kwargs): # the constructor might be called independently of an observed data object self._STIXBase__valid_refs = kwargs.pop('_valid_refs', []) - - self._allow_custom = kwargs.get('allow_custom', False) self._properties['extensions'].allow_custom = kwargs.get('allow_custom', False) + super(_Observable, self).__init__(**kwargs) - try: - # Since `spec_version` is optional, this is how we check for a 2.1 SCO - self._id_contributing_properties + if 'id' not in kwargs and not isinstance(self, stix2.v20._Observable): + # Specific to 2.1+ observables: generate a deterministic ID + id_ = self._generate_id() - if 'id' not in kwargs: - possible_id = self._generate_id(kwargs) - if possible_id is not None: - kwargs['id'] = possible_id - except AttributeError: - # End up here if handling a 2.0 SCO, and don't need to do anything further - pass - - super(_Observable, self).__init__(**kwargs) + # Spec says fall back to UUIDv4 if no contributing properties were + # given. That's what already happened (the following is actually + # overwriting the default uuidv4), so nothing to do here. + if id_ is not None: + # Can't assign to self (we're immutable), so slip the ID in + # more sneakily. + self._inner["id"] = id_ def _check_ref(self, ref, prop, prop_name): """ @@ -396,42 +393,53 @@ class _Observable(_STIXBase): for ref in kwargs[prop_name]: self._check_ref(ref, prop, prop_name) - def _generate_id(self, kwargs): - required_prefix = self._type + "--" - - properties_to_use = self._id_contributing_properties - if properties_to_use: - streamlined_object = {} - if "hashes" in kwargs and "hashes" in properties_to_use: - possible_hash = _choose_one_hash(kwargs["hashes"]) - if possible_hash: - streamlined_object["hashes"] = possible_hash - for key in properties_to_use: - if key != "hashes" and key in kwargs: - if isinstance(kwargs[key], dict) or isinstance(kwargs[key], _STIXBase): - temp_deep_copy = copy.deepcopy(dict(kwargs[key])) - _recursive_stix_to_dict(temp_deep_copy) - streamlined_object[key] = temp_deep_copy - elif isinstance(kwargs[key], list): - temp_deep_copy = copy.deepcopy(kwargs[key]) - _recursive_stix_list_to_dict(temp_deep_copy) - streamlined_object[key] = temp_deep_copy - else: - streamlined_object[key] = kwargs[key] - if streamlined_object: - data = canonicalize(streamlined_object, utf8=False) - - # The situation is complicated w.r.t. python 2/3 behavior, so - # I'd rather not rely on particular exceptions being raised to - # determine what to do. Better to just check the python version - # directly. - if six.PY3: - return required_prefix + six.text_type(uuid.uuid5(SCO_DET_ID_NAMESPACE, data)) + def _generate_id(self): + """ + Generate a UUIDv5 for this observable, using its "ID contributing + properties". + + :return: The ID, or None if no ID contributing properties are set + """ + + id_ = None + json_serializable_object = {} + + for key in self._id_contributing_properties: + + if key in self: + obj_value = self[key] + + if key == "hashes": + serializable_value = _choose_one_hash(obj_value) + + if serializable_value is None: + raise InvalidValueError( + self, key, "No hashes given", + ) + else: - return required_prefix + six.text_type(uuid.uuid5(SCO_DET_ID_NAMESPACE, data.encode("utf-8"))) + serializable_value = _make_json_serializable(obj_value) - # We return None if there are no values specified for any of the id-contributing-properties - return None + json_serializable_object[key] = serializable_value + + if json_serializable_object: + + data = canonicalize(json_serializable_object, utf8=False) + + # The situation is complicated w.r.t. python 2/3 behavior, so + # I'd rather not rely on particular exceptions being raised to + # determine what to do. Better to just check the python version + # directly. + if six.PY3: + uuid_ = uuid.uuid5(SCO_DET_ID_NAMESPACE, data) + else: + uuid_ = uuid.uuid5( + SCO_DET_ID_NAMESPACE, data.encode("utf-8"), + ) + + id_ = "{}--{}".format(self._type, six.text_type(uuid_)) + + return id_ class _Extension(_STIXBase): @@ -455,35 +463,100 @@ def _choose_one_hash(hash_dict): if k is not None: return {k: hash_dict[k]} + return None + def _cls_init(cls, obj, kwargs): if getattr(cls, '__init__', object.__init__) is not object.__init__: cls.__init__(obj, **kwargs) -def _recursive_stix_to_dict(input_dict): - for key in input_dict: - if isinstance(input_dict[key], dict): - _recursive_stix_to_dict(input_dict[key]) - elif isinstance(input_dict[key], _STIXBase): - input_dict[key] = dict(input_dict[key]) +def _make_json_serializable(value): + """ + Make the given value JSON-serializable; required for the JSON canonicalizer + to work. This recurses into lists/dicts, converts stix objects to dicts, + etc. "Convenience" types this library uses as property values are + JSON-serialized to produce a JSON-serializable value. (So you will always + get strings for those.) + + The conversion will not affect the passed in value. + + :param value: The value to make JSON-serializable. + :return: The JSON-serializable value. + :raises ValueError: If value is None (since nulls are not allowed in STIX + objects). + """ + if value is None: + raise ValueError("Illegal null value found in a STIX object") + + json_value = value # default assumption + + if isinstance(value, Mapping): + json_value = { + k: _make_json_serializable(v) + for k, v in value.items() + } + + elif isinstance(value, list): + json_value = [ + _make_json_serializable(v) + for v in value + ] + + elif not isinstance(value, (int, float, six.string_types, bool)): + # If a "simple" value which is not already JSON-serializable, + # JSON-serialize to a string and use that as our JSON-serializable + # value. This applies to our datetime objects currently (timestamp + # properties), and could apply to any other "convenience" types this + # library uses for property values in the future. + json_value = json.dumps(value, ensure_ascii=False, cls=STIXJSONEncoder) + + # If it looks like a string literal was output, strip off the quotes. + # Otherwise, a second pair will be added when it's canonicalized. Also + # to be extra safe, we need to unescape. + if len(json_value) >= 2 and \ + json_value[0] == '"' and json_value[-1] == '"': + json_value = _un_json_escape(json_value[1:-1]) + + return json_value + + +_JSON_ESCAPE_RE = re.compile(r"\\.") +# I don't think I should need to worry about the unicode escapes (\uXXXX) +# since I use ensure_ascii=False when generating it. I will just fix all +# the other escapes, e.g. \n, \r, etc. +# +# This list is taken from RFC8259 section 7: +# https://tools.ietf.org/html/rfc8259#section-7 +# Maps the second char of a "\X" style escape, to a replacement char +_JSON_ESCAPE_MAP = { + '"': '"', + "\\": "\\", + "/": "/", + "b": "\b", + "f": "\f", + "n": "\n", + "r": "\r", + "t": "\t" +} +def _un_json_escape(json_string): + """ + Removes JSON string literal escapes. We should undo these things Python's + serializer does, so we can ensure they're done canonically. The + canonicalizer should be in charge of everything, as much as is feasible. - # There may stil be nested _STIXBase objects - _recursive_stix_to_dict(input_dict[key]) - elif isinstance(input_dict[key], list): - _recursive_stix_list_to_dict(input_dict[key]) - else: - pass + :param json_string: String literal output of Python's JSON serializer, + minus the surrounding quotes. + :return: The unescaped string + """ + def replace(m): + replacement = _JSON_ESCAPE_MAP.get(m.group(0)[1]) + if replacement is None: + raise ValueError("Unrecognized JSON escape: " + m.group(0)) -def _recursive_stix_list_to_dict(input_list): - for i in range(len(input_list)): - if isinstance(input_list[i], _STIXBase): - input_list[i] = dict(input_list[i]) - elif isinstance(input_list[i], dict): - pass - elif isinstance(input_list[i], list): - _recursive_stix_list_to_dict(input_list[i]) - else: - continue - _recursive_stix_to_dict(input_list[i]) + return replacement + + result = _JSON_ESCAPE_RE.sub(replace, json_string) + + return result
oasis-open/cti-python-stix2
41525f9be08eea163ee3b88cb9b30b82f9c66ff2
diff --git a/stix2/test/v21/test_deterministic_ids.py b/stix2/test/v21/test_deterministic_ids.py new file mode 100644 index 0000000..da72142 --- /dev/null +++ b/stix2/test/v21/test_deterministic_ids.py @@ -0,0 +1,337 @@ +from collections import OrderedDict +import datetime +import uuid + +import pytest +import six + +import stix2.base +import stix2.canonicalization.Canonicalize +import stix2.exceptions +from stix2.properties import ( + BooleanProperty, DictionaryProperty, EmbeddedObjectProperty, + ExtensionsProperty, FloatProperty, HashesProperty, IDProperty, + IntegerProperty, ListProperty, StringProperty, TimestampProperty, + TypeProperty, +) +import stix2.v21 + +SCO_DET_ID_NAMESPACE = uuid.UUID("00abedb4-aa42-466c-9c01-fed23315a9b7") + + +def _uuid_from_id(id_): + dd_idx = id_.index("--") + uuid_str = id_[dd_idx+2:] + uuid_ = uuid.UUID(uuid_str) + + return uuid_ + + +def _make_uuid5(name): + """ + Make a STIX 2.1+ compliant UUIDv5 from a "name". + """ + if six.PY3: + uuid_ = uuid.uuid5(SCO_DET_ID_NAMESPACE, name) + else: + uuid_ = uuid.uuid5( + SCO_DET_ID_NAMESPACE, name.encode("utf-8"), + ) + + return uuid_ + + +def test_no_contrib_props_defined(): + + class SomeSCO(stix2.v21._Observable): + _type = "some-sco" + _properties = OrderedDict(( + ('type', TypeProperty(_type, spec_version='2.1')), + ('id', IDProperty(_type, spec_version='2.1')), + ( + 'extensions', ExtensionsProperty( + spec_version='2.1', enclosing_type=_type, + ), + ), + )) + _id_contributing_properties = [] + + sco = SomeSCO() + uuid_ = _uuid_from_id(sco["id"]) + + assert uuid_.variant == uuid.RFC_4122 + assert uuid_.version == 4 + + +def test_json_compatible_prop_values(): + class SomeSCO(stix2.v21._Observable): + _type = "some-sco" + _properties = OrderedDict(( + ('type', TypeProperty(_type, spec_version='2.1')), + ('id', IDProperty(_type, spec_version='2.1')), + ( + 'extensions', ExtensionsProperty( + spec_version='2.1', enclosing_type=_type, + ), + ), + ('string', StringProperty()), + ('int', IntegerProperty()), + ('float', FloatProperty()), + ('bool', BooleanProperty()), + ('list', ListProperty(IntegerProperty())), + ('dict', DictionaryProperty(spec_version="2.1")), + )) + _id_contributing_properties = [ + 'string', 'int', 'float', 'bool', 'list', 'dict', + ] + + obj = { + "string": "abc", + "int": 1, + "float": 1.5, + "bool": True, + "list": [1, 2, 3], + "dict": {"a": 1, "b": [2], "c": "three"}, + } + + sco = SomeSCO(**obj) + + can_json = stix2.canonicalization.Canonicalize.canonicalize(obj, utf8=False) + expected_uuid5 = _make_uuid5(can_json) + actual_uuid5 = _uuid_from_id(sco["id"]) + + assert actual_uuid5 == expected_uuid5 + + +def test_json_incompatible_timestamp_value(): + class SomeSCO(stix2.v21._Observable): + _type = "some-sco" + _properties = OrderedDict(( + ('type', TypeProperty(_type, spec_version='2.1')), + ('id', IDProperty(_type, spec_version='2.1')), + ( + 'extensions', ExtensionsProperty( + spec_version='2.1', enclosing_type=_type, + ), + ), + ('timestamp', TimestampProperty()), + )) + _id_contributing_properties = ['timestamp'] + + ts = datetime.datetime(1987, 1, 2, 3, 4, 5, 678900) + + sco = SomeSCO(timestamp=ts) + + obj = { + "timestamp": "1987-01-02T03:04:05.6789Z", + } + + can_json = stix2.canonicalization.Canonicalize.canonicalize(obj, utf8=False) + expected_uuid5 = _make_uuid5(can_json) + actual_uuid5 = _uuid_from_id(sco["id"]) + + assert actual_uuid5 == expected_uuid5 + + +def test_embedded_object(): + class SubObj(stix2.base._STIXBase): + _type = "sub-object" + _properties = OrderedDict(( + ('value', StringProperty()), + )) + + class SomeSCO(stix2.v21._Observable): + _type = "some-sco" + _properties = OrderedDict(( + ('type', TypeProperty(_type, spec_version='2.1')), + ('id', IDProperty(_type, spec_version='2.1')), + ( + 'extensions', ExtensionsProperty( + spec_version='2.1', enclosing_type=_type, + ), + ), + ('sub_obj', EmbeddedObjectProperty(type=SubObj)), + )) + _id_contributing_properties = ['sub_obj'] + + sub_obj = SubObj(value="foo") + sco = SomeSCO(sub_obj=sub_obj) + + obj = { + "sub_obj": { + "value": "foo", + }, + } + + can_json = stix2.canonicalization.Canonicalize.canonicalize(obj, utf8=False) + expected_uuid5 = _make_uuid5(can_json) + actual_uuid5 = _uuid_from_id(sco["id"]) + + assert actual_uuid5 == expected_uuid5 + + +def test_empty_hash(): + class SomeSCO(stix2.v21._Observable): + _type = "some-sco" + _properties = OrderedDict(( + ('type', TypeProperty(_type, spec_version='2.1')), + ('id', IDProperty(_type, spec_version='2.1')), + ( + 'extensions', ExtensionsProperty( + spec_version='2.1', enclosing_type=_type, + ), + ), + ('hashes', HashesProperty()), + )) + _id_contributing_properties = ['hashes'] + + with pytest.raises(stix2.exceptions.InvalidValueError): + SomeSCO(hashes={}) + + [email protected]("json_escaped, expected_unescaped", [ + ("", ""), + ("a", "a"), + (r"\n", "\n"), + (r"\n\r\b\t\\\/\"", "\n\r\b\t\\/\""), + (r"\\n", r"\n"), + (r"\\\n", "\\\n") +]) +def test_json_unescaping(json_escaped, expected_unescaped): + actual_unescaped = stix2.base._un_json_escape(json_escaped) + assert actual_unescaped == expected_unescaped + + +def test_json_unescaping_bad_escape(): + with pytest.raises(ValueError): + stix2.base._un_json_escape(r"\x") + + +def test_deterministic_id_same_extra_prop_vals(): + email_addr_1 = stix2.v21.EmailAddress( + value="[email protected]", + display_name="Johnny Doe", + ) + + email_addr_2 = stix2.v21.EmailAddress( + value="[email protected]", + display_name="Johnny Doe", + ) + + assert email_addr_1.id == email_addr_2.id + + uuid_obj_1 = uuid.UUID(email_addr_1.id[-36:]) + assert uuid_obj_1.variant == uuid.RFC_4122 + assert uuid_obj_1.version == 5 + + uuid_obj_2 = uuid.UUID(email_addr_2.id[-36:]) + assert uuid_obj_2.variant == uuid.RFC_4122 + assert uuid_obj_2.version == 5 + + +def test_deterministic_id_diff_extra_prop_vals(): + email_addr_1 = stix2.v21.EmailAddress( + value="[email protected]", + display_name="Johnny Doe", + ) + + email_addr_2 = stix2.v21.EmailAddress( + value="[email protected]", + display_name="Janey Doe", + ) + + assert email_addr_1.id == email_addr_2.id + + uuid_obj_1 = uuid.UUID(email_addr_1.id[-36:]) + assert uuid_obj_1.variant == uuid.RFC_4122 + assert uuid_obj_1.version == 5 + + uuid_obj_2 = uuid.UUID(email_addr_2.id[-36:]) + assert uuid_obj_2.variant == uuid.RFC_4122 + assert uuid_obj_2.version == 5 + + +def test_deterministic_id_diff_contributing_prop_vals(): + email_addr_1 = stix2.v21.EmailAddress( + value="[email protected]", + display_name="Johnny Doe", + ) + + email_addr_2 = stix2.v21.EmailAddress( + value="[email protected]", + display_name="Janey Doe", + ) + + assert email_addr_1.id != email_addr_2.id + + uuid_obj_1 = uuid.UUID(email_addr_1.id[-36:]) + assert uuid_obj_1.variant == uuid.RFC_4122 + assert uuid_obj_1.version == 5 + + uuid_obj_2 = uuid.UUID(email_addr_2.id[-36:]) + assert uuid_obj_2.variant == uuid.RFC_4122 + assert uuid_obj_2.version == 5 + + +def test_deterministic_id_no_contributing_props(): + email_msg_1 = stix2.v21.EmailMessage( + is_multipart=False, + ) + + email_msg_2 = stix2.v21.EmailMessage( + is_multipart=False, + ) + + assert email_msg_1.id != email_msg_2.id + + uuid_obj_1 = uuid.UUID(email_msg_1.id[-36:]) + assert uuid_obj_1.variant == uuid.RFC_4122 + assert uuid_obj_1.version == 4 + + uuid_obj_2 = uuid.UUID(email_msg_2.id[-36:]) + assert uuid_obj_2.variant == uuid.RFC_4122 + assert uuid_obj_2.version == 4 + + +def test_id_gen_recursive_dict_conversion_1(): + file_observable = stix2.v21.File( + name="example.exe", + size=68 * 1000, + magic_number_hex="50000000", + hashes={ + "SHA-256": "841a8921140aba50671ebb0770fecc4ee308c4952cfeff8de154ab14eeef4649", + }, + extensions={ + "windows-pebinary-ext": stix2.v21.WindowsPEBinaryExt( + pe_type="exe", + machine_hex="014c", + sections=[ + stix2.v21.WindowsPESection( + name=".data", + size=4096, + entropy=7.980693, + hashes={"SHA-256": "6e3b6f3978e5cd96ba7abee35c24e867b7e64072e2ecb22d0ee7a6e6af6894d0"}, + ), + ], + ), + }, + ) + + assert file_observable.id == "file--ced31cd4-bdcb-537d-aefa-92d291bfc11d" + + +def test_id_gen_recursive_dict_conversion_2(): + wrko = stix2.v21.WindowsRegistryKey( + values=[ + stix2.v21.WindowsRegistryValueType( + name="Foo", + data="qwerty", + ), + stix2.v21.WindowsRegistryValueType( + name="Bar", + data="42", + ), + ], + ) + + assert wrko.id == "windows-registry-key--36594eba-bcc7-5014-9835-0e154264e588" diff --git a/stix2/test/v21/test_observed_data.py b/stix2/test/v21/test_observed_data.py index c13148a..ceca8f1 100644 --- a/stix2/test/v21/test_observed_data.py +++ b/stix2/test/v21/test_observed_data.py @@ -1469,133 +1469,3 @@ def test_objects_deprecation(): }, }, ) - - -def test_deterministic_id_same_extra_prop_vals(): - email_addr_1 = stix2.v21.EmailAddress( - value="[email protected]", - display_name="Johnny Doe", - ) - - email_addr_2 = stix2.v21.EmailAddress( - value="[email protected]", - display_name="Johnny Doe", - ) - - assert email_addr_1.id == email_addr_2.id - - uuid_obj_1 = uuid.UUID(email_addr_1.id[-36:]) - assert uuid_obj_1.variant == uuid.RFC_4122 - assert uuid_obj_1.version == 5 - - uuid_obj_2 = uuid.UUID(email_addr_2.id[-36:]) - assert uuid_obj_2.variant == uuid.RFC_4122 - assert uuid_obj_2.version == 5 - - -def test_deterministic_id_diff_extra_prop_vals(): - email_addr_1 = stix2.v21.EmailAddress( - value="[email protected]", - display_name="Johnny Doe", - ) - - email_addr_2 = stix2.v21.EmailAddress( - value="[email protected]", - display_name="Janey Doe", - ) - - assert email_addr_1.id == email_addr_2.id - - uuid_obj_1 = uuid.UUID(email_addr_1.id[-36:]) - assert uuid_obj_1.variant == uuid.RFC_4122 - assert uuid_obj_1.version == 5 - - uuid_obj_2 = uuid.UUID(email_addr_2.id[-36:]) - assert uuid_obj_2.variant == uuid.RFC_4122 - assert uuid_obj_2.version == 5 - - -def test_deterministic_id_diff_contributing_prop_vals(): - email_addr_1 = stix2.v21.EmailAddress( - value="[email protected]", - display_name="Johnny Doe", - ) - - email_addr_2 = stix2.v21.EmailAddress( - value="[email protected]", - display_name="Janey Doe", - ) - - assert email_addr_1.id != email_addr_2.id - - uuid_obj_1 = uuid.UUID(email_addr_1.id[-36:]) - assert uuid_obj_1.variant == uuid.RFC_4122 - assert uuid_obj_1.version == 5 - - uuid_obj_2 = uuid.UUID(email_addr_2.id[-36:]) - assert uuid_obj_2.variant == uuid.RFC_4122 - assert uuid_obj_2.version == 5 - - -def test_deterministic_id_no_contributing_props(): - email_msg_1 = stix2.v21.EmailMessage( - is_multipart=False, - ) - - email_msg_2 = stix2.v21.EmailMessage( - is_multipart=False, - ) - - assert email_msg_1.id != email_msg_2.id - - uuid_obj_1 = uuid.UUID(email_msg_1.id[-36:]) - assert uuid_obj_1.variant == uuid.RFC_4122 - assert uuid_obj_1.version == 4 - - uuid_obj_2 = uuid.UUID(email_msg_2.id[-36:]) - assert uuid_obj_2.variant == uuid.RFC_4122 - assert uuid_obj_2.version == 4 - - -def test_id_gen_recursive_dict_conversion_1(): - file_observable = stix2.v21.File( - name="example.exe", - size=68 * 1000, - magic_number_hex="50000000", - hashes={ - "SHA-256": "841a8921140aba50671ebb0770fecc4ee308c4952cfeff8de154ab14eeef4649", - }, - extensions={ - "windows-pebinary-ext": stix2.v21.WindowsPEBinaryExt( - pe_type="exe", - machine_hex="014c", - sections=[ - stix2.v21.WindowsPESection( - name=".data", - size=4096, - entropy=7.980693, - hashes={"SHA-256": "6e3b6f3978e5cd96ba7abee35c24e867b7e64072e2ecb22d0ee7a6e6af6894d0"}, - ), - ], - ), - }, - ) - - assert file_observable.id == "file--ced31cd4-bdcb-537d-aefa-92d291bfc11d" - - -def test_id_gen_recursive_dict_conversion_2(): - wrko = stix2.v21.WindowsRegistryKey( - values=[ - stix2.v21.WindowsRegistryValueType( - name="Foo", - data="qwerty", - ), - stix2.v21.WindowsRegistryValueType( - name="Bar", - data="42", - ), - ], - ) - - assert wrko.id == "windows-registry-key--36594eba-bcc7-5014-9835-0e154264e588"
`CustomExtension`s for `File` with `TimestampProperty`s can't handle `datetime` objects STIX 2.1 File SCOs require that their extensions be considered when generating deterministic UUIDs, serialised following JSON canonicalisation rules. Defining a `CustomExtension` for `Files` that include a timestamp property results in exceptions being raised when that property is provided as a `datetime` object rather than a Zulu formatted datestamp string. The following snippet demonstrates the issue: ```py import datetime import pprint import stix2.v21 import stix2.properties @stix2.v21.CustomExtension(stix2.v21.File, "x-xtime-ext", ( ("xtime", stix2.properties.TimestampProperty(), ), )) class XTimeExtension(): pass try: f = stix2.v21.File( name="foo", extensions={"x-xtime-ext": {"xtime": datetime.datetime.utcnow()}, }, ) except Exception as exc: print(exc) else: raise Exception("That should have failed...") f = stix2.v21.File( name="foo", extensions={"x-xtime-ext": {"xtime": str(datetime.datetime.utcnow())}, }, ) s = f.serialize() pprint.pprint(s) stix2.parse(s) f = stix2.parse(""" {"type": "file", "spec_version": "2.1", "name": "foo", "extensions": { "x-xtime-ext": {"xtime": "1970-01-01T00:00:00Z"} } } """) print(f) ``` Presumably the fix would involve teaching `_Observable._generate_id()` to use a `STIXJSONEncoder` rather than just calling `stix2.canonicalization.Canonicalize.canonicalization()` which uses the default `JSONEncoder` implementation.
0.0
[ "stix2/test/v21/test_deterministic_ids.py::test_json_incompatible_timestamp_value", "stix2/test/v21/test_deterministic_ids.py::test_json_unescaping[-]", "stix2/test/v21/test_deterministic_ids.py::test_json_unescaping[a-a]", "stix2/test/v21/test_deterministic_ids.py::test_json_unescaping[\\\\n-\\n]", "stix2/test/v21/test_deterministic_ids.py::test_json_unescaping[\\\\n\\\\r\\\\b\\\\t\\\\\\\\\\\\/\\\\\"-\\n\\r\\x08\\t\\\\/\"]", "stix2/test/v21/test_deterministic_ids.py::test_json_unescaping[\\\\\\\\n-\\\\n]", "stix2/test/v21/test_deterministic_ids.py::test_json_unescaping[\\\\\\\\\\\\n-\\\\\\n]", "stix2/test/v21/test_deterministic_ids.py::test_json_unescaping_bad_escape" ]
[ "stix2/test/v21/test_deterministic_ids.py::test_no_contrib_props_defined", "stix2/test/v21/test_deterministic_ids.py::test_json_compatible_prop_values", "stix2/test/v21/test_deterministic_ids.py::test_embedded_object", "stix2/test/v21/test_deterministic_ids.py::test_empty_hash", "stix2/test/v21/test_deterministic_ids.py::test_deterministic_id_same_extra_prop_vals", "stix2/test/v21/test_deterministic_ids.py::test_deterministic_id_diff_extra_prop_vals", "stix2/test/v21/test_deterministic_ids.py::test_deterministic_id_diff_contributing_prop_vals", "stix2/test/v21/test_deterministic_ids.py::test_deterministic_id_no_contributing_props", "stix2/test/v21/test_deterministic_ids.py::test_id_gen_recursive_dict_conversion_1", "stix2/test/v21/test_deterministic_ids.py::test_id_gen_recursive_dict_conversion_2", "stix2/test/v21/test_observed_data.py::test_observed_data_example", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_refs", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_object_refs", "stix2/test/v21/test_observed_data.py::test_observed_data_object_constraint", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_bad_refs", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_non_dictionary", "stix2/test/v21/test_observed_data.py::test_observed_data_example_with_empty_dictionary", "stix2/test/v21/test_observed_data.py::test_parse_observed_data[{\\n", "stix2/test/v21/test_observed_data.py::test_parse_observed_data[data1]", "stix2/test/v21/test_observed_data.py::test_parse_artifact_valid[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_artifact_invalid[\"0\":", "stix2/test/v21/test_observed_data.py::test_artifact_example_dependency_error", "stix2/test/v21/test_observed_data.py::test_parse_autonomous_system_valid[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_email_address[{\\n", "stix2/test/v21/test_observed_data.py::test_parse_email_message[\\n", "stix2/test/v21/test_observed_data.py::test_parse_email_message_not_multipart[\\n", "stix2/test/v21/test_observed_data.py::test_parse_file_archive[\"0\":", "stix2/test/v21/test_observed_data.py::test_parse_email_message_with_at_least_one_error[\\n", "stix2/test/v21/test_observed_data.py::test_parse_basic_tcp_traffic[\\n", "stix2/test/v21/test_observed_data.py::test_parse_basic_tcp_traffic_with_error[\\n", "stix2/test/v21/test_observed_data.py::test_observed_data_with_process_example", "stix2/test/v21/test_observed_data.py::test_artifact_example", "stix2/test/v21/test_observed_data.py::test_artifact_mutual_exclusion_error", "stix2/test/v21/test_observed_data.py::test_directory_example", "stix2/test/v21/test_observed_data.py::test_directory_example_ref_error", "stix2/test/v21/test_observed_data.py::test_domain_name_example", "stix2/test/v21/test_observed_data.py::test_domain_name_example_invalid_ref_type", "stix2/test/v21/test_observed_data.py::test_file_example", "stix2/test/v21/test_observed_data.py::test_file_ssdeep_example", "stix2/test/v21/test_observed_data.py::test_file_example_with_NTFSExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_empty_NTFSExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_PDFExt", "stix2/test/v21/test_observed_data.py::test_file_example_with_PDFExt_Object", "stix2/test/v21/test_observed_data.py::test_file_example_with_RasterImageExt_Object", "stix2/test/v21/test_observed_data.py::test_raster_image_ext_parse", "stix2/test/v21/test_observed_data.py::test_raster_images_ext_create", "stix2/test/v21/test_observed_data.py::test_file_example_with_WindowsPEBinaryExt", "stix2/test/v21/test_observed_data.py::test_file_example_encryption_error", "stix2/test/v21/test_observed_data.py::test_ipv4_address_example", "stix2/test/v21/test_observed_data.py::test_ipv4_address_valid_refs", "stix2/test/v21/test_observed_data.py::test_ipv4_address_example_cidr", "stix2/test/v21/test_observed_data.py::test_ipv6_address_example", "stix2/test/v21/test_observed_data.py::test_mac_address_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_http_request_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_icmp_example", "stix2/test/v21/test_observed_data.py::test_network_traffic_socket_example", "stix2/test/v21/test_observed_data.py::test_correct_socket_options", "stix2/test/v21/test_observed_data.py::test_incorrect_socket_options", "stix2/test/v21/test_observed_data.py::test_network_traffic_tcp_example", "stix2/test/v21/test_observed_data.py::test_mutex_example", "stix2/test/v21/test_observed_data.py::test_process_example", "stix2/test/v21/test_observed_data.py::test_process_example_empty_error", "stix2/test/v21/test_observed_data.py::test_process_example_empty_with_extensions", "stix2/test/v21/test_observed_data.py::test_process_example_windows_process_ext", "stix2/test/v21/test_observed_data.py::test_process_example_windows_process_ext_empty", "stix2/test/v21/test_observed_data.py::test_process_example_extensions_empty", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsProcessExt_Object", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsServiceExt", "stix2/test/v21/test_observed_data.py::test_process_example_with_WindowsProcessServiceExt", "stix2/test/v21/test_observed_data.py::test_software_example", "stix2/test/v21/test_observed_data.py::test_url_example", "stix2/test/v21/test_observed_data.py::test_user_account_example", "stix2/test/v21/test_observed_data.py::test_user_account_unix_account_ext_example", "stix2/test/v21/test_observed_data.py::test_windows_registry_key_example", "stix2/test/v21/test_observed_data.py::test_x509_certificate_example", "stix2/test/v21/test_observed_data.py::test_x509_certificate_error", "stix2/test/v21/test_observed_data.py::test_new_version_with_related_objects", "stix2/test/v21/test_observed_data.py::test_objects_deprecation" ]
2020-06-02 18:53:53+00:00
4,302
oasis-open__cti-python-stix2-407
diff --git a/stix2/properties.py b/stix2/properties.py index c876c11..a267eb5 100644 --- a/stix2/properties.py +++ b/stix2/properties.py @@ -537,7 +537,7 @@ def enumerate_types(types, spec_version): return return_types -SELECTOR_REGEX = re.compile(r"^[a-z0-9_-]{3,250}(\.(\[\d+\]|[a-z0-9_-]{1,250}))*$") +SELECTOR_REGEX = re.compile(r"^([a-z0-9_-]{3,250}(\.(\[\d+\]|[a-z0-9_-]{1,250}))*|id)$") class SelectorProperty(Property):
oasis-open/cti-python-stix2
6faf6b9fa1bfe65250ac07eaab322ff0f4be6d59
diff --git a/stix2/test/v20/test_granular_markings.py b/stix2/test/v20/test_granular_markings.py index e912cc1..ae2da3b 100644 --- a/stix2/test/v20/test_granular_markings.py +++ b/stix2/test/v20/test_granular_markings.py @@ -1089,3 +1089,17 @@ def test_clear_marking_not_present(data): """Test clearing markings for a selector that has no associated markings.""" with pytest.raises(MarkingNotFoundError): data = markings.clear_markings(data, ["labels"]) + + +def test_set_marking_on_id_property(): + malware = Malware( + granular_markings=[ + { + "selectors": ["id"], + "marking_ref": MARKING_IDS[0], + }, + ], + **MALWARE_KWARGS + ) + + assert "id" in malware["granular_markings"][0]["selectors"] diff --git a/stix2/test/v21/test_granular_markings.py b/stix2/test/v21/test_granular_markings.py index 1c3194b..ff8fe26 100644 --- a/stix2/test/v21/test_granular_markings.py +++ b/stix2/test/v21/test_granular_markings.py @@ -1307,3 +1307,17 @@ def test_clear_marking_not_present(data): """Test clearing markings for a selector that has no associated markings.""" with pytest.raises(MarkingNotFoundError): markings.clear_markings(data, ["malware_types"]) + + +def test_set_marking_on_id_property(): + malware = Malware( + granular_markings=[ + { + "selectors": ["id"], + "marking_ref": MARKING_IDS[0], + }, + ], + **MALWARE_KWARGS + ) + + assert "id" in malware["granular_markings"][0]["selectors"]
Placing GranularMarking on id property causes ValueError https://github.com/oasis-open/cti-python-stix2/blob/6faf6b9fa1bfe65250ac07eaab322ff0f4be6d59/stix2/properties.py#L540 ``` Traceback (most recent call last): File "C:\Users\user-1\cti-python-stix2\stix2\base.py", line 104, in _check_property kwargs[prop_name] = prop.clean(kwargs[prop_name]) File "C:\Users\user-1\cti-python-stix2\stix2\properties.py", line 216, in clean valid = self.contained.clean(item) File "C:\Users\user-1\cti-python-stix2\stix2\properties.py", line 547, in clean raise ValueError("must adhere to selector syntax.") ValueError: must adhere to selector syntax. ```
0.0
[ "stix2/test/v20/test_granular_markings.py::test_set_marking_on_id_property", "stix2/test/v21/test_granular_markings.py::test_set_marking_on_id_property" ]
[ "stix2/test/v20/test_granular_markings.py::test_add_marking_mark_one_selector_multiple_refs", "stix2/test/v20/test_granular_markings.py::test_add_marking_mark_multiple_selector_one_refs[data0]", "stix2/test/v20/test_granular_markings.py::test_add_marking_mark_multiple_selector_one_refs[data1]", "stix2/test/v20/test_granular_markings.py::test_add_marking_mark_multiple_selector_one_refs[data2]", "stix2/test/v20/test_granular_markings.py::test_add_marking_mark_multiple_selector_multiple_refs", "stix2/test/v20/test_granular_markings.py::test_add_marking_mark_another_property_same_marking", "stix2/test/v20/test_granular_markings.py::test_add_marking_mark_same_property_same_marking", "stix2/test/v20/test_granular_markings.py::test_add_marking_bad_selector[data0-marking0]", "stix2/test/v20/test_granular_markings.py::test_get_markings_smoke[data0]", "stix2/test/v20/test_granular_markings.py::test_get_markings_not_marked[data0]", "stix2/test/v20/test_granular_markings.py::test_get_markings_not_marked[data1]", "stix2/test/v20/test_granular_markings.py::test_get_markings_multiple_selectors[data0]", "stix2/test/v20/test_granular_markings.py::test_get_markings_bad_selector[data0-foo]", "stix2/test/v20/test_granular_markings.py::test_get_markings_bad_selector[data1-]", "stix2/test/v20/test_granular_markings.py::test_get_markings_bad_selector[data2-selector2]", "stix2/test/v20/test_granular_markings.py::test_get_markings_bad_selector[data3-selector3]", "stix2/test/v20/test_granular_markings.py::test_get_markings_bad_selector[data4-x.z.[-2]]", "stix2/test/v20/test_granular_markings.py::test_get_markings_bad_selector[data5-c.f]", "stix2/test/v20/test_granular_markings.py::test_get_markings_bad_selector[data6-c.[2].i]", "stix2/test/v20/test_granular_markings.py::test_get_markings_bad_selector[data7-c.[3]]", "stix2/test/v20/test_granular_markings.py::test_get_markings_bad_selector[data8-d]", "stix2/test/v20/test_granular_markings.py::test_get_markings_bad_selector[data9-x.[0]]", "stix2/test/v20/test_granular_markings.py::test_get_markings_bad_selector[data10-z.y.w]", "stix2/test/v20/test_granular_markings.py::test_get_markings_bad_selector[data11-x.z.[1]]", "stix2/test/v20/test_granular_markings.py::test_get_markings_bad_selector[data12-x.z.foo3]", "stix2/test/v20/test_granular_markings.py::test_get_markings_positional_arguments_combinations[data0]", "stix2/test/v20/test_granular_markings.py::test_remove_marking_remove_one_selector_with_multiple_refs[data0]", "stix2/test/v20/test_granular_markings.py::test_remove_marking_remove_one_selector_with_multiple_refs[data1]", "stix2/test/v20/test_granular_markings.py::test_remove_marking_remove_multiple_selector_one_ref", "stix2/test/v20/test_granular_markings.py::test_remove_marking_mark_one_selector_from_multiple_ones", "stix2/test/v20/test_granular_markings.py::test_remove_marking_mark_one_selector_markings_from_multiple_ones", "stix2/test/v20/test_granular_markings.py::test_remove_marking_mark_mutilple_selector_multiple_refs", "stix2/test/v20/test_granular_markings.py::test_remove_marking_mark_another_property_same_marking", "stix2/test/v20/test_granular_markings.py::test_remove_marking_mark_same_property_same_marking", "stix2/test/v20/test_granular_markings.py::test_remove_no_markings", "stix2/test/v20/test_granular_markings.py::test_remove_marking_bad_selector", "stix2/test/v20/test_granular_markings.py::test_remove_marking_not_present", "stix2/test/v20/test_granular_markings.py::test_is_marked_smoke[data0]", "stix2/test/v20/test_granular_markings.py::test_is_marked_smoke[data1]", "stix2/test/v20/test_granular_markings.py::test_is_marked_invalid_selector[data0-foo]", "stix2/test/v20/test_granular_markings.py::test_is_marked_invalid_selector[data1-]", "stix2/test/v20/test_granular_markings.py::test_is_marked_invalid_selector[data2-selector2]", "stix2/test/v20/test_granular_markings.py::test_is_marked_invalid_selector[data3-selector3]", "stix2/test/v20/test_granular_markings.py::test_is_marked_invalid_selector[data4-x.z.[-2]]", "stix2/test/v20/test_granular_markings.py::test_is_marked_invalid_selector[data5-c.f]", "stix2/test/v20/test_granular_markings.py::test_is_marked_invalid_selector[data6-c.[2].i]", "stix2/test/v20/test_granular_markings.py::test_is_marked_invalid_selector[data7-c.[3]]", "stix2/test/v20/test_granular_markings.py::test_is_marked_invalid_selector[data8-d]", "stix2/test/v20/test_granular_markings.py::test_is_marked_invalid_selector[data9-x.[0]]", "stix2/test/v20/test_granular_markings.py::test_is_marked_invalid_selector[data10-z.y.w]", "stix2/test/v20/test_granular_markings.py::test_is_marked_invalid_selector[data11-x.z.[1]]", "stix2/test/v20/test_granular_markings.py::test_is_marked_invalid_selector[data12-x.z.foo3]", "stix2/test/v20/test_granular_markings.py::test_is_marked_mix_selector[data0]", "stix2/test/v20/test_granular_markings.py::test_is_marked_mix_selector[data1]", "stix2/test/v20/test_granular_markings.py::test_is_marked_valid_selector_no_refs[data0]", "stix2/test/v20/test_granular_markings.py::test_is_marked_valid_selector_no_refs[data1]", "stix2/test/v20/test_granular_markings.py::test_is_marked_valid_selector_and_refs[data0]", "stix2/test/v20/test_granular_markings.py::test_is_marked_valid_selector_and_refs[data1]", "stix2/test/v20/test_granular_markings.py::test_is_marked_valid_selector_multiple_refs[data0]", "stix2/test/v20/test_granular_markings.py::test_is_marked_valid_selector_multiple_refs[data1]", "stix2/test/v20/test_granular_markings.py::test_is_marked_no_marking_refs[data0]", "stix2/test/v20/test_granular_markings.py::test_is_marked_no_marking_refs[data1]", "stix2/test/v20/test_granular_markings.py::test_is_marked_no_selectors[data0]", "stix2/test/v20/test_granular_markings.py::test_is_marked_no_selectors[data1]", "stix2/test/v20/test_granular_markings.py::test_is_marked_positional_arguments_combinations", "stix2/test/v20/test_granular_markings.py::test_create_sdo_with_invalid_marking", "stix2/test/v20/test_granular_markings.py::test_set_marking_mark_one_selector_multiple_refs", "stix2/test/v20/test_granular_markings.py::test_set_marking_mark_multiple_selector_one_refs", "stix2/test/v20/test_granular_markings.py::test_set_marking_mark_multiple_selector_multiple_refs_from_none", "stix2/test/v20/test_granular_markings.py::test_set_marking_mark_another_property_same_marking", "stix2/test/v20/test_granular_markings.py::test_set_marking_bad_selector[marking0]", "stix2/test/v20/test_granular_markings.py::test_set_marking_bad_selector[marking1]", "stix2/test/v20/test_granular_markings.py::test_set_marking_bad_selector[marking2]", "stix2/test/v20/test_granular_markings.py::test_set_marking_bad_selector[marking3]", "stix2/test/v20/test_granular_markings.py::test_set_marking_mark_same_property_same_marking", "stix2/test/v20/test_granular_markings.py::test_clear_marking_smoke[data0]", "stix2/test/v20/test_granular_markings.py::test_clear_marking_smoke[data1]", "stix2/test/v20/test_granular_markings.py::test_clear_marking_multiple_selectors[data0]", "stix2/test/v20/test_granular_markings.py::test_clear_marking_multiple_selectors[data1]", "stix2/test/v20/test_granular_markings.py::test_clear_marking_one_selector[data0]", "stix2/test/v20/test_granular_markings.py::test_clear_marking_one_selector[data1]", "stix2/test/v20/test_granular_markings.py::test_clear_marking_all_selectors[data0]", "stix2/test/v20/test_granular_markings.py::test_clear_marking_all_selectors[data1]", "stix2/test/v20/test_granular_markings.py::test_clear_marking_bad_selector[data0-foo]", "stix2/test/v20/test_granular_markings.py::test_clear_marking_bad_selector[data1-]", "stix2/test/v20/test_granular_markings.py::test_clear_marking_bad_selector[data2-selector2]", "stix2/test/v20/test_granular_markings.py::test_clear_marking_bad_selector[data3-selector3]", "stix2/test/v20/test_granular_markings.py::test_clear_marking_not_present[data0]", "stix2/test/v20/test_granular_markings.py::test_clear_marking_not_present[data1]", "stix2/test/v21/test_granular_markings.py::test_add_marking_mark_one_selector_multiple_refs", "stix2/test/v21/test_granular_markings.py::test_add_marking_mark_multiple_selector_one_refs[data0]", "stix2/test/v21/test_granular_markings.py::test_add_marking_mark_multiple_selector_one_refs[data1]", "stix2/test/v21/test_granular_markings.py::test_add_marking_mark_multiple_selector_one_refs[data2]", "stix2/test/v21/test_granular_markings.py::test_add_marking_mark_multiple_selector_multiple_refs", "stix2/test/v21/test_granular_markings.py::test_add_marking_mark_multiple_selector_multiple_refs_mixed", "stix2/test/v21/test_granular_markings.py::test_add_marking_mark_another_property_same_marking", "stix2/test/v21/test_granular_markings.py::test_add_marking_mark_same_property_same_marking", "stix2/test/v21/test_granular_markings.py::test_add_marking_bad_selector[data0-marking0]", "stix2/test/v21/test_granular_markings.py::test_get_markings_smoke[data0]", "stix2/test/v21/test_granular_markings.py::test_get_markings_not_marked[data0]", "stix2/test/v21/test_granular_markings.py::test_get_markings_not_marked[data1]", "stix2/test/v21/test_granular_markings.py::test_get_markings_multiple_selectors[data0]", "stix2/test/v21/test_granular_markings.py::test_get_markings_bad_selector[data0-foo]", "stix2/test/v21/test_granular_markings.py::test_get_markings_bad_selector[data1-]", "stix2/test/v21/test_granular_markings.py::test_get_markings_bad_selector[data2-selector2]", "stix2/test/v21/test_granular_markings.py::test_get_markings_bad_selector[data3-selector3]", "stix2/test/v21/test_granular_markings.py::test_get_markings_bad_selector[data4-x.z.[-2]]", "stix2/test/v21/test_granular_markings.py::test_get_markings_bad_selector[data5-c.f]", "stix2/test/v21/test_granular_markings.py::test_get_markings_bad_selector[data6-c.[2].i]", "stix2/test/v21/test_granular_markings.py::test_get_markings_bad_selector[data7-c.[3]]", "stix2/test/v21/test_granular_markings.py::test_get_markings_bad_selector[data8-d]", "stix2/test/v21/test_granular_markings.py::test_get_markings_bad_selector[data9-x.[0]]", "stix2/test/v21/test_granular_markings.py::test_get_markings_bad_selector[data10-z.y.w]", "stix2/test/v21/test_granular_markings.py::test_get_markings_bad_selector[data11-x.z.[1]]", "stix2/test/v21/test_granular_markings.py::test_get_markings_bad_selector[data12-x.z.foo3]", "stix2/test/v21/test_granular_markings.py::test_get_markings_positional_arguments_combinations[data0]", "stix2/test/v21/test_granular_markings.py::test_get_markings_multiple_selectors_langs[data0]", "stix2/test/v21/test_granular_markings.py::test_get_markings_multiple_selectors_with_options[data0]", "stix2/test/v21/test_granular_markings.py::test_remove_marking_remove_one_selector_with_multiple_refs[data0]", "stix2/test/v21/test_granular_markings.py::test_remove_marking_remove_one_selector_with_multiple_refs[data1]", "stix2/test/v21/test_granular_markings.py::test_remove_marking_remove_multiple_selector_one_ref", "stix2/test/v21/test_granular_markings.py::test_remove_marking_mark_one_selector_from_multiple_ones", "stix2/test/v21/test_granular_markings.py::test_remove_marking_mark_one_selector_from_multiple_ones_mixed", "stix2/test/v21/test_granular_markings.py::test_remove_marking_mark_one_selector_markings_from_multiple_ones", "stix2/test/v21/test_granular_markings.py::test_remove_marking_mark_mutilple_selector_multiple_refs", "stix2/test/v21/test_granular_markings.py::test_remove_marking_mark_another_property_same_marking", "stix2/test/v21/test_granular_markings.py::test_remove_marking_mark_same_property_same_marking", "stix2/test/v21/test_granular_markings.py::test_remove_no_markings", "stix2/test/v21/test_granular_markings.py::test_remove_marking_bad_selector", "stix2/test/v21/test_granular_markings.py::test_remove_marking_not_present", "stix2/test/v21/test_granular_markings.py::test_is_marked_smoke[data0]", "stix2/test/v21/test_granular_markings.py::test_is_marked_smoke[data1]", "stix2/test/v21/test_granular_markings.py::test_is_marked_invalid_selector[data0-foo]", "stix2/test/v21/test_granular_markings.py::test_is_marked_invalid_selector[data1-]", "stix2/test/v21/test_granular_markings.py::test_is_marked_invalid_selector[data2-selector2]", "stix2/test/v21/test_granular_markings.py::test_is_marked_invalid_selector[data3-selector3]", "stix2/test/v21/test_granular_markings.py::test_is_marked_invalid_selector[data4-x.z.[-2]]", "stix2/test/v21/test_granular_markings.py::test_is_marked_invalid_selector[data5-c.f]", "stix2/test/v21/test_granular_markings.py::test_is_marked_invalid_selector[data6-c.[2].i]", "stix2/test/v21/test_granular_markings.py::test_is_marked_invalid_selector[data7-c.[3]]", "stix2/test/v21/test_granular_markings.py::test_is_marked_invalid_selector[data8-d]", "stix2/test/v21/test_granular_markings.py::test_is_marked_invalid_selector[data9-x.[0]]", "stix2/test/v21/test_granular_markings.py::test_is_marked_invalid_selector[data10-z.y.w]", "stix2/test/v21/test_granular_markings.py::test_is_marked_invalid_selector[data11-x.z.[1]]", "stix2/test/v21/test_granular_markings.py::test_is_marked_invalid_selector[data12-x.z.foo3]", "stix2/test/v21/test_granular_markings.py::test_is_marked_mix_selector[data0]", "stix2/test/v21/test_granular_markings.py::test_is_marked_mix_selector[data1]", "stix2/test/v21/test_granular_markings.py::test_is_marked_valid_selector_no_refs[data0]", "stix2/test/v21/test_granular_markings.py::test_is_marked_valid_selector_no_refs[data1]", "stix2/test/v21/test_granular_markings.py::test_is_marked_valid_selector_and_refs[data0]", "stix2/test/v21/test_granular_markings.py::test_is_marked_valid_selector_and_refs[data1]", "stix2/test/v21/test_granular_markings.py::test_is_marked_valid_selector_multiple_refs[data0]", "stix2/test/v21/test_granular_markings.py::test_is_marked_valid_selector_multiple_refs[data1]", "stix2/test/v21/test_granular_markings.py::test_is_marked_no_marking_refs[data0]", "stix2/test/v21/test_granular_markings.py::test_is_marked_no_marking_refs[data1]", "stix2/test/v21/test_granular_markings.py::test_is_marked_no_selectors[data0]", "stix2/test/v21/test_granular_markings.py::test_is_marked_no_selectors[data1]", "stix2/test/v21/test_granular_markings.py::test_is_marked_positional_arguments_combinations", "stix2/test/v21/test_granular_markings.py::test_create_sdo_with_invalid_marking", "stix2/test/v21/test_granular_markings.py::test_set_marking_mark_one_selector_multiple_refs", "stix2/test/v21/test_granular_markings.py::test_set_marking_mark_one_selector_multiple_lang_refs", "stix2/test/v21/test_granular_markings.py::test_set_marking_mark_multiple_selector_one_refs", "stix2/test/v21/test_granular_markings.py::test_set_marking_mark_multiple_mixed_markings", "stix2/test/v21/test_granular_markings.py::test_set_marking_mark_multiple_selector_multiple_refs_from_none", "stix2/test/v21/test_granular_markings.py::test_set_marking_mark_another_property_same_marking", "stix2/test/v21/test_granular_markings.py::test_set_marking_bad_selector[marking0]", "stix2/test/v21/test_granular_markings.py::test_set_marking_bad_selector[marking1]", "stix2/test/v21/test_granular_markings.py::test_set_marking_bad_selector[marking2]", "stix2/test/v21/test_granular_markings.py::test_set_marking_bad_selector[marking3]", "stix2/test/v21/test_granular_markings.py::test_set_marking_mark_same_property_same_marking", "stix2/test/v21/test_granular_markings.py::test_clear_marking_smoke[data0]", "stix2/test/v21/test_granular_markings.py::test_clear_marking_smoke[data1]", "stix2/test/v21/test_granular_markings.py::test_clear_marking_multiple_selectors[data0]", "stix2/test/v21/test_granular_markings.py::test_clear_marking_multiple_selectors[data1]", "stix2/test/v21/test_granular_markings.py::test_clear_marking_one_selector[data0]", "stix2/test/v21/test_granular_markings.py::test_clear_marking_one_selector[data1]", "stix2/test/v21/test_granular_markings.py::test_clear_marking_all_selectors[data0]", "stix2/test/v21/test_granular_markings.py::test_clear_marking_all_selectors[data1]", "stix2/test/v21/test_granular_markings.py::test_clear_marking_bad_selector[data0-foo]", "stix2/test/v21/test_granular_markings.py::test_clear_marking_bad_selector[data1-]", "stix2/test/v21/test_granular_markings.py::test_clear_marking_bad_selector[data2-selector2]", "stix2/test/v21/test_granular_markings.py::test_clear_marking_bad_selector[data3-selector3]", "stix2/test/v21/test_granular_markings.py::test_clear_marking_not_present[data0]", "stix2/test/v21/test_granular_markings.py::test_clear_marking_not_present[data1]" ]
2020-06-08 13:28:42+00:00
4,303
oasis-open__cti-python-stix2-436
diff --git a/stix2/pattern_visitor.py b/stix2/pattern_visitor.py index 5b8300f..c4deb64 100644 --- a/stix2/pattern_visitor.py +++ b/stix2/pattern_visitor.py @@ -49,6 +49,9 @@ def check_for_valid_timetamp_syntax(timestamp_string): return _TIMESTAMP_RE.match(timestamp_string) +def same_boolean_operator(current_op, op_token): + return current_op == op_token.symbol.text + class STIXPatternVisitorForSTIX2(): classes = {} @@ -131,7 +134,7 @@ class STIXPatternVisitorForSTIX2(): if len(children) == 1: return children[0] else: - if isinstance(children[0], _BooleanExpression): + if isinstance(children[0], _BooleanExpression) and same_boolean_operator(children[0].operator, children[1]): children[0].operands.append(children[2]) return children[0] else:
oasis-open/cti-python-stix2
bb82beeec109e5e45d3ee19da97f4cd145b3491d
diff --git a/stix2/test/v20/test_pattern_expressions.py b/stix2/test/v20/test_pattern_expressions.py index a96d3b8..0e0a9ca 100644 --- a/stix2/test/v20/test_pattern_expressions.py +++ b/stix2/test/v20/test_pattern_expressions.py @@ -511,6 +511,16 @@ def test_parsing_start_stop_qualified_expression(): ) == "[ipv4-addr:value = '1.2.3.4'] START '2016-06-01T00:00:00Z' STOP '2017-03-12T08:30:00Z'" +def test_parsing_mixed_boolean_expression_1(): + patt_obj = create_pattern_object("[a:b = 1 AND a:b = 2 OR a:b = 3]",) + assert str(patt_obj) == "[a:b = 1 AND a:b = 2 OR a:b = 3]" + + +def test_parsing_mixed_boolean_expression_2(): + patt_obj = create_pattern_object("[a:b = 1 OR a:b = 2 AND a:b = 3]",) + assert str(patt_obj) == "[a:b = 1 OR a:b = 2 AND a:b = 3]" + + def test_parsing_illegal_start_stop_qualified_expression(): with pytest.raises(ValueError): create_pattern_object("[ipv4-addr:value = '1.2.3.4'] START '2016-06-01' STOP '2017-03-12T08:30:00Z'", version="2.0") diff --git a/stix2/test/v21/test_pattern_expressions.py b/stix2/test/v21/test_pattern_expressions.py index 8294a41..b574e05 100644 --- a/stix2/test/v21/test_pattern_expressions.py +++ b/stix2/test/v21/test_pattern_expressions.py @@ -644,6 +644,16 @@ def test_parsing_boolean(): assert str(patt_obj) == "[network-traffic:is_active = true]" +def test_parsing_mixed_boolean_expression_1(): + patt_obj = create_pattern_object("[a:b = 1 AND a:b = 2 OR a:b = 3]",) + assert str(patt_obj) == "[a:b = 1 AND a:b = 2 OR a:b = 3]" + + +def test_parsing_mixed_boolean_expression_2(): + patt_obj = create_pattern_object("[a:b = 1 OR a:b = 2 AND a:b = 3]",) + assert str(patt_obj) == "[a:b = 1 OR a:b = 2 AND a:b = 3]" + + def test_parsing_multiple_slashes_quotes(): patt_obj = create_pattern_object("[ file:name = 'weird_name\\'' ]", version="2.1") assert str(patt_obj) == "[file:name = 'weird_name\\'']"
Pattern AST creation bug Comparison expression ORs can get changed to ANDs: ```python from stix2.pattern_visitor import create_pattern_object ast = create_pattern_object(pattern="[a:b=1 AND a:b=2 OR a:b=3]") print(ast) ``` produces ``` [a:b = 1 AND a:b = 2 AND a:b = 3] ```
0.0
[ "stix2/test/v20/test_pattern_expressions.py::test_parsing_mixed_boolean_expression_1", "stix2/test/v21/test_pattern_expressions.py::test_parsing_mixed_boolean_expression_1" ]
[ "stix2/test/v20/test_pattern_expressions.py::test_create_comparison_expression", "stix2/test/v20/test_pattern_expressions.py::test_boolean_expression", "stix2/test/v20/test_pattern_expressions.py::test_boolean_expression_with_parentheses", "stix2/test/v20/test_pattern_expressions.py::test_hash_followed_by_registryKey_expression_python_constant", "stix2/test/v20/test_pattern_expressions.py::test_hash_followed_by_registryKey_expression", "stix2/test/v20/test_pattern_expressions.py::test_file_observable_expression", "stix2/test/v20/test_pattern_expressions.py::test_multiple_file_observable_expression[AndObservationExpression-AND]", "stix2/test/v20/test_pattern_expressions.py::test_multiple_file_observable_expression[OrObservationExpression-OR]", "stix2/test/v20/test_pattern_expressions.py::test_root_types", "stix2/test/v20/test_pattern_expressions.py::test_artifact_payload", "stix2/test/v20/test_pattern_expressions.py::test_greater_than_python_constant", "stix2/test/v20/test_pattern_expressions.py::test_greater_than", "stix2/test/v20/test_pattern_expressions.py::test_less_than", "stix2/test/v20/test_pattern_expressions.py::test_greater_than_or_equal", "stix2/test/v20/test_pattern_expressions.py::test_less_than_or_equal", "stix2/test/v20/test_pattern_expressions.py::test_not", "stix2/test/v20/test_pattern_expressions.py::test_and_observable_expression", "stix2/test/v20/test_pattern_expressions.py::test_invalid_and_observable_expression", "stix2/test/v20/test_pattern_expressions.py::test_hex", "stix2/test/v20/test_pattern_expressions.py::test_multiple_qualifiers", "stix2/test/v20/test_pattern_expressions.py::test_set_op", "stix2/test/v20/test_pattern_expressions.py::test_timestamp", "stix2/test/v20/test_pattern_expressions.py::test_boolean", "stix2/test/v20/test_pattern_expressions.py::test_binary", "stix2/test/v20/test_pattern_expressions.py::test_list", "stix2/test/v20/test_pattern_expressions.py::test_list2", "stix2/test/v20/test_pattern_expressions.py::test_invalid_constant_type", "stix2/test/v20/test_pattern_expressions.py::test_invalid_integer_constant", "stix2/test/v20/test_pattern_expressions.py::test_invalid_float_constant", "stix2/test/v20/test_pattern_expressions.py::test_boolean_constant[True-True0]", "stix2/test/v20/test_pattern_expressions.py::test_boolean_constant[False-False0]", "stix2/test/v20/test_pattern_expressions.py::test_boolean_constant[True-True1]", "stix2/test/v20/test_pattern_expressions.py::test_boolean_constant[False-False1]", "stix2/test/v20/test_pattern_expressions.py::test_boolean_constant[true-True]", "stix2/test/v20/test_pattern_expressions.py::test_boolean_constant[false-False]", "stix2/test/v20/test_pattern_expressions.py::test_boolean_constant[t-True]", "stix2/test/v20/test_pattern_expressions.py::test_boolean_constant[f-False]", "stix2/test/v20/test_pattern_expressions.py::test_boolean_constant[T-True]", "stix2/test/v20/test_pattern_expressions.py::test_boolean_constant[F-False]", "stix2/test/v20/test_pattern_expressions.py::test_boolean_constant[1-True]", "stix2/test/v20/test_pattern_expressions.py::test_boolean_constant[0-False]", "stix2/test/v20/test_pattern_expressions.py::test_invalid_boolean_constant", "stix2/test/v20/test_pattern_expressions.py::test_invalid_hash_constant[MD5-zzz]", "stix2/test/v20/test_pattern_expressions.py::test_invalid_hash_constant[ssdeep-zzz==]", "stix2/test/v20/test_pattern_expressions.py::test_invalid_hex_constant", "stix2/test/v20/test_pattern_expressions.py::test_invalid_binary_constant", "stix2/test/v20/test_pattern_expressions.py::test_escape_quotes_and_backslashes", "stix2/test/v20/test_pattern_expressions.py::test_like", "stix2/test/v20/test_pattern_expressions.py::test_issuperset", "stix2/test/v20/test_pattern_expressions.py::test_repeat_qualifier", "stix2/test/v20/test_pattern_expressions.py::test_invalid_repeat_qualifier", "stix2/test/v20/test_pattern_expressions.py::test_invalid_within_qualifier", "stix2/test/v20/test_pattern_expressions.py::test_startstop_qualifier", "stix2/test/v20/test_pattern_expressions.py::test_invalid_startstop_qualifier", "stix2/test/v20/test_pattern_expressions.py::test_make_constant_already_a_constant", "stix2/test/v20/test_pattern_expressions.py::test_parsing_comparison_expression", "stix2/test/v20/test_pattern_expressions.py::test_parsing_qualified_expression", "stix2/test/v20/test_pattern_expressions.py::test_parsing_start_stop_qualified_expression", "stix2/test/v20/test_pattern_expressions.py::test_parsing_mixed_boolean_expression_2", "stix2/test/v20/test_pattern_expressions.py::test_parsing_illegal_start_stop_qualified_expression", "stix2/test/v20/test_pattern_expressions.py::test_list_constant", "stix2/test/v21/test_pattern_expressions.py::test_create_comparison_expression", "stix2/test/v21/test_pattern_expressions.py::test_boolean_expression", "stix2/test/v21/test_pattern_expressions.py::test_boolean_expression_with_parentheses", "stix2/test/v21/test_pattern_expressions.py::test_hash_followed_by_registryKey_expression_python_constant", "stix2/test/v21/test_pattern_expressions.py::test_hash_followed_by_registryKey_expression", "stix2/test/v21/test_pattern_expressions.py::test_file_observable_expression", "stix2/test/v21/test_pattern_expressions.py::test_multiple_file_observable_expression[AndObservationExpression-AND]", "stix2/test/v21/test_pattern_expressions.py::test_multiple_file_observable_expression[OrObservationExpression-OR]", "stix2/test/v21/test_pattern_expressions.py::test_root_types", "stix2/test/v21/test_pattern_expressions.py::test_artifact_payload", "stix2/test/v21/test_pattern_expressions.py::test_greater_than_python_constant", "stix2/test/v21/test_pattern_expressions.py::test_greater_than", "stix2/test/v21/test_pattern_expressions.py::test_parsing_greater_than", "stix2/test/v21/test_pattern_expressions.py::test_less_than", "stix2/test/v21/test_pattern_expressions.py::test_parsing_less_than", "stix2/test/v21/test_pattern_expressions.py::test_greater_than_or_equal", "stix2/test/v21/test_pattern_expressions.py::test_parsing_greater_than_or_equal", "stix2/test/v21/test_pattern_expressions.py::test_less_than_or_equal", "stix2/test/v21/test_pattern_expressions.py::test_parsing_less_than_or_equal", "stix2/test/v21/test_pattern_expressions.py::test_parsing_issubset", "stix2/test/v21/test_pattern_expressions.py::test_parsing_issuperset", "stix2/test/v21/test_pattern_expressions.py::test_parsing_like", "stix2/test/v21/test_pattern_expressions.py::test_parsing_match", "stix2/test/v21/test_pattern_expressions.py::test_parsing_followed_by", "stix2/test/v21/test_pattern_expressions.py::test_not", "stix2/test/v21/test_pattern_expressions.py::test_and_observable_expression", "stix2/test/v21/test_pattern_expressions.py::test_parsing_and_observable_expression", "stix2/test/v21/test_pattern_expressions.py::test_or_observable_expression", "stix2/test/v21/test_pattern_expressions.py::test_parsing_or_observable_expression", "stix2/test/v21/test_pattern_expressions.py::test_invalid_and_observable_expression", "stix2/test/v21/test_pattern_expressions.py::test_hex", "stix2/test/v21/test_pattern_expressions.py::test_parsing_hex", "stix2/test/v21/test_pattern_expressions.py::test_multiple_qualifiers", "stix2/test/v21/test_pattern_expressions.py::test_set_op", "stix2/test/v21/test_pattern_expressions.py::test_timestamp", "stix2/test/v21/test_pattern_expressions.py::test_boolean", "stix2/test/v21/test_pattern_expressions.py::test_binary", "stix2/test/v21/test_pattern_expressions.py::test_parsing_binary", "stix2/test/v21/test_pattern_expressions.py::test_list", "stix2/test/v21/test_pattern_expressions.py::test_list2", "stix2/test/v21/test_pattern_expressions.py::test_invalid_constant_type", "stix2/test/v21/test_pattern_expressions.py::test_invalid_integer_constant", "stix2/test/v21/test_pattern_expressions.py::test_invalid_timestamp_constant", "stix2/test/v21/test_pattern_expressions.py::test_invalid_float_constant", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[True-True0]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[False-False0]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[True-True1]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[False-False1]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[true-True]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[false-False]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[t-True]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[f-False]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[T-True]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[F-False]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[1-True]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[0-False]", "stix2/test/v21/test_pattern_expressions.py::test_invalid_boolean_constant", "stix2/test/v21/test_pattern_expressions.py::test_invalid_hash_constant[MD5-zzz]", "stix2/test/v21/test_pattern_expressions.py::test_invalid_hash_constant[SSDEEP-zzz==]", "stix2/test/v21/test_pattern_expressions.py::test_invalid_hex_constant", "stix2/test/v21/test_pattern_expressions.py::test_invalid_binary_constant", "stix2/test/v21/test_pattern_expressions.py::test_escape_quotes_and_backslashes", "stix2/test/v21/test_pattern_expressions.py::test_like", "stix2/test/v21/test_pattern_expressions.py::test_issuperset", "stix2/test/v21/test_pattern_expressions.py::test_repeat_qualifier", "stix2/test/v21/test_pattern_expressions.py::test_invalid_repeat_qualifier", "stix2/test/v21/test_pattern_expressions.py::test_invalid_within_qualifier", "stix2/test/v21/test_pattern_expressions.py::test_startstop_qualifier", "stix2/test/v21/test_pattern_expressions.py::test_invalid_startstop_qualifier", "stix2/test/v21/test_pattern_expressions.py::test_make_constant_already_a_constant", "stix2/test/v21/test_pattern_expressions.py::test_parsing_comparison_expression", "stix2/test/v21/test_pattern_expressions.py::test_parsing_repeat_and_within_qualified_expression", "stix2/test/v21/test_pattern_expressions.py::test_parsing_start_stop_qualified_expression", "stix2/test/v21/test_pattern_expressions.py::test_list_constant", "stix2/test/v21/test_pattern_expressions.py::test_parsing_boolean", "stix2/test/v21/test_pattern_expressions.py::test_parsing_mixed_boolean_expression_2", "stix2/test/v21/test_pattern_expressions.py::test_parsing_multiple_slashes_quotes", "stix2/test/v21/test_pattern_expressions.py::test_parse_error" ]
2020-07-24 15:41:29+00:00
4,304
oasis-open__cti-python-stix2-454
diff --git a/stix2/patterns.py b/stix2/patterns.py index bbee7ac..f1472cd 100644 --- a/stix2/patterns.py +++ b/stix2/patterns.py @@ -227,7 +227,7 @@ def make_constant(value): return value try: - return parse_into_datetime(value) + return TimestampConstant(value) except (ValueError, TypeError): pass
oasis-open/cti-python-stix2
72a032c6e31387254629e730470c3974919765a9
diff --git a/stix2/test/v20/test_pattern_expressions.py b/stix2/test/v20/test_pattern_expressions.py index fa9000e..526fe97 100644 --- a/stix2/test/v20/test_pattern_expressions.py +++ b/stix2/test/v20/test_pattern_expressions.py @@ -1,9 +1,11 @@ import datetime import pytest +import pytz import stix2 from stix2.pattern_visitor import create_pattern_object +import stix2.utils def test_create_comparison_expression(): @@ -482,6 +484,44 @@ def test_invalid_startstop_qualifier(): ) [email protected]( + "input_, expected_class, expected_value", [ + (1, stix2.patterns.IntegerConstant, 1), + (1.5, stix2.patterns.FloatConstant, 1.5), + ("abc", stix2.patterns.StringConstant, "abc"), + (True, stix2.patterns.BooleanConstant, True), + ( + "2001-02-10T21:36:15Z", stix2.patterns.TimestampConstant, + stix2.utils.STIXdatetime(2001, 2, 10, 21, 36, 15, tzinfo=pytz.utc), + ), + ( + datetime.datetime(2001, 2, 10, 21, 36, 15, tzinfo=pytz.utc), + stix2.patterns.TimestampConstant, + stix2.utils.STIXdatetime(2001, 2, 10, 21, 36, 15, tzinfo=pytz.utc), + ), + ], +) +def test_make_constant_simple(input_, expected_class, expected_value): + const = stix2.patterns.make_constant(input_) + + assert isinstance(const, expected_class) + assert const.value == expected_value + + +def test_make_constant_list(): + list_const = stix2.patterns.make_constant([1, 2, 3]) + + assert isinstance(list_const, stix2.patterns.ListConstant) + assert all( + isinstance(elt, stix2.patterns.IntegerConstant) + for elt in list_const.value + ) + assert all( + int_const.value == test_elt + for int_const, test_elt in zip(list_const.value, [1, 2, 3]) + ) + + def test_make_constant_already_a_constant(): str_const = stix2.StringConstant('Foo') result = stix2.patterns.make_constant(str_const) diff --git a/stix2/test/v21/test_pattern_expressions.py b/stix2/test/v21/test_pattern_expressions.py index ac6a439..58cef3e 100644 --- a/stix2/test/v21/test_pattern_expressions.py +++ b/stix2/test/v21/test_pattern_expressions.py @@ -1,10 +1,12 @@ import datetime import pytest +import pytz from stix2patterns.exceptions import ParseException import stix2 from stix2.pattern_visitor import create_pattern_object +import stix2.utils def test_create_comparison_expression(): @@ -603,6 +605,44 @@ def test_invalid_startstop_qualifier(): ) [email protected]( + "input_, expected_class, expected_value", [ + (1, stix2.patterns.IntegerConstant, 1), + (1.5, stix2.patterns.FloatConstant, 1.5), + ("abc", stix2.patterns.StringConstant, "abc"), + (True, stix2.patterns.BooleanConstant, True), + ( + "2001-02-10T21:36:15Z", stix2.patterns.TimestampConstant, + stix2.utils.STIXdatetime(2001, 2, 10, 21, 36, 15, tzinfo=pytz.utc), + ), + ( + datetime.datetime(2001, 2, 10, 21, 36, 15, tzinfo=pytz.utc), + stix2.patterns.TimestampConstant, + stix2.utils.STIXdatetime(2001, 2, 10, 21, 36, 15, tzinfo=pytz.utc), + ), + ], +) +def test_make_constant_simple(input_, expected_class, expected_value): + const = stix2.patterns.make_constant(input_) + + assert isinstance(const, expected_class) + assert const.value == expected_value + + +def test_make_constant_list(): + list_const = stix2.patterns.make_constant([1, 2, 3]) + + assert isinstance(list_const, stix2.patterns.ListConstant) + assert all( + isinstance(elt, stix2.patterns.IntegerConstant) + for elt in list_const.value + ) + assert all( + int_const.value == test_elt + for int_const, test_elt in zip(list_const.value, [1, 2, 3]) + ) + + def test_make_constant_already_a_constant(): str_const = stix2.StringConstant('Foo') result = stix2.patterns.make_constant(str_const)
AST make_constant() function doesn't make timestamp constants If make_constant() can interpret the passed value as a timestamp, it will return a STIXdatetime object instead of a timestamp constant. That results in an incorrect AST and messed up pattern format. E.g. ```python import stix2.patterns comp_expr = stix2.patterns.EqualityComparisonExpression("a:b", "1993-07-12T22:27:23Z") print(comp_expr) ``` results in ``` a:b = 1993-07-12 22:27:23+00:00 ```
0.0
[ "stix2/test/v20/test_pattern_expressions.py::test_make_constant_simple[2001-02-10T21:36:15Z-TimestampConstant-expected_value4]", "stix2/test/v20/test_pattern_expressions.py::test_make_constant_simple[input_5-TimestampConstant-expected_value5]", "stix2/test/v21/test_pattern_expressions.py::test_make_constant_simple[2001-02-10T21:36:15Z-TimestampConstant-expected_value4]", "stix2/test/v21/test_pattern_expressions.py::test_make_constant_simple[input_5-TimestampConstant-expected_value5]" ]
[ "stix2/test/v20/test_pattern_expressions.py::test_create_comparison_expression", "stix2/test/v20/test_pattern_expressions.py::test_boolean_expression", "stix2/test/v20/test_pattern_expressions.py::test_boolean_expression_with_parentheses", "stix2/test/v20/test_pattern_expressions.py::test_hash_followed_by_registryKey_expression_python_constant", "stix2/test/v20/test_pattern_expressions.py::test_hash_followed_by_registryKey_expression", "stix2/test/v20/test_pattern_expressions.py::test_file_observable_expression", "stix2/test/v20/test_pattern_expressions.py::test_multiple_file_observable_expression[AndObservationExpression-AND]", "stix2/test/v20/test_pattern_expressions.py::test_multiple_file_observable_expression[OrObservationExpression-OR]", "stix2/test/v20/test_pattern_expressions.py::test_root_types", "stix2/test/v20/test_pattern_expressions.py::test_artifact_payload", "stix2/test/v20/test_pattern_expressions.py::test_greater_than_python_constant", "stix2/test/v20/test_pattern_expressions.py::test_greater_than", "stix2/test/v20/test_pattern_expressions.py::test_less_than", "stix2/test/v20/test_pattern_expressions.py::test_greater_than_or_equal", "stix2/test/v20/test_pattern_expressions.py::test_less_than_or_equal", "stix2/test/v20/test_pattern_expressions.py::test_not", "stix2/test/v20/test_pattern_expressions.py::test_and_observable_expression", "stix2/test/v20/test_pattern_expressions.py::test_invalid_and_observable_expression", "stix2/test/v20/test_pattern_expressions.py::test_hex", "stix2/test/v20/test_pattern_expressions.py::test_multiple_qualifiers", "stix2/test/v20/test_pattern_expressions.py::test_set_op", "stix2/test/v20/test_pattern_expressions.py::test_timestamp", "stix2/test/v20/test_pattern_expressions.py::test_boolean", "stix2/test/v20/test_pattern_expressions.py::test_binary", "stix2/test/v20/test_pattern_expressions.py::test_list", "stix2/test/v20/test_pattern_expressions.py::test_list2", "stix2/test/v20/test_pattern_expressions.py::test_invalid_constant_type", "stix2/test/v20/test_pattern_expressions.py::test_invalid_integer_constant", "stix2/test/v20/test_pattern_expressions.py::test_invalid_float_constant", "stix2/test/v20/test_pattern_expressions.py::test_boolean_constant[True-True0]", "stix2/test/v20/test_pattern_expressions.py::test_boolean_constant[False-False0]", "stix2/test/v20/test_pattern_expressions.py::test_boolean_constant[True-True1]", "stix2/test/v20/test_pattern_expressions.py::test_boolean_constant[False-False1]", "stix2/test/v20/test_pattern_expressions.py::test_boolean_constant[true-True]", "stix2/test/v20/test_pattern_expressions.py::test_boolean_constant[false-False]", "stix2/test/v20/test_pattern_expressions.py::test_boolean_constant[t-True]", "stix2/test/v20/test_pattern_expressions.py::test_boolean_constant[f-False]", "stix2/test/v20/test_pattern_expressions.py::test_boolean_constant[T-True]", "stix2/test/v20/test_pattern_expressions.py::test_boolean_constant[F-False]", "stix2/test/v20/test_pattern_expressions.py::test_boolean_constant[1-True]", "stix2/test/v20/test_pattern_expressions.py::test_boolean_constant[0-False]", "stix2/test/v20/test_pattern_expressions.py::test_invalid_boolean_constant", "stix2/test/v20/test_pattern_expressions.py::test_invalid_hash_constant[MD5-zzz]", "stix2/test/v20/test_pattern_expressions.py::test_invalid_hash_constant[ssdeep-zzz==]", "stix2/test/v20/test_pattern_expressions.py::test_invalid_hex_constant", "stix2/test/v20/test_pattern_expressions.py::test_invalid_binary_constant", "stix2/test/v20/test_pattern_expressions.py::test_escape_quotes_and_backslashes", "stix2/test/v20/test_pattern_expressions.py::test_like", "stix2/test/v20/test_pattern_expressions.py::test_issuperset", "stix2/test/v20/test_pattern_expressions.py::test_repeat_qualifier", "stix2/test/v20/test_pattern_expressions.py::test_invalid_repeat_qualifier", "stix2/test/v20/test_pattern_expressions.py::test_invalid_within_qualifier", "stix2/test/v20/test_pattern_expressions.py::test_startstop_qualifier", "stix2/test/v20/test_pattern_expressions.py::test_invalid_startstop_qualifier", "stix2/test/v20/test_pattern_expressions.py::test_make_constant_simple[1-IntegerConstant-1]", "stix2/test/v20/test_pattern_expressions.py::test_make_constant_simple[1.5-FloatConstant-1.5]", "stix2/test/v20/test_pattern_expressions.py::test_make_constant_simple[abc-StringConstant-abc]", "stix2/test/v20/test_pattern_expressions.py::test_make_constant_simple[True-BooleanConstant-True]", "stix2/test/v20/test_pattern_expressions.py::test_make_constant_list", "stix2/test/v20/test_pattern_expressions.py::test_make_constant_already_a_constant", "stix2/test/v20/test_pattern_expressions.py::test_parsing_comparison_expression", "stix2/test/v20/test_pattern_expressions.py::test_parsing_qualified_expression", "stix2/test/v20/test_pattern_expressions.py::test_parsing_start_stop_qualified_expression", "stix2/test/v20/test_pattern_expressions.py::test_parsing_mixed_boolean_expression_1", "stix2/test/v20/test_pattern_expressions.py::test_parsing_mixed_boolean_expression_2", "stix2/test/v20/test_pattern_expressions.py::test_parsing_integer_index", "stix2/test/v20/test_pattern_expressions.py::test_parsing_quoted_first_path_component", "stix2/test/v20/test_pattern_expressions.py::test_parsing_quoted_second_path_component", "stix2/test/v20/test_pattern_expressions.py::test_parsing_illegal_start_stop_qualified_expression", "stix2/test/v20/test_pattern_expressions.py::test_list_constant", "stix2/test/v21/test_pattern_expressions.py::test_create_comparison_expression", "stix2/test/v21/test_pattern_expressions.py::test_boolean_expression", "stix2/test/v21/test_pattern_expressions.py::test_boolean_expression_with_parentheses", "stix2/test/v21/test_pattern_expressions.py::test_hash_followed_by_registryKey_expression_python_constant", "stix2/test/v21/test_pattern_expressions.py::test_hash_followed_by_registryKey_expression", "stix2/test/v21/test_pattern_expressions.py::test_file_observable_expression", "stix2/test/v21/test_pattern_expressions.py::test_multiple_file_observable_expression[AndObservationExpression-AND]", "stix2/test/v21/test_pattern_expressions.py::test_multiple_file_observable_expression[OrObservationExpression-OR]", "stix2/test/v21/test_pattern_expressions.py::test_root_types", "stix2/test/v21/test_pattern_expressions.py::test_artifact_payload", "stix2/test/v21/test_pattern_expressions.py::test_greater_than_python_constant", "stix2/test/v21/test_pattern_expressions.py::test_greater_than", "stix2/test/v21/test_pattern_expressions.py::test_parsing_greater_than", "stix2/test/v21/test_pattern_expressions.py::test_less_than", "stix2/test/v21/test_pattern_expressions.py::test_parsing_less_than", "stix2/test/v21/test_pattern_expressions.py::test_greater_than_or_equal", "stix2/test/v21/test_pattern_expressions.py::test_parsing_greater_than_or_equal", "stix2/test/v21/test_pattern_expressions.py::test_less_than_or_equal", "stix2/test/v21/test_pattern_expressions.py::test_parsing_less_than_or_equal", "stix2/test/v21/test_pattern_expressions.py::test_parsing_issubset", "stix2/test/v21/test_pattern_expressions.py::test_parsing_issuperset", "stix2/test/v21/test_pattern_expressions.py::test_parsing_like", "stix2/test/v21/test_pattern_expressions.py::test_parsing_match", "stix2/test/v21/test_pattern_expressions.py::test_parsing_followed_by", "stix2/test/v21/test_pattern_expressions.py::test_not", "stix2/test/v21/test_pattern_expressions.py::test_and_observable_expression", "stix2/test/v21/test_pattern_expressions.py::test_parsing_and_observable_expression", "stix2/test/v21/test_pattern_expressions.py::test_or_observable_expression", "stix2/test/v21/test_pattern_expressions.py::test_parsing_or_observable_expression", "stix2/test/v21/test_pattern_expressions.py::test_invalid_and_observable_expression", "stix2/test/v21/test_pattern_expressions.py::test_hex", "stix2/test/v21/test_pattern_expressions.py::test_parsing_hex", "stix2/test/v21/test_pattern_expressions.py::test_multiple_qualifiers", "stix2/test/v21/test_pattern_expressions.py::test_set_op", "stix2/test/v21/test_pattern_expressions.py::test_timestamp", "stix2/test/v21/test_pattern_expressions.py::test_boolean", "stix2/test/v21/test_pattern_expressions.py::test_binary", "stix2/test/v21/test_pattern_expressions.py::test_parsing_binary", "stix2/test/v21/test_pattern_expressions.py::test_list", "stix2/test/v21/test_pattern_expressions.py::test_list2", "stix2/test/v21/test_pattern_expressions.py::test_invalid_constant_type", "stix2/test/v21/test_pattern_expressions.py::test_invalid_integer_constant", "stix2/test/v21/test_pattern_expressions.py::test_invalid_timestamp_constant", "stix2/test/v21/test_pattern_expressions.py::test_invalid_float_constant", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[True-True0]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[False-False0]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[True-True1]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[False-False1]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[true-True]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[false-False]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[t-True]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[f-False]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[T-True]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[F-False]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[1-True]", "stix2/test/v21/test_pattern_expressions.py::test_boolean_constant[0-False]", "stix2/test/v21/test_pattern_expressions.py::test_invalid_boolean_constant", "stix2/test/v21/test_pattern_expressions.py::test_invalid_hash_constant[MD5-zzz]", "stix2/test/v21/test_pattern_expressions.py::test_invalid_hash_constant[SSDEEP-zzz==]", "stix2/test/v21/test_pattern_expressions.py::test_invalid_hex_constant", "stix2/test/v21/test_pattern_expressions.py::test_invalid_binary_constant", "stix2/test/v21/test_pattern_expressions.py::test_escape_quotes_and_backslashes", "stix2/test/v21/test_pattern_expressions.py::test_like", "stix2/test/v21/test_pattern_expressions.py::test_issuperset", "stix2/test/v21/test_pattern_expressions.py::test_repeat_qualifier", "stix2/test/v21/test_pattern_expressions.py::test_invalid_repeat_qualifier", "stix2/test/v21/test_pattern_expressions.py::test_invalid_within_qualifier", "stix2/test/v21/test_pattern_expressions.py::test_startstop_qualifier", "stix2/test/v21/test_pattern_expressions.py::test_invalid_startstop_qualifier", "stix2/test/v21/test_pattern_expressions.py::test_make_constant_simple[1-IntegerConstant-1]", "stix2/test/v21/test_pattern_expressions.py::test_make_constant_simple[1.5-FloatConstant-1.5]", "stix2/test/v21/test_pattern_expressions.py::test_make_constant_simple[abc-StringConstant-abc]", "stix2/test/v21/test_pattern_expressions.py::test_make_constant_simple[True-BooleanConstant-True]", "stix2/test/v21/test_pattern_expressions.py::test_make_constant_list", "stix2/test/v21/test_pattern_expressions.py::test_make_constant_already_a_constant", "stix2/test/v21/test_pattern_expressions.py::test_parsing_comparison_expression", "stix2/test/v21/test_pattern_expressions.py::test_parsing_repeat_and_within_qualified_expression", "stix2/test/v21/test_pattern_expressions.py::test_parsing_start_stop_qualified_expression", "stix2/test/v21/test_pattern_expressions.py::test_list_constant", "stix2/test/v21/test_pattern_expressions.py::test_parsing_boolean", "stix2/test/v21/test_pattern_expressions.py::test_parsing_mixed_boolean_expression_1", "stix2/test/v21/test_pattern_expressions.py::test_parsing_mixed_boolean_expression_2", "stix2/test/v21/test_pattern_expressions.py::test_parsing_integer_index", "stix2/test/v21/test_pattern_expressions.py::test_parsing_quoted_first_path_component", "stix2/test/v21/test_pattern_expressions.py::test_parsing_quoted_second_path_component", "stix2/test/v21/test_pattern_expressions.py::test_parsing_multiple_slashes_quotes", "stix2/test/v21/test_pattern_expressions.py::test_parse_error" ]
2020-09-12 23:21:38+00:00
4,305
oasis-open__cti-python-stix2-470
diff --git a/stix2/v21/sro.py b/stix2/v21/sro.py index d287373..e6eada6 100644 --- a/stix2/v21/sro.py +++ b/stix2/v21/sro.py @@ -86,7 +86,7 @@ class Sighting(_RelationshipObject): ('count', IntegerProperty(min=0, max=999999999)), ('sighting_of_ref', ReferenceProperty(valid_types="SDO", spec_version='2.1', required=True)), ('observed_data_refs', ListProperty(ReferenceProperty(valid_types='observed-data', spec_version='2.1'))), - ('where_sighted_refs', ListProperty(ReferenceProperty(valid_types='identity', spec_version='2.1'))), + ('where_sighted_refs', ListProperty(ReferenceProperty(valid_types=['identity', 'location'], spec_version='2.1'))), ('summary', BooleanProperty()), ('revoked', BooleanProperty(default=lambda: False)), ('labels', ListProperty(StringProperty)),
oasis-open/cti-python-stix2
a751df32c681e3ddfef92f29b91c071b84e91033
diff --git a/stix2/test/v21/test_sighting.py b/stix2/test/v21/test_sighting.py index 0493b71..0ef5faa 100644 --- a/stix2/test/v21/test_sighting.py +++ b/stix2/test/v21/test_sighting.py @@ -5,7 +5,9 @@ import pytz import stix2 -from .constants import IDENTITY_ID, INDICATOR_ID, SIGHTING_ID, SIGHTING_KWARGS +from .constants import ( + IDENTITY_ID, INDICATOR_ID, LOCATION_ID, SIGHTING_ID, SIGHTING_KWARGS, +) EXPECTED_SIGHTING = """{ "type": "sighting", @@ -15,7 +17,8 @@ EXPECTED_SIGHTING = """{ "modified": "2016-04-06T20:06:37.000Z", "sighting_of_ref": "indicator--a740531e-63ff-4e49-a9e1-a0a3eed0e3e7", "where_sighted_refs": [ - "identity--311b2d2d-f010-4473-83ec-1edf84858f4c" + "identity--311b2d2d-f010-4473-83ec-1edf84858f4c", + "location--a6e9345f-5a15-4c29-8bb3-7dcc5d168d64" ] }""" @@ -41,7 +44,7 @@ def test_sighting_all_required_properties(): created=now, modified=now, sighting_of_ref=INDICATOR_ID, - where_sighted_refs=[IDENTITY_ID], + where_sighted_refs=[IDENTITY_ID, LOCATION_ID], ) assert str(s) == EXPECTED_SIGHTING @@ -101,6 +104,7 @@ def test_create_sighting_from_objects_rather_than_ids(malware): # noqa: F811 "type": "sighting", "where_sighted_refs": [ IDENTITY_ID, + LOCATION_ID, ], }, ], @@ -114,4 +118,4 @@ def test_parse_sighting(data): assert sighting.created == dt.datetime(2016, 4, 6, 20, 6, 37, tzinfo=pytz.utc) assert sighting.modified == dt.datetime(2016, 4, 6, 20, 6, 37, tzinfo=pytz.utc) assert sighting.sighting_of_ref == INDICATOR_ID - assert sighting.where_sighted_refs == [IDENTITY_ID] + assert sighting.where_sighted_refs == [IDENTITY_ID, LOCATION_ID]
Sighting: where_sighted_refs enforced with wrong types STIX 2.1 spec section 5.2 says for the `where_sighted_refs` property of the Sighting relationship: ``` This property MUST reference only Identity or Location SDOs. ``` But the stix2 library only allows Identity. This should be fixed to also allow Location references. https://github.com/oasis-open/cti-python-stix2/blob/a751df32c681e3ddfef92f29b91c071b84e91033/stix2/v21/sro.py#L89
0.0
[ "stix2/test/v21/test_sighting.py::test_sighting_all_required_properties", "stix2/test/v21/test_sighting.py::test_parse_sighting[{\\n", "stix2/test/v21/test_sighting.py::test_parse_sighting[data1]" ]
[ "stix2/test/v21/test_sighting.py::test_sighting_bad_where_sighted_refs", "stix2/test/v21/test_sighting.py::test_sighting_type_must_be_sightings", "stix2/test/v21/test_sighting.py::test_invalid_kwarg_to_sighting", "stix2/test/v21/test_sighting.py::test_create_sighting_from_objects_rather_than_ids" ]
2020-11-16 20:08:20+00:00
4,306
oasis-open__cti-python-stix2-489
diff --git a/stix2/equivalence/pattern/transform/observation.py b/stix2/equivalence/pattern/transform/observation.py index ee698bd..029824d 100644 --- a/stix2/equivalence/pattern/transform/observation.py +++ b/stix2/equivalence/pattern/transform/observation.py @@ -282,6 +282,7 @@ class AbsorptionTransformer( A or (A and B) = A A or (A followedby B) = A + A or (B followedby A) = A Other variants do not hold for observation expressions. """ @@ -435,28 +436,35 @@ class DNFTransformer(ObservationExpressionTransformer): A and (B or C) => (A and B) or (A and C) A followedby (B or C) => (A followedby B) or (A followedby C) + (A or B) followedby C => (A followedby C) or (B followedby C) """ def __transform(self, ast): - root_type = type(ast) # will be AST class for AND or FOLLOWEDBY - changed = False - or_children = [] - other_children = [] - for child in ast.operands: - if isinstance(child, OrObservationExpression): - or_children.append(child.operands) - else: - other_children.append(child) + # If no OR children, nothing to do + if any( + isinstance(child, OrObservationExpression) + for child in ast.operands + ): + # When we distribute FOLLOWEDBY over OR, it is important to + # preserve the original FOLLOWEDBY order! We don't need to do that + # for AND, but we do it anyway because it doesn't hurt, and we can + # use the same code for both. + iterables = [] + for child in ast.operands: + if isinstance(child, OrObservationExpression): + iterables.append(child.operands) + else: + iterables.append((child,)) - if or_children: + root_type = type(ast) # will be AST class for AND or FOLLOWEDBY distributed_children = [ root_type([ _dupe_ast(sub_ast) for sub_ast in itertools.chain( - other_children, prod_seq, + prod_seq, ) ]) - for prod_seq in itertools.product(*or_children) + for prod_seq in itertools.product(*iterables) ] # Need to recursively continue to distribute AND/FOLLOWEDBY over OR @@ -470,6 +478,7 @@ class DNFTransformer(ObservationExpressionTransformer): else: result = ast + changed = False return result, changed
oasis-open/cti-python-stix2
bfc47e73f5cdf336610e492e8fca4218566843d9
diff --git a/stix2/test/test_pattern_equivalence.py b/stix2/test/test_pattern_equivalence.py index 431322f..cebb9e7 100644 --- a/stix2/test/test_pattern_equivalence.py +++ b/stix2/test/test_pattern_equivalence.py @@ -223,6 +223,10 @@ def test_obs_absorb_not_equivalent(patt1, patt2): "([a:b=1] OR [a:b=2]) FOLLOWEDBY ([a:b=3] OR [a:b=4])", "([a:b=1] FOLLOWEDBY [a:b=3]) OR ([a:b=1] FOLLOWEDBY [a:b=4]) OR ([a:b=2] FOLLOWEDBY [a:b=3]) OR ([a:b=2] FOLLOWEDBY [a:b=4])", ), + ( + "([a:b=1] OR [a:b=2]) FOLLOWEDBY ([a:b=5] AND [a:b=6])", + "([a:b=1] FOLLOWEDBY ([a:b=5] AND [a:b=6])) OR ([a:b=2] FOLLOWEDBY ([a:b=5] AND [a:b=6]))", + ), ], ) def test_obs_dnf_equivalent(patt1, patt2): @@ -243,6 +247,10 @@ def test_obs_dnf_equivalent(patt1, patt2): "[a:b=1] WITHIN 2 SECONDS", "[a:b=1] REPEATS 2 TIMES", ), + ( + "[a:b=1] FOLLOWEDBY ([a:b=2] OR [a:b=3])", + "([a:b=2] FOLLOWEDBY [a:b=1]) OR ([a:b=1] FOLLOWEDBY [a:b=3])", + ), ], ) def test_obs_not_equivalent(patt1, patt2):
Observation expression DNF transformer needs to preserve FOLLOWEDBY order This was just a plain oversight on my part. The same basic code handled both distributing AND over OR and FOLLOWEDBY over OR, but those have differing requirements. FOLLOWEDBY order must always be preserved. For example: ``` ([A] OR [B]) FOLLOWEDBY ([C] AND [D]) ``` was being transformed to ``` (([C] AND [D]) FOLLOWEDBY [A]) OR (([C] AND [D]) FOLLOWEDBY [B]) ``` so that the A/B parts were put last in each distributed FOLLOWEDBY clause. This would be fine if the FOLLOWEDBY were an AND. The transformed result needs to be: ``` ([A] FOLLOWEDBY ([C] AND [D])) OR ([B] FOLLOWEDBY ([C] AND [D])) ``` The transform needs to be fixed to preserve FOLLOWEDBY order.
0.0
[ "stix2/test/test_pattern_equivalence.py::test_obs_dnf_equivalent[([a:b=1]" ]
[ "stix2/test/test_pattern_equivalence.py::test_obs_dupe_equivalent[[a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_dupe_not_equivalent[[a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_flatten_equivalent[[a:b=1]-([a:b=1])]", "stix2/test/test_pattern_equivalence.py::test_obs_flatten_equivalent[(((([a:b=1]))))-([a:b=1])]", "stix2/test/test_pattern_equivalence.py::test_obs_flatten_equivalent[[a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_flatten_equivalent[([a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_flatten_not_equivalent[([a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_flatten_not_equivalent[[a:b=1]-([a:b=1])", "stix2/test/test_pattern_equivalence.py::test_obs_flatten_not_equivalent[(((([a:b=1]))))-([a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_flatten_not_equivalent[[a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_order_equivalent[[a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_order_not_equivalent[[a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_absorb_equivalent[[a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_absorb_equivalent[([a:b=3]", "stix2/test/test_pattern_equivalence.py::test_obs_absorb_equivalent[([a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_absorb_not_equivalent[([a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_absorb_not_equivalent[([a:b=2]", "stix2/test/test_pattern_equivalence.py::test_obs_dnf_equivalent[[a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_not_equivalent[[a:b=1]", "stix2/test/test_pattern_equivalence.py::test_comp_dupe_equivalent[[a:b=1", "stix2/test/test_pattern_equivalence.py::test_comp_flatten_equivalent[[(a:b=1)]-[a:b=1]]", "stix2/test/test_pattern_equivalence.py::test_comp_flatten_equivalent[[(((((a:b=1)))))]-[(a:b=1)]]", "stix2/test/test_pattern_equivalence.py::test_comp_flatten_equivalent[[a:b=1", "stix2/test/test_pattern_equivalence.py::test_comp_flatten_equivalent[[(((a:b=1", "stix2/test/test_pattern_equivalence.py::test_comp_order_equivalent[[a:b=1", "stix2/test/test_pattern_equivalence.py::test_comp_order_equivalent[[(a:b=1", "stix2/test/test_pattern_equivalence.py::test_comp_absorb_equivalent[[a:b=1", "stix2/test/test_pattern_equivalence.py::test_comp_absorb_equivalent[[(a:b=1", "stix2/test/test_pattern_equivalence.py::test_comp_dnf_equivalent[[a:b=1", "stix2/test/test_pattern_equivalence.py::test_comp_dnf_equivalent[[(a:b=1", "stix2/test/test_pattern_equivalence.py::test_comp_not_equivalent[[a:b=1]-[a:b=2]]", "stix2/test/test_pattern_equivalence.py::test_comp_not_equivalent[[a:b=1", "stix2/test/test_pattern_equivalence.py::test_comp_not_equivalent[[(a:b=1", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv4[[ipv4-addr:value='1.2.3.4/32']-[ipv4-addr:value='1.2.3.4']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv4[[ipv4-addr:value='1.2.3.4/24']-[ipv4-addr:value='1.2.3.0/24']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv4[[ipv4-addr:value='1.2.255.4/23']-[ipv4-addr:value='1.2.254.0/23']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv4[[ipv4-addr:value='1.2.255.4/20']-[ipv4-addr:value='1.2.240.0/20']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv4[[ipv4-addr:value='1.2.255.4/0']-[ipv4-addr:value='0.0.0.0/0']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv4[[ipv4-addr:value='01.02.03.04']-[ipv4-addr:value='1.2.3.4']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv4[[ipv4-addr:value='1.2.3.4/-5']-[ipv4-addr:value='1.2.3.4/-5']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv4[[ipv4-addr:value='1.2.3.4/99']-[ipv4-addr:value='1.2.3.4/99']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv4[[ipv4-addr:value='foo']-[ipv4-addr:value='foo']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv4_not_equivalent[[ipv4-addr:value='1.2.3.4']-[ipv4-addr:value='1.2.3.5']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv4_not_equivalent[[ipv4-addr:value='1.2.3.4/1']-[ipv4-addr:value='1.2.3.4/2']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv4_not_equivalent[[ipv4-addr:value='foo']-[ipv4-addr:value='bar']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6[[ipv6-addr:value='1:2:3:4:5:6:7:8/128']-[ipv6-addr:value='1:2:3:4:5:6:7:8']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6[[ipv6-addr:value='1:2:3:4:5:6:7:8/112']-[ipv6-addr:value='1:2:3:4:5:6:7:0/112']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6[[ipv6-addr:value='1:2:3:4:5:6:ffff:8/111']-[ipv6-addr:value='1:2:3:4:5:6:fffe:0/111']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6[[ipv6-addr:value='1:2:3:4:5:6:ffff:8/104']-[ipv6-addr:value='1:2:3:4:5:6:ff00:0/104']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6[[ipv6-addr:value='1:2:3:4:5:6:7:8/0']-[ipv6-addr:value='0:0:0:0:0:0:0:0/0']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6[[ipv6-addr:value='0001:0000:0000:0000:0000:0000:0000:0001']-[ipv6-addr:value='1::1']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6[[ipv6-addr:value='0000:0000:0000:0000:0000:0000:0000:0000']-[ipv6-addr:value='::']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6[[ipv6-addr:value='1:2:3:4:5:6:7:8/-5']-[ipv6-addr:value='1:2:3:4:5:6:7:8/-5']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6[[ipv6-addr:value='1:2:3:4:5:6:7:8/99']-[ipv6-addr:value='1:2:3:4:5:6:7:8/99']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6[[ipv6-addr:value='foo']-[ipv6-addr:value='foo']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6_not_equivalent[[ipv6-addr:value='1:2:3:4:5:6:7:8']-[ipv6-addr:value='1:2:3:4:5:6:7:9']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6_not_equivalent[[ipv6-addr:value='1:2:3:4:5:6:7:8/1']-[ipv6-addr:value='1:2:3:4:5:6:7:8/2']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6_not_equivalent[[ipv6-addr:value='foo']-[ipv6-addr:value='bar']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_win_reg_key[[windows-registry-key:key", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_win_reg_key[[windows-registry-key:values[0].name", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_win_reg_key[[windows-registry-key:values[*].name", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_win_reg_key_not_equivalent[[windows-registry-key:key='foo']-[windows-registry-key:key='bar']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_win_reg_key_not_equivalent[[windows-registry-key:values[0].name='foo']-[windows-registry-key:values[0].name='bar']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_win_reg_key_not_equivalent[[windows-registry-key:values[*].name='foo']-[windows-registry-key:values[*].name='bar']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_win_reg_key_not_equivalent[[windows-registry-key:values[*].data='foo']-[windows-registry-key:values[*].data='FOO']]", "stix2/test/test_pattern_equivalence.py::test_comp_other_constant_types", "stix2/test/test_pattern_equivalence.py::test_find_equivalent_patterns" ]
2021-02-04 22:32:31+00:00
4,307
oasis-open__cti-python-stix2-534
diff --git a/stix2/equivalence/pattern/transform/comparison.py b/stix2/equivalence/pattern/transform/comparison.py index 93a80e4..9da91ef 100644 --- a/stix2/equivalence/pattern/transform/comparison.py +++ b/stix2/equivalence/pattern/transform/comparison.py @@ -13,8 +13,8 @@ from stix2.equivalence.pattern.transform.specials import ( ipv4_addr, ipv6_addr, windows_reg_key, ) from stix2.patterns import ( - AndBooleanExpression, OrBooleanExpression, ParentheticalExpression, - _BooleanExpression, _ComparisonExpression, + AndBooleanExpression, ObjectPath, OrBooleanExpression, + ParentheticalExpression, _BooleanExpression, _ComparisonExpression, ) @@ -22,12 +22,6 @@ def _dupe_ast(ast): """ Create a duplicate of the given AST. - Note: - The comparison expression "leaves", i.e. simple <path> <op> <value> - comparisons are currently not duplicated. I don't think it's necessary - as of this writing; they are never changed. But revisit this if/when - necessary. - Args: ast: The AST to duplicate @@ -45,9 +39,13 @@ def _dupe_ast(ast): ]) elif isinstance(ast, _ComparisonExpression): - # Change this to create a dupe, if we ever need to change simple - # comparison expressions as part of normalization. - result = ast + # Maybe we go as far as duping the ObjectPath object too? + new_object_path = ObjectPath( + ast.lhs.object_type_name, ast.lhs.property_path, + ) + result = _ComparisonExpression( + ast.operator, new_object_path, ast.rhs, ast.negated, + ) else: raise TypeError("Can't duplicate " + type(ast).__name__) @@ -333,17 +331,33 @@ class DNFTransformer(ComparisonExpressionTransformer): other_children.append(child) if or_children: - distributed_children = [ - AndBooleanExpression([ - # Make dupes: distribution implies adding repetition, and - # we should ensure each repetition is independent of the - # others. - _dupe_ast(sub_ast) for sub_ast in itertools.chain( - other_children, prod_seq, - ) - ]) + distributed_and_arg_sets = ( + itertools.chain(other_children, prod_seq) for prod_seq in itertools.product(*or_children) - ] + ) + + # The AST implementation will error if AND boolean comparison + # operands have no common SCO types. We need to handle that here. + # The following will drop AND's with no common SCO types, which is + # harmless (since they're impossible patterns and couldn't match + # anything anyway). It also acts as a nice simplification of the + # pattern. If the original AND node was legal (operands had at + # least one SCO type in common), it is guaranteed that there will + # be at least one legal distributed AND node (distributed_children + # below will not wind up empty). + distributed_children = [] + for and_arg_set in distributed_and_arg_sets: + try: + and_node = AndBooleanExpression( + # Make dupes: distribution implies adding repetition, + # and we should ensure each repetition is independent + # of the others. + _dupe_ast(arg) for arg in and_arg_set + ) + except ValueError: + pass + else: + distributed_children.append(and_node) # Need to recursively continue to distribute AND over OR in # any of our new sub-expressions which need it. This causes diff --git a/stix2/patterns.py b/stix2/patterns.py index a718bf7..c53a83f 100644 --- a/stix2/patterns.py +++ b/stix2/patterns.py @@ -505,7 +505,7 @@ class _BooleanExpression(_PatternExpression): def __init__(self, operator, operands): self.operator = operator self.operands = list(operands) - for arg in operands: + for arg in self.operands: if not hasattr(self, "root_types"): self.root_types = arg.root_types elif operator == "AND":
oasis-open/cti-python-stix2
81550cab92aaacbca5db0d37c607dfd1707ce4c3
diff --git a/stix2/test/test_pattern_equivalence.py b/stix2/test/test_pattern_equivalence.py index cebb9e7..a33caec 100644 --- a/stix2/test/test_pattern_equivalence.py +++ b/stix2/test/test_pattern_equivalence.py @@ -384,6 +384,15 @@ def test_comp_absorb_equivalent(patt1, patt2): "[a:b=1 AND (a:b=2 AND (a:b=3 OR a:b=4))]", "[(a:b=1 AND a:b=2 AND a:b=3) OR (a:b=1 AND a:b=2 AND a:b=4)]", ), + # Some tests with different SCO types + ( + "[(a:b=1 OR b:c=1) AND (b:d=1 OR c:d=1)]", + "[b:c=1 AND b:d=1]", + ), + ( + "[(a:b=1 OR b:c=1) AND (b:d=1 OR c:d=1)]", + "[(z:y=1 OR b:c=1) AND (b:d=1 OR x:w=1 OR v:u=1)]", + ), ], ) def test_comp_dnf_equivalent(patt1, patt2):
Pattern semantic equivalence comparison expression DNF transformer ignores SCO types The pattern semantic equivalence comparison expression DNF transformer rearranges an AST and can create new comparison expression AND nodes. Current AST AND node implementation will check whether all operands have an SCO type in common, as required by spec, and error if this is not the case. Some STIX patterns would cause the DNF transformer to create an AND node with no SCO types in common and trigger that error and crash. For example: [(a:b=1 OR b:c=1) AND (b:d=1 OR c:d=1)] would DNF transform to: [(a:b=1 AND b:d=1) OR (a:b=1 AND c:d=1) OR (b:c=1 AND b:d=1) OR (b:c=1 AND c:d=1)] The first, second, and fourth AND expressions mix different SCO types and cause the error.
0.0
[ "stix2/test/test_pattern_equivalence.py::test_comp_dnf_equivalent[[(a:b=1" ]
[ "stix2/test/test_pattern_equivalence.py::test_obs_dupe_equivalent[[a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_dupe_not_equivalent[[a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_flatten_equivalent[[a:b=1]-([a:b=1])]", "stix2/test/test_pattern_equivalence.py::test_obs_flatten_equivalent[(((([a:b=1]))))-([a:b=1])]", "stix2/test/test_pattern_equivalence.py::test_obs_flatten_equivalent[[a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_flatten_equivalent[([a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_flatten_not_equivalent[([a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_flatten_not_equivalent[[a:b=1]-([a:b=1])", "stix2/test/test_pattern_equivalence.py::test_obs_flatten_not_equivalent[(((([a:b=1]))))-([a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_flatten_not_equivalent[[a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_order_equivalent[[a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_order_not_equivalent[[a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_absorb_equivalent[[a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_absorb_equivalent[([a:b=3]", "stix2/test/test_pattern_equivalence.py::test_obs_absorb_equivalent[([a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_absorb_not_equivalent[([a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_absorb_not_equivalent[([a:b=2]", "stix2/test/test_pattern_equivalence.py::test_obs_dnf_equivalent[[a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_dnf_equivalent[([a:b=1]", "stix2/test/test_pattern_equivalence.py::test_obs_not_equivalent[[a:b=1]", "stix2/test/test_pattern_equivalence.py::test_comp_dupe_equivalent[[a:b=1", "stix2/test/test_pattern_equivalence.py::test_comp_flatten_equivalent[[(a:b=1)]-[a:b=1]]", "stix2/test/test_pattern_equivalence.py::test_comp_flatten_equivalent[[(((((a:b=1)))))]-[(a:b=1)]]", "stix2/test/test_pattern_equivalence.py::test_comp_flatten_equivalent[[a:b=1", "stix2/test/test_pattern_equivalence.py::test_comp_flatten_equivalent[[(((a:b=1", "stix2/test/test_pattern_equivalence.py::test_comp_order_equivalent[[a:b=1", "stix2/test/test_pattern_equivalence.py::test_comp_order_equivalent[[(a:b=1", "stix2/test/test_pattern_equivalence.py::test_comp_absorb_equivalent[[a:b=1", "stix2/test/test_pattern_equivalence.py::test_comp_absorb_equivalent[[(a:b=1", "stix2/test/test_pattern_equivalence.py::test_comp_dnf_equivalent[[a:b=1", "stix2/test/test_pattern_equivalence.py::test_comp_not_equivalent[[a:b=1]-[a:b=2]]", "stix2/test/test_pattern_equivalence.py::test_comp_not_equivalent[[a:b=1", "stix2/test/test_pattern_equivalence.py::test_comp_not_equivalent[[(a:b=1", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv4[[ipv4-addr:value='1.2.3.4/32']-[ipv4-addr:value='1.2.3.4']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv4[[ipv4-addr:value='1.2.3.4/24']-[ipv4-addr:value='1.2.3.0/24']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv4[[ipv4-addr:value='1.2.255.4/23']-[ipv4-addr:value='1.2.254.0/23']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv4[[ipv4-addr:value='1.2.255.4/20']-[ipv4-addr:value='1.2.240.0/20']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv4[[ipv4-addr:value='1.2.255.4/0']-[ipv4-addr:value='0.0.0.0/0']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv4[[ipv4-addr:value='01.02.03.04']-[ipv4-addr:value='1.2.3.4']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv4[[ipv4-addr:value='1.2.3.4/-5']-[ipv4-addr:value='1.2.3.4/-5']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv4[[ipv4-addr:value='1.2.3.4/99']-[ipv4-addr:value='1.2.3.4/99']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv4[[ipv4-addr:value='foo']-[ipv4-addr:value='foo']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv4_not_equivalent[[ipv4-addr:value='1.2.3.4']-[ipv4-addr:value='1.2.3.5']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv4_not_equivalent[[ipv4-addr:value='1.2.3.4/1']-[ipv4-addr:value='1.2.3.4/2']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv4_not_equivalent[[ipv4-addr:value='foo']-[ipv4-addr:value='bar']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6[[ipv6-addr:value='1:2:3:4:5:6:7:8/128']-[ipv6-addr:value='1:2:3:4:5:6:7:8']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6[[ipv6-addr:value='1:2:3:4:5:6:7:8/112']-[ipv6-addr:value='1:2:3:4:5:6:7:0/112']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6[[ipv6-addr:value='1:2:3:4:5:6:ffff:8/111']-[ipv6-addr:value='1:2:3:4:5:6:fffe:0/111']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6[[ipv6-addr:value='1:2:3:4:5:6:ffff:8/104']-[ipv6-addr:value='1:2:3:4:5:6:ff00:0/104']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6[[ipv6-addr:value='1:2:3:4:5:6:7:8/0']-[ipv6-addr:value='0:0:0:0:0:0:0:0/0']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6[[ipv6-addr:value='0001:0000:0000:0000:0000:0000:0000:0001']-[ipv6-addr:value='1::1']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6[[ipv6-addr:value='0000:0000:0000:0000:0000:0000:0000:0000']-[ipv6-addr:value='::']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6[[ipv6-addr:value='1:2:3:4:5:6:7:8/-5']-[ipv6-addr:value='1:2:3:4:5:6:7:8/-5']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6[[ipv6-addr:value='1:2:3:4:5:6:7:8/99']-[ipv6-addr:value='1:2:3:4:5:6:7:8/99']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6[[ipv6-addr:value='foo']-[ipv6-addr:value='foo']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6_not_equivalent[[ipv6-addr:value='1:2:3:4:5:6:7:8']-[ipv6-addr:value='1:2:3:4:5:6:7:9']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6_not_equivalent[[ipv6-addr:value='1:2:3:4:5:6:7:8/1']-[ipv6-addr:value='1:2:3:4:5:6:7:8/2']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_ipv6_not_equivalent[[ipv6-addr:value='foo']-[ipv6-addr:value='bar']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_win_reg_key[[windows-registry-key:key", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_win_reg_key[[windows-registry-key:values[0].name", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_win_reg_key[[windows-registry-key:values[*].name", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_win_reg_key_not_equivalent[[windows-registry-key:key='foo']-[windows-registry-key:key='bar']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_win_reg_key_not_equivalent[[windows-registry-key:values[0].name='foo']-[windows-registry-key:values[0].name='bar']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_win_reg_key_not_equivalent[[windows-registry-key:values[*].name='foo']-[windows-registry-key:values[*].name='bar']]", "stix2/test/test_pattern_equivalence.py::test_comp_special_canonicalization_win_reg_key_not_equivalent[[windows-registry-key:values[*].data='foo']-[windows-registry-key:values[*].data='FOO']]", "stix2/test/test_pattern_equivalence.py::test_comp_other_constant_types", "stix2/test/test_pattern_equivalence.py::test_find_equivalent_patterns" ]
2021-12-23 07:07:23+00:00
4,308
oasis-open__cti-python-stix2-74
diff --git a/stix2/core.py b/stix2/core.py index 3eaabb0..8ee11f5 100644 --- a/stix2/core.py +++ b/stix2/core.py @@ -15,6 +15,10 @@ from .utils import get_dict class STIXObjectProperty(Property): + def __init__(self, allow_custom=False): + self.allow_custom = allow_custom + super(STIXObjectProperty, self).__init__() + def clean(self, value): try: dictified = get_dict(value) @@ -25,7 +29,10 @@ class STIXObjectProperty(Property): if 'type' in dictified and dictified['type'] == 'bundle': raise ValueError('This property may not contain a Bundle object') - parsed_obj = parse(dictified) + if self.allow_custom: + parsed_obj = parse(dictified, allow_custom=True) + else: + parsed_obj = parse(dictified) return parsed_obj @@ -48,6 +55,10 @@ class Bundle(_STIXBase): else: kwargs['objects'] = list(args) + kwargs.get('objects', []) + allow_custom = kwargs.get('allow_custom', False) + if allow_custom: + self._properties['objects'] = ListProperty(STIXObjectProperty(True)) + super(Bundle, self).__init__(**kwargs) diff --git a/stix2/properties.py b/stix2/properties.py index afe994f..ca7f04c 100644 --- a/stix2/properties.py +++ b/stix2/properties.py @@ -124,7 +124,11 @@ class ListProperty(Property): obj_type = self.contained.type elif type(self.contained).__name__ is 'STIXObjectProperty': # ^ this way of checking doesn't require a circular import - obj_type = type(valid) + # valid is already an instance of a python-stix2 class; no need + # to turn it into a dictionary and then pass it to the class + # constructor again + result.append(valid) + continue else: obj_type = self.contained
oasis-open/cti-python-stix2
3c80e5e7ebb641b5feb55337f9470ec9d9d58572
diff --git a/stix2/test/test_custom.py b/stix2/test/test_custom.py index ff432c1..48529b9 100644 --- a/stix2/test/test_custom.py +++ b/stix2/test/test_custom.py @@ -81,6 +81,18 @@ def test_parse_identity_custom_property(data): assert identity.foo == "bar" +def test_custom_property_in_bundled_object(): + identity = stix2.Identity( + name="John Smith", + identity_class="individual", + x_foo="bar", + allow_custom=True, + ) + bundle = stix2.Bundle(identity, allow_custom=True) + + assert bundle.objects[0].x_foo == "bar" + + @stix2.sdo.CustomObject('x-new-type', [ ('property1', stix2.properties.StringProperty(required=True)), ('property2', stix2.properties.IntegerProperty()),
Unable to creat 'Bundle' when using custom fields with SDO Hi, When attempting to generate a bundle, a failure message is created when passing an SDO with custom objects even with `allow_custom=True` set on the SDO object. example: `v = factory.create( Vulnerability, name="Test Vulnerability", custom_field = "This is custom", allow_custom=True )` `print Bundle(v)` Will result in the following output: `File "stix.py", line 142, in <module> print Bundle(v) File "/usr/local/lib/python2.7/dist-packages/stix2/core.py", line 51, in __init__ super(Bundle, self).__init__(**kwargs) File "/usr/local/lib/python2.7/dist-packages/stix2/base.py", line 121, in __init__ self._check_property(prop_name, prop_metadata, setting_kwargs) File "/usr/local/lib/python2.7/dist-packages/stix2/base.py", line 55, in _check_property kwargs[prop_name] = prop.clean(kwargs[prop_name]) File "/usr/local/lib/python2.7/dist-packages/stix2/properties.py", line 115, in clean valid = self.contained.clean(item) File "/usr/local/lib/python2.7/dist-packages/stix2/core.py", line 28, in clean parsed_obj = parse(dictified) File "/usr/local/lib/python2.7/dist-packages/stix2/core.py", line 94, in parse return obj_class(allow_custom=allow_custom, **obj) File "/usr/local/lib/python2.7/dist-packages/stix2/base.py", line 104, in __init__ raise ExtraPropertiesError(cls, extra_kwargs) stix2.exceptions.ExtraPropertiesError: Unexpected properties for Vulnerability: (custom_field).`
0.0
[ "stix2/test/test_custom.py::test_custom_property_in_bundled_object" ]
[ "stix2/test/test_custom.py::test_identity_custom_property", "stix2/test/test_custom.py::test_identity_custom_property_invalid", "stix2/test/test_custom.py::test_identity_custom_property_allowed", "stix2/test/test_custom.py::test_parse_identity_custom_property[{\\n", "stix2/test/test_custom.py::test_custom_object_type", "stix2/test/test_custom.py::test_parse_custom_object_type", "stix2/test/test_custom.py::test_parse_unregistered_custom_object_type", "stix2/test/test_custom.py::test_custom_observable_object", "stix2/test/test_custom.py::test_custom_observable_object_invalid_ref_property", "stix2/test/test_custom.py::test_custom_observable_object_invalid_refs_property", "stix2/test/test_custom.py::test_custom_observable_object_invalid_refs_list_property", "stix2/test/test_custom.py::test_custom_observable_object_invalid_valid_refs", "stix2/test/test_custom.py::test_custom_no_properties_raises_exception", "stix2/test/test_custom.py::test_custom_wrong_properties_arg_raises_exception", "stix2/test/test_custom.py::test_parse_unregistered_custom_observable_object", "stix2/test/test_custom.py::test_parse_invalid_custom_observable_object", "stix2/test/test_custom.py::test_observable_custom_property", "stix2/test/test_custom.py::test_observable_custom_property_invalid", "stix2/test/test_custom.py::test_observable_custom_property_allowed", "stix2/test/test_custom.py::test_custom_extension", "stix2/test/test_custom.py::test_custom_extension_wrong_observable_type", "stix2/test/test_custom.py::test_custom_extension_invalid_observable", "stix2/test/test_custom.py::test_custom_extension_no_properties", "stix2/test/test_custom.py::test_custom_extension_empty_properties", "stix2/test/test_custom.py::test_parse_observable_with_custom_extension", "stix2/test/test_custom.py::test_parse_observable_with_unregistered_custom_extension" ]
2017-10-09 21:36:36+00:00
4,309
oasis-open__cti-stix-elevator-195
diff --git a/idioms-json-2.1-valid/Appendix_G_IOCs_Full.json b/idioms-json-2.1-valid/Appendix_G_IOCs_Full.json index b6c60fb..2f62f74 100644 --- a/idioms-json-2.1-valid/Appendix_G_IOCs_Full.json +++ b/idioms-json-2.1-valid/Appendix_G_IOCs_Full.json @@ -1451,4 +1451,4 @@ } ], "type": "bundle" -} +} \ No newline at end of file diff --git a/stix2elevator/cli.py b/stix2elevator/cli.py index eaa19c6..feb35ee 100644 --- a/stix2elevator/cli.py +++ b/stix2elevator/cli.py @@ -107,8 +107,8 @@ def _get_arg_parser(is_script=True): help="A comma-separated list of the stix2-elevator messages to enable. " "If the --disable option is not used, no other messages will be " "shown. \n\nExample: stix2_elevator.py <file> --enable 250", - dest="enable", - default="" + dest="enabled", + default=None ) parser.add_argument( @@ -116,8 +116,8 @@ def _get_arg_parser(is_script=True): "--disable", help="A comma-separated list of the stix2-elevator messages to disable. \n\n" "Example: stix2_elevator.py <file> --disable 212,220", - dest="disable", - default="" + dest="disabled", + default=None ) parser.add_argument( diff --git a/stix2elevator/options.py b/stix2elevator/options.py index 86f4a1a..8ff2377 100644 --- a/stix2elevator/options.py +++ b/stix2elevator/options.py @@ -1,8 +1,9 @@ +import copy import logging import os import shlex -from six import text_type +from six import string_types from stix2validator.scripts import stix2_validator ALL_OPTIONS = None @@ -86,6 +87,29 @@ def setup_logger(package_id): log.addHandler(fh) +def _convert_to_int_list(check_codes): + """Takes a comma-separated string or list of strings and converts to list of ints. + + Args: + check_codes: comma-separated string or list of strings + + Returns: + list: the check codes as a list of integers + + Raises: + ValueError: if conversion fails + RuntimeError: if cannot determine how to convert input + """ + if isinstance(check_codes, list): + if all(isinstance(x, int) for x in check_codes): + return check_codes # good input + else: + return [int(x) for x in check_codes] # list of str + elif isinstance(check_codes, string_types): + return [int(x) for x in check_codes.split(",")] # str, comma-separated expected + raise RuntimeError("Could not convert values: {} of type {}".format(check_codes, type(check_codes))) + + class ElevatorOptions(object): """Collection of stix2-elevator options which can be set via command line or programmatically in a script. @@ -107,8 +131,8 @@ class ElevatorOptions(object): When this value is not set, current time will be used instead. validator_args: If set, these values will be used to create a ValidationOptions instance if requested. The elevator should not produce any custom objects. - enable: Messages to enable. - disable: Messages to disable. + enabled: Messages to enable. Expects a list of ints. + disabled: Messages to disable. Expects a list of ints. silent: If set, no stix2-elevator log messages will be emitted. message_log_directory: If set, it will write all emitted messages to file. It will use the filename or package id to name the log file. @@ -119,7 +143,7 @@ class ElevatorOptions(object): def __init__(self, cmd_args=None, file_=None, incidents=False, missing_policy="add-to-description", custom_property_prefix="elevator", infrastructure=False, package_created_by_id=None, default_timestamp=None, - validator_args="--strict-types", enable="", disable="", + validator_args="--strict-types", enabled=None, disabled=None, silent=False, message_log_directory=None, policy="no_policy", output_directory=None, log_level="INFO", markings_allowed="", spec_version="2.0"): @@ -135,8 +159,8 @@ class ElevatorOptions(object): self.default_timestamp = cmd_args.default_timestamp self.validator_args = cmd_args.validator_args - self.enable = cmd_args.enable - self.disable = cmd_args.disable + self.enabled = cmd_args.enabled + self.disabled = cmd_args.disabled self.silent = cmd_args.silent self.policy = cmd_args.policy self.message_log_directory = cmd_args.message_log_directory @@ -144,9 +168,6 @@ class ElevatorOptions(object): self.markings_allowed = cmd_args.markings_allowed if hasattr(cmd_args, "output_directory"): self.output_directory = cmd_args.output_directory - # validator arg --silent is currently broken - # if self.silent: - # self.validator_args += " --silent" self.spec_version = cmd_args.spec_version else: @@ -159,8 +180,8 @@ class ElevatorOptions(object): self.default_timestamp = default_timestamp self.validator_args = validator_args - self.enable = enable - self.disable = disable + self.enabled = enabled + self.disabled = disabled self.silent = silent self.policy = policy self.message_log_directory = message_log_directory @@ -172,33 +193,65 @@ class ElevatorOptions(object): if self.validator_args.find("--version") == -1: self.validator_args = self.validator_args + " --version " + self.spec_version - # Convert string of comma-separated checks to a list, - # and convert check code numbers to names. By default all messages are - # enabled. - if self.disable: - self.disabled = self.disable.split(",") - self.disabled = [CHECK_CODES[x] if x in CHECK_CODES else x - for x in self.disabled] - else: - self.disabled = [] - - if self.enable: - self.enabled = self.enable.split(",") - self.enabled = [CHECK_CODES[x] if x in CHECK_CODES else x - for x in self.enabled] - else: - self.enabled = [text_type(x) for x in CHECK_CODES] - if self.markings_allowed: self.markings_allowed = self.markings_allowed.split(",") self.marking_container = None + @property + def disabled(self): + return self._disabled + + @disabled.setter + def disabled(self, disabled): + def remove_silent(item, elements): + try: + elements.remove(item) + except ValueError: + pass # suppress exception if value is not present + # Convert string of comma-separated checks to a list, + # and convert check code numbers to names. By default no messages are + # disabled. + if disabled: + self._disabled = _convert_to_int_list(disabled) + self._disabled = [x for x in self._disabled if x in CHECK_CODES] + for x in self._disabled: + remove_silent(x, self._enabled) + else: + self._disabled = [] + + @property + def enabled(self): + return self._enabled + + @enabled.setter + def enabled(self, enabled): + def remove_silent(item, elements): + try: + elements.remove(item) + except ValueError: + pass # suppress exception if value is not present + # Convert string of comma-separated checks to a list, + # and convert check code numbers to names. By default all messages are + # enabled. + if enabled: + self._enabled = _convert_to_int_list(enabled) + self._enabled = [x for x in self._enabled if x in CHECK_CODES] + for x in self._enabled: + remove_silent(x, self._disabled) + else: + self._enabled = copy.deepcopy(CHECK_CODES) + -def initialize_options(**kwargs): +def initialize_options(options=None): global ALL_OPTIONS if not ALL_OPTIONS: - ALL_OPTIONS = ElevatorOptions(**kwargs) + if isinstance(options, ElevatorOptions): + ALL_OPTIONS = options + elif isinstance(options, dict): + ALL_OPTIONS = ElevatorOptions(**options) + else: + ALL_OPTIONS = ElevatorOptions(options) if ALL_OPTIONS.silent and ALL_OPTIONS.message_log_directory: warn("Both console and output log have disabled messages.", 209) @@ -232,8 +285,6 @@ def set_option_value(option_name, option_value): def msg_id_enabled(msg_id): - msg_id = text_type(msg_id) - if get_option_value("silent"): return False
oasis-open/cti-stix-elevator
077cda7dc2bb9d04fd24dd93e89d2a1d988d539d
diff --git a/stix2elevator/test/test_main.py b/stix2elevator/test/test_main.py index a962429..8b97a01 100644 --- a/stix2elevator/test/test_main.py +++ b/stix2elevator/test/test_main.py @@ -1,3 +1,4 @@ +from argparse import Namespace import io import os @@ -9,8 +10,12 @@ import pytest from stix2elevator import (elevate, elevate_file, elevate_package, - elevate_string) -from stix2elevator.options import initialize_options, set_option_value + elevate_string, + options) +from stix2elevator.options import (ElevatorOptions, + get_option_value, + initialize_options, + set_option_value) from stix2elevator.utils import find_dir # This module only tests for the main functions used to interact with the elevator from a programmatic or @@ -29,6 +34,24 @@ def setup_options(): set_option_value("policy", "no_policy") [email protected]("opts", [ + ElevatorOptions(policy="no_policy", spec_version="2.1", log_level="DEBUG", disabled=[212, 901]), + {"policy": "no_policy", "spec_version": "2.1", "log_level": "DEBUG", "disabled": [212, 901]}, + Namespace(policy="no_policy", spec_version="2.1", log_level="DEBUG", disabled="212,901", + file_=None, incidents=False, missing_policy="add-to-description", + custom_property_prefix="elevator", infrastructure=False, package_created_by_id=None, + default_timestamp=None, validator_args="--strict-types", enabled=None, silent=False, + message_log_directory=None, output_directory=None, markings_allowed=""), +]) +def test_setup_options(opts): + options.ALL_OPTIONS = None # To make sure we can set it again + initialize_options(opts) + assert get_option_value("policy") == "no_policy" + assert get_option_value("spec_version") == "2.1" + assert get_option_value("log_level") == "DEBUG" + assert get_option_value("disabled") == [212, 901] + + def test_elevate_with_marking_container(): setup_options() diff --git a/stix2elevator/test/test_utils.py b/stix2elevator/test/test_utils.py index 93c6aa3..bb1eea2 100644 --- a/stix2elevator/test/test_utils.py +++ b/stix2elevator/test/test_utils.py @@ -1,6 +1,8 @@ from stix.indicator import Indicator +import pytest from stix2elevator import convert_stix, utils +from stix2elevator.options import _convert_to_int_list from stix2elevator.utils import Environment @@ -26,3 +28,23 @@ def test_convert_timestamp_string(): indicator = Indicator() indicator_instance = convert_stix.create_basic_object("indicator", indicator, env) assert indicator_instance is not None + + [email protected]("data", [ + [123, 245, 344], + "123,245,344", + ["123", "245", 344], +]) +def test_convert_int_function(data): + assert _convert_to_int_list(data) == [123, 245, 344] + + [email protected]("data", [ + "12 3,245,344", + "212,garbage,33", + "definitely-not,an_int", + 234, +]) +def test_convert_int_function_bad(data): + with pytest.raises((RuntimeError, ValueError)): + _convert_to_int_list(data)
The disable/enable option are not handled correctly. The use case is: programmatically enable/disable messages at any time. Because of the way the enable/disable option works, using set_option_value will not work as expected A user would have to know that the “real” option is disabled, not disable There also seems to be an issue with the processing of the enable/disable option. They are strings from the command line, but CHECK_CODES has integers.
0.0
[ "stix2elevator/test/test_main.py::test_setup_options[opts0]", "stix2elevator/test/test_main.py::test_setup_options[opts1]", "stix2elevator/test/test_main.py::test_setup_options[opts2]", "stix2elevator/test/test_utils.py::test_strftime_with_appropriate_fractional_seconds", "stix2elevator/test/test_utils.py::test_convert_timestamp_string", "stix2elevator/test/test_utils.py::test_convert_int_function[data0]", "stix2elevator/test/test_utils.py::test_convert_int_function[123,245,344]", "stix2elevator/test/test_utils.py::test_convert_int_function[data2]", "stix2elevator/test/test_utils.py::test_convert_int_function_bad[12", "stix2elevator/test/test_utils.py::test_convert_int_function_bad[212,garbage,33]", "stix2elevator/test/test_utils.py::test_convert_int_function_bad[definitely-not,an_int]", "stix2elevator/test/test_utils.py::test_convert_int_function_bad[234]" ]
[]
2020-03-10 04:12:28+00:00
4,310
oasis-open__cti-stix-validator-109
diff --git a/stix2validator/v21/musts.py b/stix2validator/v21/musts.py index 9c71fa9..776adc4 100644 --- a/stix2validator/v21/musts.py +++ b/stix2validator/v21/musts.py @@ -408,6 +408,9 @@ def patterns(instance, options): if instance['type'] != 'indicator' or 'pattern' not in instance: return + if instance['pattern_type'] != 'stix': + return + pattern = instance['pattern'] if not isinstance(pattern, string_types): return # This error already caught by schemas
oasis-open/cti-stix-validator
3e2486c337b9e72e18443d26804556d147e9d6cd
diff --git a/stix2validator/test/v21/indicator_tests.py b/stix2validator/test/v21/indicator_tests.py index 778827c..b45ae39 100644 --- a/stix2validator/test/v21/indicator_tests.py +++ b/stix2validator/test/v21/indicator_tests.py @@ -240,3 +240,15 @@ class IndicatorTestCases(ValidatorTest): self.assertFalseWithOptions(indicator) self.check_ignore(indicator, 'indicator-properties') + + def test_indicator_different_pattern_type_does_not_get_validated(self): + pattern = ("alert tcp any any <> any 80 (msg:\"SHA256 Alert\";" + " protected_content:\"56D6F32151AD8474F40D7B939C2161EE2BBF10023F4AF1DBB3E13260EBDC6342\";" + " hash:sha256; offset:0; length:4;)") + indicator = copy.deepcopy(self.valid_indicator) + indicator["pattern"] = pattern + indicator["pattern_type"] = "snort" + indicator["pattern_version"] = "2.9.15" + + results = validate_parsed_json(indicator, self.options) + self.assertEqual(results.is_valid, True) diff --git a/stix2validator/test/v21/network_traffic_tests.py b/stix2validator/test/v21/network_traffic_tests.py index 7014d89..e38b45b 100644 --- a/stix2validator/test/v21/network_traffic_tests.py +++ b/stix2validator/test/v21/network_traffic_tests.py @@ -98,7 +98,9 @@ class ObservedDataTestCases(ValidatorTest): "address_family": "AF_INET", "socket_type": "SOCK_STREAM", "options": { - "foo": "bar" + "SO_TEST": 1000, + "IP_TEST": 100, + "MCAST_TEST": 10 } } }
The pattern validator should not be invoked for non-STIX patterns If the pattern type is snort, the STIX validator will still try to see if it is valid for the STIX Pattern language - which of course it isn't. We should not output a warning in these cases.
0.0
[ "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_indicator_different_pattern_type_does_not_get_validated" ]
[ "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_additional_schemas", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_additional_schemas_custom_type", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_additional_schemas_custom_type_invalid_schema", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_custom_property_name_invalid_character", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_custom_property_name_long", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_custom_property_name_short", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_custom_property_name_strict", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_empty_list", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_indicator_missing_description", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_indicator_missing_name", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_indicator_missing_name_description", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_invalid_lang", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_invalid_pattern", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_modified_before_created", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_pattern_custom_invalid_format", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_pattern_custom_object_noprefix", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_pattern_custom_object_prefix_lax", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_pattern_custom_object_prefix_strict", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_pattern_custom_property_prefix_strict", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_pattern_list_object_property", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_pattern_with_escaped_slashes", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_reserved_object_type_infrastructure", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_reserved_property_action", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_validate_parsed_json_list_additional_invalid_schema", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_vocab_indicator_types", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_wellformed_indicator", "stix2validator/test/v21/network_traffic_tests.py::ObservedDataTestCases::test_invalid_start_end_time", "stix2validator/test/v21/network_traffic_tests.py::ObservedDataTestCases::test_network_traffic_http_request_header", "stix2validator/test/v21/network_traffic_tests.py::ObservedDataTestCases::test_network_traffic_ipfix", "stix2validator/test/v21/network_traffic_tests.py::ObservedDataTestCases::test_network_traffic_protocols", "stix2validator/test/v21/network_traffic_tests.py::ObservedDataTestCases::test_network_traffic_socket_options", "stix2validator/test/v21/network_traffic_tests.py::ObservedDataTestCases::test_wellformed_network_traffic" ]
2019-12-12 14:49:56+00:00
4,311
oasis-open__cti-stix-validator-111
diff --git a/docs/best-practices.rst b/docs/best-practices.rst index e9cf8a1..16782ed 100644 --- a/docs/best-practices.rst +++ b/docs/best-practices.rst @@ -154,6 +154,9 @@ Check Codes - STIX 2.1 | 244 | account-type | certain property values are from the | | | | account-type vocabulary | +--------+-----------------------------+----------------------------------------+ +| 245 | indicator-pattern-types | certain property values are from the | +| | | pattern-type vocabulary | ++--------+-----------------------------+----------------------------------------+ | 270 | all-external-sources | all of the following external source | | | | checks are run | +--------+-----------------------------+----------------------------------------+ diff --git a/stix2validator/schemas-2.1 b/stix2validator/schemas-2.1 index 61ee50e..5d0d5a2 160000 --- a/stix2validator/schemas-2.1 +++ b/stix2validator/schemas-2.1 @@ -1,1 +1,1 @@ -Subproject commit 61ee50e5d4e9c69b2b878da9596bd79638cd9054 +Subproject commit 5d0d5a2ee364215acb1f15db0016f3c1c17360bc diff --git a/stix2validator/util.py b/stix2validator/util.py index e3b0398..29654cb 100644 --- a/stix2validator/util.py +++ b/stix2validator/util.py @@ -106,6 +106,8 @@ https://stix2-validator.readthedocs.io/en/latest/best-practices.html. | | | windows-pebinary-type vocabulary | | 244 | account-type | certain property values are from the | | | | account-type vocabulary | +| 245 | indicator-pattern-types | certain property values are from the | +| | | pattern-type vocabulary | | 270 | all-external-sources | all of the following external source | | | | checks are run | | 271 | mime-type | file.mime_type is a valid IANA MIME | diff --git a/stix2validator/v21/enums.py b/stix2validator/v21/enums.py index 5737ad1..5fe7172 100644 --- a/stix2validator/v21/enums.py +++ b/stix2validator/v21/enums.py @@ -188,6 +188,14 @@ MALWARE_CAPABILITIES_OV = [ "steals-authentication-credentials", "violates-system-operational-integrity", ] +INDICATOR_PATTERN_OV = [ + "stix", + "pcre", + "sigma", + "snort", + "suricata", + "yara", +] PROCESSOR_ARCHITECTURE_OV = [ "alpha", "arm", @@ -286,19 +294,13 @@ TOOL_TYPE_OV = [ ] HASH_ALGO_OV = [ "MD5", - "MD6", - "RIPEMD-160", "SHA-1", - "SHA-224", "SHA-256", - "SHA-384", "SHA-512", - "SHA3-224", "SHA3-256", - "SHA3-384", "SHA3-512", - "ssdeep", - "WHIRLPOOL", + "SSDEEP", + "TLSH", ] WINDOWS_PEBINARY_TYPE_OV = [ "exe", @@ -365,6 +367,9 @@ IMPLEMENTATION_LANGUAGES_USES = { INDICATOR_TYPE_USES = { "indicator": ["indicator_types"], } +INDICATOR_PATTERN_USES = { + "indicator": ["pattern_type"], +} INFRASTRUCTURE_TYPE_USES = { "infrastructure": ["infrastructure_types"], } @@ -2112,6 +2117,7 @@ CHECK_CODES = { '241': 'hash-algo', '243': 'windows-pebinary-type', '244': 'account-type', + '245': 'indicator-pattern-types', '270': 'all-external-sources', '271': 'mime-type', '272': 'protocols', @@ -2253,34 +2259,202 @@ def ipfix(): return ipfix.ipflist +# If you have a Socket Option not present in this list +# for SO|ICMP|ICMP6|IP|IPV6|MCAST|TCP|IRLMP please open an issue/PR +# in https://github.com/oasis-open/cti-stix-validator/ to include it. +# Include a reference (link) to where its defined. SOCKET_OPTIONS = [ + 'ICMP6_FILTER', + 'IP_ADD_MEMBERSHIP', + 'IP_ADD_SOURCE_MEMBERSHIP', + 'IP_BIND_ADDRESS_NO_PORT', + 'IP_BLOCK_SOURCE', + 'IP_DONTFRAGMENT', + 'IP_DROP_MEMBERSHIP', + 'IP_DROP_SOURCE_MEMBERSHIP', + 'IP_FREEBIND', + 'IP_HDRINCL', + 'IP_MSFILTER', + 'IP_MTU', + 'IP_MTU_DISCOVER', + 'IP_MULTICAST_ALL', + 'IP_MULTICAST_IF', + 'IP_MULTICAST_LOOP', + 'IP_MULTICAST_TTL', + 'IP_NODEFRAG', + 'IP_OPTIONS', + 'IP_ORIGINAL_ARRIVAL_IF', + 'IP_PKTINFO', + 'IP_RECEIVE_BROADCAST', + 'IP_RECVDSTADDR', + 'IP_RECVERR', + 'IP_RECVIF', + 'IP_RECVOPTS', + 'IP_RECVORIGDSTADDR', + 'IP_RECVTOS', + 'IP_RECVTTL', + 'IP_RETOPTS', + 'IP_ROUTER_ALERT', + 'IP_TOS', + 'IP_TRANSPARENT', + 'IP_TTL', + 'IP_UNBLOCK_SOURCE', + 'IP_UNICAST_IF', + 'IP_WFP_REDIRECT_CONTEXT', + 'IP_WFP_REDIRECT_RECORDS', + 'IPV6_ADD_MEMBERSHIP', + 'IPV6_CHECKSUM', + 'IPV6_DONTFRAG', + 'IPV6_DROP_MEMBERSHIP', + 'IPV6_DSTOPTS', + 'IPV6_HDRINCL', + 'IPV6_HOPLIMIT', + 'IPV6_HOPOPTS', + 'IPV6_JOIN_GROUP', + 'IPV6_LEAVE_GROUP', + 'IPV6_MTU', + 'IPV6_MTU_DISCOVER', + 'IPV6_MULTICAST_HOPS', + 'IPV6_MULTICAST_IF', + 'IPV6_MULTICAST_LOOP', + 'IPV6_NEXTHOP', + 'IPV6_PATHMTU', + 'IPV6_PKTINFO', + 'IPV6_PROTECTION_LEVEL', + 'IPV6_RECVDSTOPTS', + 'IPV6_RECVHOPLIMIT', + 'IPV6_RECVHOPOPTS', + 'IPV6_RECVIF', + 'IPV6_RECVPATHMTU', + 'IPV6_RECVPKTINFO', + 'IPV6_RECVRTHDR', + 'IPV6_RECVTCLASS', + 'IPV6_RTHDR', + 'IPV6_TCLASS', + 'IPV6_UNICAST_HOPS', + 'IPV6_UNICAST_IF', + 'IPV6_UNICAT_HOPS', + 'IPV6_USE_MIN_MTU', + 'IPV6_V6ONLY', + 'IRLMP_9WIRE_MODE', + 'IRLMP_DISCOVERY_MODE', + 'IRLMP_ENUMDEVICES', + 'IRLMP_EXCLUSIVE_MODE', + 'IRLMP_IAS_QUERY', + 'IRLMP_IAS_SET', + 'IRLMP_IRLPT_MODE', + 'IRLMP_PARAMETERS', + 'IRLMP_SEND_PDU_LEN', + 'IRLMP_SHARP_MODE', + 'IRLMP_TINYTP_MODE', + 'MCAST_BLOCK_SOURCE', + 'MCAST_JOIN_GROUP', + 'MCAST_JOIN_SOURCE_GROUP', + 'MCAST_LEAVE_GROUP', + 'MCAST_LEAVE_SOURCE_GROUP', + 'MCAST_UNBLOCK_SOURCE', 'SO_ACCEPTCONN', + 'SO_ATTACH_BPF', + 'SO_ATTACH_FILTER', + 'SO_ATTACH_REUSEPORT_CBPF', 'SO_BINDTODEVICE', 'SO_BROADCAST', 'SO_BSDCOMPAT', + 'SO_BSP_STATE', + 'SO_BUSY_POLL', + 'SO_CONDITIONAL_ACCEPT', + 'SO_CONFIRM_NAME', + 'SO_CONNDATA', + 'SO_CONNDATALEN', + 'SO_CONNECT_TIME', + 'SO_CONNOPT', + 'SO_CONNOPTLEN', 'SO_DEBUG', + 'SO_DEREGISTER_NAME', + 'SO_DETACH_FILTER', + 'SO_DISCDATA', + 'SO_DISCDATALEN', + 'SO_DISCOPT', + 'SO_DISCOPTLEN', 'SO_DOMAIN', - 'SO_ERROR', + 'SO_DONTLINGER', 'SO_DONTROUTE', + 'SO_ERROR', + 'SO_EXCLUSIVEADDRUSE', + 'SO_GETLOCALZONES', + 'SO_GETMYZONE', + 'SO_GETNETINFO', + 'SO_GETZONELIST', + 'SO_GROUP_ID', + 'SO_GROUP_PRIORITY', + 'SO_INCOMING_CPU', 'SO_KEEPALIVE', 'SO_LINGER', + 'SO_LOOKUP_MYZONE', + 'SO_LOOKUP_NAME', + 'SO_LOOKUP_NETDEF_ON_ADAPTER', + 'SO_LOOKUP_ZONES', + 'SO_LOOKUP_ZONES_ON_ADAPTER', 'SO_MARK', + 'SO_MAX_MSG_SIZE', + 'SO_MAXDG', + 'SO_MAXPATHDG', 'SO_OOBINLINE', + 'SO_OPENTYPE', + 'SO_PAP_GET_SERVER_STATUS', + 'SO_PAP_PRIME_READ', + 'SO_PAP_SET_SERVER_STATUS', 'SO_PASSCRED', + 'SO_PASSSEC', + 'SO_PAUSE_ACCEPT', + 'SO_PEEK_OFF', 'SO_PEERCRED', + 'SO_PORT_SCALABILITY', 'SO_PRIORITY', 'SO_PROTOCOL', + 'SO_PROTOCOL_INFO', + 'SO_PROTOCOL_INFOA', + 'SO_PROTOCOL_INFOW', + 'SO_RANDOMIZE_PORT', 'SO_RCVBUF', 'SO_RCVBUFFORCE', 'SO_RCVLOWAT', - 'SO_SNDLOWAT', 'SO_RCVTIMEO', - 'SO_SNDTIMEO', + 'SO_REGISTER_NAME', + 'SO_REMOVE_NAME', + 'SO_REUSE_MULTICASTPORT', + 'SO_REUSE_UNICASTPORT', 'SO_REUSEADDR', + 'SO_REUSEPORT', + 'SO_RXQ_OVFL', 'SO_SNDBUF', 'SO_SNDBUFFORCE', + 'SO_SNDLOWAT', + 'SO_SNDTIMEO', 'SO_TIMESTAMP', - 'SO_TYPE' + 'SO_TYPE', + 'SO_UPDATE_ACCEPT_CONTEXT', + 'SO_UPDATE_CONNECT_CONTEXT', + 'SO_USELOOPBACK', + 'TCP_BSDURGENT', + 'TCP_CONGESTION', + 'TCP_CORK', + 'TCP_DEFER_ACCEPT', + 'TCP_EXPEDITED_1122', + 'TCP_FASTOPEN', + 'TCP_INFO', + 'TCP_KEEPCNT', + 'TCP_KEEPIDLE', + 'TCP_KEEPINTVL', + 'TCP_LINGER2', + 'TCP_MAXRT', + 'TCP_MAXSEG', + 'TCP_NODELAY', + 'TCP_QUICKACK', + 'TCP_SYNCNT', + 'TCP_TIMESTAMPS', + 'TCP_USER_TIMEOUT', + 'TCP_WINDOW_CLAMP', ] PDF_DID = [ diff --git a/stix2validator/v21/musts.py b/stix2validator/v21/musts.py index 9c71fa9..776adc4 100644 --- a/stix2validator/v21/musts.py +++ b/stix2validator/v21/musts.py @@ -408,6 +408,9 @@ def patterns(instance, options): if instance['type'] != 'indicator' or 'pattern' not in instance: return + if instance['pattern_type'] != 'stix': + return + pattern = instance['pattern'] if not isinstance(pattern, string_types): return # This error already caught by schemas diff --git a/stix2validator/v21/shoulds.py b/stix2validator/v21/shoulds.py index 1b442ff..78f19ec 100644 --- a/stix2validator/v21/shoulds.py +++ b/stix2validator/v21/shoulds.py @@ -348,6 +348,11 @@ def vocab_region(instance): 'region') +def vocab_pattern_type(instance): + return check_vocab(instance, "INDICATOR_PATTERN", + 'indicator-pattern-types') + + def vocab_marking_definition(instance): """Ensure that the `definition_type` property of `marking-definition` objects is one of the values in the STIX 2.0 specification. @@ -948,7 +953,7 @@ def socket_options(instance): if opt not in enums.SOCKET_OPTIONS: yield JSONError("The 'options' property of object '%s' " "contains a key ('%s') that is not a valid" - " socket option (SO_*)." + " socket option (SO|ICMP|ICMP6|IP|IPV6|MCAST|TCP|IRLMP)_*." % (instance['id'], opt), instance['id'], 'socket-options') @@ -1278,6 +1283,7 @@ CHECKS = { vocab_indicator_types, vocab_industry_sector, vocab_malware_types, + vocab_pattern_type, vocab_report_types, vocab_threat_actor_types, vocab_threat_actor_role, @@ -1342,6 +1348,7 @@ CHECKS = { vocab_indicator_types, vocab_industry_sector, vocab_malware_types, + vocab_pattern_type, vocab_report_types, vocab_threat_actor_types, vocab_threat_actor_role, @@ -1376,6 +1383,7 @@ CHECKS = { vocab_indicator_types, vocab_industry_sector, vocab_malware_types, + vocab_pattern_type, vocab_report_types, vocab_threat_actor_types, vocab_threat_actor_role, @@ -1395,6 +1403,7 @@ CHECKS = { 'malware-capabilities': vocab_malware_capabilities, 'processor-architecture': vocab_processor_architecture, 'identity-class': vocab_identity_class, + 'indicator-pattern-types': vocab_pattern_type, 'indicator-types': vocab_indicator_types, 'industry-sector': vocab_industry_sector, 'malware-types': vocab_malware_types, @@ -1492,6 +1501,8 @@ def list_shoulds(options): validator_list.append(CHECKS['attack-resource-level']) if 'identity-class' not in options.disabled: validator_list.append(CHECKS['identity-class']) + if 'indicator-pattern-types' not in options.disabled: + validator_list.append(CHECKS['indicator-pattern-types']) if 'indicator-types' not in options.disabled: validator_list.append(CHECKS['indicator-types']) if 'industry-sector' not in options.disabled: diff --git a/tox.ini b/tox.ini index 2989c83..684f6b8 100644 --- a/tox.ini +++ b/tox.ini @@ -1,5 +1,5 @@ [tox] -envlist = py27,py34,py35,py36,py37,style,isort-check,packaging +envlist = py27,py34,py35,py36,py37,py38,style,isort-check,packaging [testenv] deps =
oasis-open/cti-stix-validator
be4ec65ad29997a7ac66b2ee0658f4c46a5229fa
diff --git a/stix2validator/test/v21/indicator_tests.py b/stix2validator/test/v21/indicator_tests.py index 778827c..158788e 100644 --- a/stix2validator/test/v21/indicator_tests.py +++ b/stix2validator/test/v21/indicator_tests.py @@ -240,3 +240,29 @@ class IndicatorTestCases(ValidatorTest): self.assertFalseWithOptions(indicator) self.check_ignore(indicator, 'indicator-properties') + + def test_indicator_different_pattern_type_does_not_get_validated(self): + pattern = ("alert tcp any any <> any 80 (msg:\"SHA256 Alert\";" + " protected_content:\"56D6F32151AD8474F40D7B939C2161EE2BBF10023F4AF1DBB3E13260EBDC6342\";" + " hash:sha256; offset:0; length:4;)") + indicator = copy.deepcopy(self.valid_indicator) + indicator["pattern"] = pattern + indicator["pattern_type"] = "snort" + indicator["pattern_version"] = "2.9.15" + + results = validate_parsed_json(indicator, self.options) + self.assertEqual(results.is_valid, True) + + def test_indicator_different_pattern_type_not_in_enum(self): + pattern = ("signature example-signature {" + "ip-proto == tcp" + "dst-port == 80" + "payload /^Some expression/" + "}") + indicator = copy.deepcopy(self.valid_indicator) + indicator["pattern"] = pattern + indicator["pattern_type"] = "zeek" + indicator["pattern_version"] = "3.0.1" + + self.assertFalseWithOptions(indicator) + self.check_ignore(indicator, 'indicator-pattern-types')
Fix Socket Options warning The following warning was seen in the elevator for a valid socket option: > The 'options' property of object 'network-traffic--eedcb05c-d030-5b59-9657-9fe758867611' contains a key ('IP_MULTICAST_LOOP') that is not a valid socket option (SO_*). The warning message doesn't accurately reflect what is being checked, and we leave out IP* and MCAST* options.
0.0
[ "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_indicator_different_pattern_type_does_not_get_validated", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_indicator_different_pattern_type_not_in_enum" ]
[ "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_additional_schemas", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_additional_schemas_custom_type", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_additional_schemas_custom_type_invalid_schema", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_custom_property_name_invalid_character", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_custom_property_name_long", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_custom_property_name_short", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_custom_property_name_strict", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_empty_list", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_indicator_missing_description", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_indicator_missing_name", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_indicator_missing_name_description", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_invalid_lang", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_invalid_pattern", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_modified_before_created", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_pattern_custom_invalid_format", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_pattern_custom_object_noprefix", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_pattern_custom_object_prefix_lax", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_pattern_custom_object_prefix_strict", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_pattern_custom_property_prefix_strict", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_pattern_list_object_property", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_pattern_with_escaped_slashes", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_reserved_object_type_infrastructure", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_reserved_property_action", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_validate_parsed_json_list_additional_invalid_schema", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_vocab_indicator_types", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_wellformed_indicator" ]
2019-12-13 14:52:08+00:00
4,312
oasis-open__cti-stix-validator-55
diff --git a/stix2validator/scripts/stix2_validator.py b/stix2validator/scripts/stix2_validator.py index 15bd7b0..8dda167 100644 --- a/stix2validator/scripts/stix2_validator.py +++ b/stix2validator/scripts/stix2_validator.py @@ -292,9 +292,6 @@ def main(): options = ValidationOptions(args) try: - # Set the output level (e.g., quiet vs. verbose) - output.set_level(options.verbose) - if not options.no_cache: init_requests_cache(options.refresh_cache) diff --git a/stix2validator/util.py b/stix2validator/util.py index 4da0be5..327931f 100644 --- a/stix2validator/util.py +++ b/stix2validator/util.py @@ -1,5 +1,7 @@ from collections import Iterable +from .output import error, set_level, set_silent + class ValidationOptions(object): """Collection of validation options which can be set via command line or @@ -72,6 +74,12 @@ class ValidationOptions(object): self.refresh_cache = refresh_cache self.clear_cache = clear_cache + # Set the output level (e.g., quiet vs. verbose) + if self.silent and self.verbose: + error('Error: Output can either be silent or verbose, but not both.') + set_level(self.verbose) + set_silent(self.silent) + # Convert string of comma-separated checks to a list, # and convert check code numbers to names if self.disabled:
oasis-open/cti-stix-validator
f3dcf83c352c99b5190e9697db7149ce3baf5961
diff --git a/stix2validator/test/bundle_tests.py b/stix2validator/test/bundle_tests.py index 8f417bd..52235ba 100644 --- a/stix2validator/test/bundle_tests.py +++ b/stix2validator/test/bundle_tests.py @@ -1,6 +1,8 @@ import copy import json +import pytest + from . import ValidatorTest VALID_BUNDLE = u""" @@ -51,3 +53,8 @@ class BundleTestCases(ValidatorTest): bundle['objects'][1]['modified'] = "2017-06-22T14:09:00.123Z" self.assertTrueWithOptions(bundle) + + def test_silent_and_verbose(self): + bundle = json.loads(VALID_BUNDLE) + with pytest.raises(SystemExit): + self.assertFalseWithOptions(bundle, silent=True, verbose=True)
handle options --verbose and --silent correctly Related to #50 The correct combination of these two should be as follows: |--verbose | --silent | desired behavior | | --- | --- | --- | |absent (default is False) | absent (default is False) | all messages except those printed by info | |absent (default is False) | present (True) | no messages printed | present (True) | absent (default is False) | all messages, including info are printed | present (True) | present (True) | error | Current behavior is: |--verbose | --silent | current behavior | | --- | --- | --- | |absent (default is False) | absent (default is False) | all messages except those printed by info | |absent (default is False) | present (ignored, so the default - False) | all messages except those printed by info | | present (True) | absent (default is False) | all messages, including info are printed | present (True) | present (ignored, so the default - False) | all messages, including info are printed |
0.0
[ "stix2validator/test/bundle_tests.py::BundleTestCases::test_silent_and_verbose" ]
[ "stix2validator/test/bundle_tests.py::BundleTestCases::test_bundle_created", "stix2validator/test/bundle_tests.py::BundleTestCases::test_bundle_object_categories", "stix2validator/test/bundle_tests.py::BundleTestCases::test_bundle_version" ]
2018-06-08 12:26:02+00:00
4,313
oasis-open__cti-stix-validator-89
diff --git a/stix2validator/errors.py b/stix2validator/errors.py index c3e70b7..a0f3f42 100644 --- a/stix2validator/errors.py +++ b/stix2validator/errors.py @@ -222,9 +222,9 @@ def pretty_error(error, verbose=False): "not an allowed value", msg) elif ('target_ref' in error.schema_path or 'source_ref' in error.schema_path): - msg = "Relationships cannot link bundles, marking definitions"\ - ", sightings, or other relationships. This field must "\ - "contain the id of an SDO." + msg = "Relationships cannot link bundles, marking definitions"\ + ", sightings, or other relationships. This field must "\ + "contain the id of an SDO." elif 'sighting_of_ref' in error.schema_path: msg = "'sighting_of_ref' must refer to a STIX Domain Object or "\ "Custom Object" diff --git a/stix2validator/util.py b/stix2validator/util.py index df790d9..725a3d5 100644 --- a/stix2validator/util.py +++ b/stix2validator/util.py @@ -324,7 +324,7 @@ class ValidationOptions(object): contained within the same bundle """ - def __init__(self, cmd_args=None, version=DEFAULT_VER, verbose=False, silent=False, + def __init__(self, cmd_args=None, version=None, verbose=False, silent=False, files=None, recursive=False, schema_dir=None, disabled="", enabled="", strict=False, strict_types=False, strict_properties=False, no_cache=False, @@ -348,7 +348,10 @@ class ValidationOptions(object): self.enforce_refs = cmd_args.enforce_refs else: # input options - self.version = version + if version is not None: + self.version = version + else: + self.version = None self.files = files self.recursive = recursive self.schema_dir = schema_dir @@ -391,6 +394,25 @@ class ValidationOptions(object): for x in self.enabled] +def set_check_codes(options): + if options.version == '2.0': + options.check_codes = CHECK_CODES20 + else: + options.check_codes = CHECK_CODES21 + + if options.disabled: + if isinstance(options.disabled, str): + options.disabled = options.disabled.split(',') + options.disabled = [options.check_codes[x] if x in options.check_codes else x + for x in options.disabled] + if options.enabled: + if isinstance(options.enabled, str): + options.enabled = options.enabled.split(',') + options.enabled = [options.check_codes[x] if x in options.check_codes else x + for x in options.enabled] + return options + + def has_cyber_observable_data(instance): """Return True only if the given instance is an observed-data object containing STIX Cyber Observable objects. @@ -402,6 +424,31 @@ def has_cyber_observable_data(instance): return False +def check_spec(instance, options): + """ Checks to see if there are differences in command-line option + provided spec_version and the spec_version found with bundles + and/or objects. + """ + warnings = [] + if options.version: + try: + if instance['type'] == 'bundle' and 'spec_version' in instance: + if instance['spec_version'] != options.version: + warnings.append(instance['id'] + ": spec_version mismatch with command-" + "line option. Defaulting to spec_version " + options.version) + if instance['type'] == 'bundle' and 'objects' in instance: + for obj in instance['objects']: + if 'spec_version' in obj: + if obj['spec_version'] != options.version: + warnings.append(obj['id'] + ": spec_version mismatch with command-" + "line option. Defaulting to spec_version " + + options.version) + except Exception: + pass + + return warnings + + def cyber_observable_check(original_function): """Decorator for functions that require cyber observable data. """ diff --git a/stix2validator/v21/musts.py b/stix2validator/v21/musts.py index 41dd81a..007e69b 100644 --- a/stix2validator/v21/musts.py +++ b/stix2validator/v21/musts.py @@ -350,8 +350,8 @@ def language(instance): """Ensure the 'lang' property of SDOs is a valid RFC 5646 language code. """ if ('lang' in instance and instance['lang'] not in enums.LANG_CODES): - yield JSONError("'%s' is not a valid RFC 5646 language code." - % instance['lang'], instance['id']) + yield JSONError("'%s' is not a valid RFC 5646 language code." + % instance['lang'], instance['id']) @cyber_observable_check diff --git a/stix2validator/validator.py b/stix2validator/validator.py index e13fae2..4259724 100644 --- a/stix2validator/validator.py +++ b/stix2validator/validator.py @@ -15,8 +15,8 @@ from six import iteritems, string_types, text_type from . import output from .errors import (NoJSONFileFoundError, SchemaError, SchemaInvalidError, ValidationError, pretty_error) -from .util import (DEFAULT_VER, ValidationOptions, clear_requests_cache, - init_requests_cache) +from .util import (DEFAULT_VER, ValidationOptions, check_spec, + clear_requests_cache, init_requests_cache, set_check_codes) from .v20 import musts as musts20 from .v20 import shoulds as shoulds20 from .v21 import musts as musts21 @@ -645,6 +645,13 @@ def _schema_validate(sdo, options): else: error_prefix = '' + if options.version is None and 'spec_version' in sdo: + options.version = sdo['spec_version'] + if options.version is None: + options.version = "2.1" + + options = set_check_codes(options) + # Get validator for built-in schema base_sdo_errors = _get_error_generator(sdo['type'], sdo, version=options.version) if base_sdo_errors: @@ -718,6 +725,8 @@ def validate_instance(instance, options=None): # Schema validation if instance['type'] == 'bundle' and 'objects' in instance: + if options.version is None and 'spec_version' in instance: + options.version = instance['spec_version'] # Validate each object in a bundle separately for sdo in instance['objects']: if 'type' not in sdo: @@ -726,6 +735,8 @@ def validate_instance(instance, options=None): else: error_gens += _schema_validate(instance, options) + spec_warnings = check_spec(instance, options) + # Custom validation must_checks = _get_musts(options) should_checks = _get_shoulds(options) @@ -741,6 +752,7 @@ def validate_instance(instance, options=None): else: chained_errors = errors warnings = [pretty_error(x, options.verbose) for x in warnings] + warnings.extend(spec_warnings) except schema_exceptions.RefResolutionError: raise SchemaInvalidError('Invalid JSON schema: a JSON reference ' 'failed to resolve') @@ -756,11 +768,11 @@ def validate_instance(instance, options=None): for error in gen: msg = prefix + pretty_error(error, options.verbose) error_list.append(SchemaError(msg)) - + if options.strict: + error_list.extend(spec_warnings) if error_list: valid = False else: valid = True - return ObjectValidationResults(is_valid=valid, object_id=instance.get('id', ''), errors=error_list, warnings=warnings)
oasis-open/cti-stix-validator
a607014e3fa500a7678f8b61b278456ca581f9d0
diff --git a/stix2validator/test/v21/indicator_tests.py b/stix2validator/test/v21/indicator_tests.py index a4d3950..549506f 100644 --- a/stix2validator/test/v21/indicator_tests.py +++ b/stix2validator/test/v21/indicator_tests.py @@ -213,8 +213,7 @@ class IndicatorTestCases(ValidatorTest): indicator = copy.deepcopy(self.valid_indicator) indicator['name'] = 'Foobar' objects = [indicator, ADDTNL_INVALID_SCHEMA] - - options = ValidationOptions(schema_dir=self.custom_schemas) + options = ValidationOptions(schema_dir=self.custom_schemas, version="2.1") results = validate_parsed_json(objects, options) assert results[0].is_valid assert not results[1].is_valid diff --git a/stix2validator/test/v21/spec_version_tests.py b/stix2validator/test/v21/spec_version_tests.py new file mode 100644 index 0000000..bfba3d5 --- /dev/null +++ b/stix2validator/test/v21/spec_version_tests.py @@ -0,0 +1,165 @@ +import copy +import json + +from . import ValidatorTest +from ... import ValidationOptions, validate_parsed_json + +VALID_BUNDLE = u""" +{ + "type": "bundle", + "id": "bundle--44af6c39-c09b-49c5-9de2-394224b04982", + "objects": [ + { + "type": "identity", + "id": "identity--8ae20dde-83d4-4218-88fd-41ef0dabf9d1", + "created": "2016-08-22T14:09:00.123Z", + "modified": "2016-08-22T14:09:00.123Z", + "name": "mitre.org", + "identity_class": "organization" + } + ] +} +""" + +VERSION_NUMBERS = ["2.0", "2.1"] + + +class SpecVersionTestCases(ValidatorTest): + valid_data = json.loads(VALID_BUNDLE) + internal_options = ValidationOptions() + + def test_empty(self): + observed_data = copy.deepcopy(self.valid_data) + results = validate_parsed_json(observed_data, self.internal_options) + self.assertFalse(results.is_valid) + + def test_cmd(self): + for version in VERSION_NUMBERS: + observed_data = copy.deepcopy(self.valid_data) + self.internal_options.version = version + results = validate_parsed_json( + observed_data, + self.internal_options) + if version == "2.0": + self.assertTrue(results.is_valid) + elif version == "2.1": + self.assertFalse(results.is_valid) + + def test_bundle(self): + for version in VERSION_NUMBERS: + observed_data = copy.deepcopy(self.valid_data) + observed_data['spec_version'] = version + results = validate_parsed_json(observed_data) + if version == "2.0": + self.assertTrue(results.is_valid) + elif version == "2.1": + self.assertFalse(results.is_valid) + self.assertTrue(len(results.errors) == 1) + self.assertTrue(len(results.warnings) == 1) + + def test_object(self): + observed_data = copy.deepcopy(self.valid_data) + for version in VERSION_NUMBERS: + observed_data['objects'][0]['spec_version'] = version + results = validate_parsed_json(observed_data) + self.assertTrue(results.is_valid) + + def test_bundle_and_object(self): + observed_data = copy.deepcopy(self.valid_data) + for bundle_version in VERSION_NUMBERS: + for object_version in VERSION_NUMBERS: + observed_data['spec_version'] = bundle_version + observed_data['objects'][0]['spec_version'] = object_version + results = validate_parsed_json(observed_data) + self.assertTrue(results.is_valid) + + def test_cmd_and_bundle(self): + observed_data = copy.deepcopy(self.valid_data) + for bundle_version in VERSION_NUMBERS: + for cmd_version in VERSION_NUMBERS: + observed_data['spec_version'] = bundle_version + self.internal_options.version = cmd_version + results = validate_parsed_json( + observed_data, + self.internal_options) + + if cmd_version == "2.0" and bundle_version == "2.0": + self.assertTrue(results.is_valid) + + elif cmd_version == "2.0" and bundle_version == "2.1": + self.assertTrue(results.is_valid) + + elif cmd_version == "2.1" and bundle_version == "2.0": + self.assertFalse(results.is_valid) + self.assertTrue(len(results.errors) == 1) + self.assertTrue(len(results.warnings) == 2) + + elif cmd_version == "2.1" and bundle_version == "2.1": + self.assertFalse(results.is_valid) + self.assertTrue(len(results.warnings) == 1) + self.assertTrue(len(results.errors) == 1) + + def test_cmd_and_obj(self): + observed_data = copy.deepcopy(self.valid_data) + for cmd_version in VERSION_NUMBERS: + for obj_version in VERSION_NUMBERS: + observed_data['objects'][0]['spec_version'] = obj_version + self.internal_options.version = cmd_version + results = validate_parsed_json( + observed_data, + self.internal_options) + if cmd_version == "2.0" and obj_version == "2.0": + self.assertTrue(results.is_valid) + self.assertTrue(len(results.warnings) == 1) + + elif cmd_version == "2.0" and obj_version == "2.1": + self.assertTrue(results.is_valid) + self.assertTrue(len(results.warnings) == 2) + + elif cmd_version == "2.1" and obj_version == "2.0": + self.assertTrue(len(results.warnings) == 1) + self.assertTrue(results.is_valid) + + elif cmd_version == "2.1" and obj_version == "2.1": + self.assertTrue(results.is_valid) + self.assertTrue(len(results.warnings) == 0) + + def test_all(self): + observed_data = copy.deepcopy(self.valid_data) + for cmd_version in VERSION_NUMBERS: + for bundle_version in VERSION_NUMBERS: + for obj_version in VERSION_NUMBERS: + observed_data['spec_version'] = bundle_version + observed_data['objects'][-1]['spec_version'] = obj_version + self.internal_options.version = cmd_version + results = validate_parsed_json( + observed_data, + self.internal_options) + + if cmd_version == "2.0" and bundle_version == "2.0" and obj_version == "2.0": + self.assertTrue(results.is_valid) + self.assertTrue(len(results.warnings) == 1) + + if cmd_version == "2.1" and bundle_version == "2.0" and obj_version == "2.0": + self.assertTrue(results.is_valid) + self.assertTrue(len(results.warnings) == 3) + + if cmd_version == "2.0" and bundle_version == "2.1" and obj_version == "2.0": + self.assertTrue(results.is_valid) + self.assertTrue(len(results.warnings) == 2) + + if cmd_version == "2.0" and bundle_version == "2.0" and obj_version == "2.1": + self.assertTrue(results.is_valid) + self.assertTrue(len(results.warnings) == 2) + + if cmd_version == "2.1" and bundle_version == "2.1" and obj_version == "2.0": + self.assertTrue(results.is_valid) + self.assertTrue(len(results.warnings) == 2) + + if cmd_version == "2.0" and bundle_version == "2.1" and obj_version == "2.1": + self.assertTrue(results.is_valid) + self.assertTrue(len(results.warnings) == 3) + + if cmd_version == "2.1" and bundle_version == "2.1" and obj_version == "2.1": + self.assertTrue(results.is_valid) + self.assertTrue(len(results.warnings) == 1)
when spec_version is 2.0 on bundle, do not warn On a stix bundle that has a spec_version of 2.0, the latest version of the validator returns a warning: [!] Warning: bundle--59afb48d-0f9c-434d-be6a-69515424b0c3: {101} Custom property 'spec_version' should have a type that starts with 'x_' followed by a source unique identifier (like a domain name with dots replaced by hyphen), a hyphen and then the name. It should NOT return a warning, as that is properly formatted STIX 2.0. This was found when checking against https://github.com/pan-unit42/playbook_viewer/blob/master/playbook_json/darkhydrus.json
0.0
[ "stix2validator/test/v21/spec_version_tests.py::SpecVersionTestCases::test_all", "stix2validator/test/v21/spec_version_tests.py::SpecVersionTestCases::test_cmd_and_obj" ]
[ "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_additional_schemas", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_additional_schemas_custom_type", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_additional_schemas_custom_type_invalid_schema", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_custom_property_name_invalid_character", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_custom_property_name_long", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_custom_property_name_short", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_custom_property_name_strict", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_empty_list", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_invalid_lang", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_invalid_pattern", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_modified_before_created", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_pattern_custom_invalid_format", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_pattern_custom_object_noprefix", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_pattern_custom_object_prefix_lax", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_pattern_custom_object_prefix_strict", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_pattern_custom_property_prefix_strict", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_pattern_list_object_property", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_pattern_with_escaped_slashes", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_validate_parsed_json_list_additional_invalid_schema", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_vocab_indicator_types", "stix2validator/test/v21/indicator_tests.py::IndicatorTestCases::test_wellformed_indicator", "stix2validator/test/v21/spec_version_tests.py::SpecVersionTestCases::test_bundle_and_object", "stix2validator/test/v21/spec_version_tests.py::SpecVersionTestCases::test_object" ]
2019-04-12 16:41:57+00:00
4,314
oasis-open__cti-taxii-client-11
diff --git a/taxii2client/__init__.py b/taxii2client/__init__.py index bee06a1..0efc770 100644 --- a/taxii2client/__init__.py +++ b/taxii2client/__init__.py @@ -478,7 +478,7 @@ class _HTTPConnection(object): resp.raise_for_status() content_type = resp.headers['Content-Type'] - if content_type != accept: + if not content_type.startswith(accept): msg = "Unexpected Response Content-Type: {}" raise TAXIIServiceException(msg.format(content_type))
oasis-open/cti-taxii-client
405bbbaa58d86371adc401ee4fe8830f429fb6b2
diff --git a/taxii2client/test/test_client.py b/taxii2client/test/test_client.py index 597ebb3..3a02747 100644 --- a/taxii2client/test/test_client.py +++ b/taxii2client/test/test_client.py @@ -3,7 +3,7 @@ import responses from taxii2client import ( MEDIA_TYPE_STIX_V20, MEDIA_TYPE_TAXII_V20, AccessError, ApiRoot, - Collection, Server + Collection, Server, TAXIIServiceException ) TAXII_SERVER = 'example.com' @@ -394,3 +394,23 @@ def test_get_status(api_root): assert len(status.failures) == 1 assert status.pending_count == 2 assert len(status.pendings) == 2 + + [email protected] +def test_content_type_valid(collection): + responses.add(responses.GET, GET_OBJECT_URL, GET_OBJECT_RESPONSE, + status=200, content_type="%s; charset=utf-8" % MEDIA_TYPE_STIX_V20) + + response = collection.get_object('indicator--252c7c11-daf2-42bd-843b-be65edca9f61') + indicator = response['objects'][0] + assert indicator['id'] == 'indicator--252c7c11-daf2-42bd-843b-be65edca9f61' + + [email protected] +def test_content_type_invalid(collection): + responses.add(responses.GET, GET_OBJECT_URL, GET_OBJECT_RESPONSE, + status=200, content_type="taxii") + + with pytest.raises(TAXIIServiceException) as excinfo: + collection.get_object('indicator--252c7c11-daf2-42bd-843b-be65edca9f61') + assert "Unexpected Response Content-Type" in str(excinfo.value)
Accept more flexible content type strings When checking the content type of packets the client receives, it checks if it is an exact match (https://github.com/oasis-open/cti-taxii-client/blob/master/taxii2client/__init__.py#L481). This fails if for example "; charset=utf-8" is appended to the content type.
0.0
[ "taxii2client/test/test_client.py::test_content_type_valid" ]
[ "taxii2client/test/test_client.py::test_server_discovery", "taxii2client/test/test_client.py::test_minimal_discovery_response", "taxii2client/test/test_client.py::test_discovery_with_no_default", "taxii2client/test/test_client.py::test_api_root", "taxii2client/test/test_client.py::test_api_root_collections", "taxii2client/test/test_client.py::test_collection", "taxii2client/test/test_client.py::test_collection_unexpected_kwarg", "taxii2client/test/test_client.py::test_get_collection_objects", "taxii2client/test/test_client.py::test_get_object", "taxii2client/test/test_client.py::test_cannot_write_to_readonly_collection", "taxii2client/test/test_client.py::test_add_object_to_collection", "taxii2client/test/test_client.py::test_cannot_read_from_writeonly_collection", "taxii2client/test/test_client.py::test_get_manifest", "taxii2client/test/test_client.py::test_get_status", "taxii2client/test/test_client.py::test_content_type_invalid" ]
2017-10-04 14:31:24+00:00
4,315
oasis-open__cti-taxii-client-31
diff --git a/.gitignore b/.gitignore index 1f8d3e2..f21feea 100644 --- a/.gitignore +++ b/.gitignore @@ -46,6 +46,7 @@ nosetests.xml coverage.xml *,cover .hypothesis/ +.pytest_cache/ # Translations *.mo diff --git a/taxii2client/__init__.py b/taxii2client/__init__.py index 85a7b7f..358892f 100644 --- a/taxii2client/__init__.py +++ b/taxii2client/__init__.py @@ -198,8 +198,8 @@ class Status(_TAXIIEndpoint): __bool__ = __nonzero__ - def refresh(self): - response = self._conn.get(self.url, accept=MEDIA_TYPE_TAXII_V20) + def refresh(self, accept=MEDIA_TYPE_TAXII_V20): + response = self._conn.get(self.url, accept=accept) self._populate_fields(**response) def wait_until_final(self, poll_interval=1, timeout=60): @@ -386,30 +386,31 @@ class Collection(_TAXIIEndpoint): msg = "Collection '{}' does not allow writing." raise AccessError(msg.format(self.url)) - def refresh(self): - response = self._conn.get(self.url, accept=MEDIA_TYPE_TAXII_V20) + def refresh(self, accept=MEDIA_TYPE_TAXII_V20): + response = self._conn.get(self.url, accept=accept) self._populate_fields(**response) self._loaded = True - def get_objects(self, **filter_kwargs): + def get_objects(self, accept=MEDIA_TYPE_STIX_V20, **filter_kwargs): """Implement the ``Get Objects`` endpoint (section 5.3)""" self._verify_can_read() query_params = _filter_kwargs_to_query_params(filter_kwargs) - return self._conn.get(self.objects_url, accept=MEDIA_TYPE_STIX_V20, + return self._conn.get(self.objects_url, accept=accept, params=query_params) - def get_object(self, obj_id, version=None): + def get_object(self, obj_id, version=None, accept=MEDIA_TYPE_STIX_V20): """Implement the ``Get an Object`` endpoint (section 5.5)""" self._verify_can_read() url = self.objects_url + str(obj_id) + "/" query_params = None if version: query_params = _filter_kwargs_to_query_params({"version": version}) - return self._conn.get(url, accept=MEDIA_TYPE_STIX_V20, + return self._conn.get(url, accept=accept, params=query_params) def add_objects(self, bundle, wait_for_completion=True, poll_interval=1, - timeout=60): + timeout=60, accept=MEDIA_TYPE_TAXII_V20, + content_type=MEDIA_TYPE_STIX_V20): """Implement the ``Add Objects`` endpoint (section 5.4) Add objects to the collection. This may be performed either @@ -427,10 +428,13 @@ class Collection(_TAXIIEndpoint): parsed into native Python) wait_for_completion (bool): Whether to wait for the add operation to complete before returning - poll_interval: If waiting for completion, how often to poll + poll_interval (int): If waiting for completion, how often to poll the status service (seconds) - timeout: If waiting for completion, how long to poll until giving - up (seconds). Use <= 0 to wait forever + timeout (int): If waiting for completion, how long to poll until + giving up (seconds). Use <= 0 to wait forever + accept (str): media type to include in the ``Accept:`` header. + content_type (str): media type to include in the ``Content-Type:`` + header. Returns: If ``wait_for_completion`` is False, a Status object corresponding @@ -446,8 +450,8 @@ class Collection(_TAXIIEndpoint): self._verify_can_write() headers = { - "Accept": MEDIA_TYPE_TAXII_V20, - "Content-Type": MEDIA_TYPE_STIX_V20, + "Accept": accept, + "Content-Type": content_type, } if isinstance(bundle, dict): @@ -473,12 +477,12 @@ class Collection(_TAXIIEndpoint): return status - def get_manifest(self, **filter_kwargs): + def get_manifest(self, accept=MEDIA_TYPE_TAXII_V20, **filter_kwargs): """Implement the ``Get Object Manifests`` endpoint (section 5.6).""" self._verify_can_read() query_params = _filter_kwargs_to_query_params(filter_kwargs) return self._conn.get(self.url + "manifest/", - accept=MEDIA_TYPE_TAXII_V20, + accept=accept, params=query_params) @@ -545,17 +549,17 @@ class ApiRoot(_TAXIIEndpoint): if not self._loaded_information: self.refresh_information() - def refresh(self): + def refresh(self, accept=MEDIA_TYPE_TAXII_V20): """Update the API Root's information and list of Collections""" - self.refresh_information() - self.refresh_collections() + self.refresh_information(accept) + self.refresh_collections(accept) - def refresh_information(self): + def refresh_information(self, accept=MEDIA_TYPE_TAXII_V20): """Update the properties of this API Root. This invokes the ``Get API Root Information`` endpoint. """ - response = self._conn.get(self.url, accept=MEDIA_TYPE_TAXII_V20) + response = self._conn.get(self.url, accept=accept) self._title = response["title"] self._description = response["description"] @@ -564,13 +568,13 @@ class ApiRoot(_TAXIIEndpoint): self._loaded_information = True - def refresh_collections(self): + def refresh_collections(self, accept=MEDIA_TYPE_TAXII_V20): """Update the list of Collections contained by this API Root. This invokes the ``Get Collections`` endpoint. """ url = self.url + "collections/" - response = self._conn.get(url, accept=MEDIA_TYPE_TAXII_V20) + response = self._conn.get(url, accept=accept) self._collections = [] for item in response["collections"]: @@ -580,9 +584,9 @@ class ApiRoot(_TAXIIEndpoint): self._loaded_collections = True - def get_status(self, status_id): + def get_status(self, status_id, accept=MEDIA_TYPE_TAXII_V20): status_url = self.url + "status/" + status_id + "/" - info = self._conn.get(status_url, accept=MEDIA_TYPE_TAXII_V20) + info = self._conn.get(status_url, accept=accept) return Status(status_url, conn=self._conn, **info) @@ -700,6 +704,23 @@ class _HTTPConnection(object): if user and password: self.session.auth = requests.auth.HTTPBasicAuth(user, password) + def valid_content_type(self, content_type, accept): + """Check that the server is returning a valid Content-Type + + Args: + content_type (str): ``Content-Type:`` header value + accept (str): media type to include in the ``Accept:`` header. + + """ + accept_tokens = accept.replace(' ', '').split(';') + content_type_tokens = content_type.replace(' ', '').split(';') + + return ( + all(elem in content_type_tokens for elem in accept_tokens) and + (content_type_tokens[0] == 'application/vnd.oasis.taxii+json' or + content_type_tokens[0] == 'application/vnd.oasis.stix+json') + ) + def get(self, url, accept, params=None): """Perform an HTTP GET, using the saved requests.Session and auth info. @@ -720,9 +741,10 @@ class _HTTPConnection(object): resp.raise_for_status() content_type = resp.headers["Content-Type"] - if not content_type.startswith(accept): - msg = "Unexpected Response Content-Type: {}" - raise TAXIIServiceException(msg.format(content_type)) + + if not self.valid_content_type(content_type=content_type, accept=accept): + msg = "Unexpected Response. Got Content-Type: '{}' for Accept: '{}'" + raise TAXIIServiceException(msg.format(content_type, accept)) return resp.json()
oasis-open/cti-taxii-client
0201af14e578714a297aff795413babc425a2219
diff --git a/taxii2client/test/test_client.py b/taxii2client/test/test_client.py index de2e303..165e2bc 100644 --- a/taxii2client/test/test_client.py +++ b/taxii2client/test/test_client.py @@ -490,7 +490,8 @@ def test_content_type_invalid(collection): with pytest.raises(TAXIIServiceException) as excinfo: collection.get_object("indicator--252c7c11-daf2-42bd-843b-be65edca9f61") - assert "Unexpected Response Content-Type" in str(excinfo.value) + assert ("Unexpected Response. Got Content-Type: 'taxii' for " + "Accept: 'application/vnd.oasis.stix+json; version=2.0'") in str(excinfo.value) def test_url_filter_type(): @@ -563,3 +564,30 @@ def test_taxii_endpoint_raises_exception(): _TAXIIEndpoint("https://example.com/api1/collections/", conn, "other", "test") assert "A connection and user/password may not both be provided." in str(excinfo.value) + + [email protected] +def test_valid_content_type_for_connection(): + """The server responded with charset=utf-8, but the media types are correct + and first.""" + responses.add(responses.GET, COLLECTION_URL, COLLECTIONS_RESPONSE, + status=200, + content_type=MEDIA_TYPE_TAXII_V20 + "; charset=utf-8") + + conn = _HTTPConnection(user="foo", password="bar", verify=False) + conn.get("https://example.com/api1/collections/91a7b528-80eb-42ed-a74d-c6fbd5a26116/", MEDIA_TYPE_TAXII_V20, None) + + [email protected] +def test_invalid_content_type_for_connection(): + responses.add(responses.GET, COLLECTION_URL, COLLECTIONS_RESPONSE, + status=200, + content_type=MEDIA_TYPE_TAXII_V20) + + with pytest.raises(TAXIIServiceException) as excinfo: + conn = _HTTPConnection(user="foo", password="bar", verify=False) + conn.get("https://example.com/api1/collections/91a7b528-80eb-42ed-a74d-c6fbd5a26116/", MEDIA_TYPE_TAXII_V20 + "; charset=utf-8", None) + + assert ("Unexpected Response. Got Content-Type: 'application/vnd.oasis.taxii+json; " + "version=2.0' for Accept: 'application/vnd.oasis.taxii+json; version=2.0; " + "charset=utf-8'") == str(excinfo.value)
More flexible content-type matching Building on #10, we should make the content-type matching more robust than just a string's `.startwith()`.
0.0
[ "taxii2client/test/test_client.py::test_content_type_invalid", "taxii2client/test/test_client.py::test_invalid_content_type_for_connection" ]
[ "taxii2client/test/test_client.py::test_server_discovery", "taxii2client/test/test_client.py::test_minimal_discovery_response", "taxii2client/test/test_client.py::test_discovery_with_no_default", "taxii2client/test/test_client.py::test_api_root", "taxii2client/test/test_client.py::test_api_root_collections", "taxii2client/test/test_client.py::test_get_collection_by_id_exists", "taxii2client/test/test_client.py::test_get_collection_by_id_not_present", "taxii2client/test/test_client.py::test_collection", "taxii2client/test/test_client.py::test_collection_unexpected_kwarg", "taxii2client/test/test_client.py::test_get_collection_objects", "taxii2client/test/test_client.py::test_get_object", "taxii2client/test/test_client.py::test_cannot_write_to_readonly_collection", "taxii2client/test/test_client.py::test_add_object_to_collection", "taxii2client/test/test_client.py::test_add_object_to_collection_dict", "taxii2client/test/test_client.py::test_add_object_rases_error_when_collection_id_does_not_match_url", "taxii2client/test/test_client.py::test_cannot_read_from_writeonly_collection", "taxii2client/test/test_client.py::test_get_manifest", "taxii2client/test/test_client.py::test_get_status", "taxii2client/test/test_client.py::test_content_type_valid", "taxii2client/test/test_client.py::test_url_filter_type", "taxii2client/test/test_client.py::test_filter_id", "taxii2client/test/test_client.py::test_filter_version", "taxii2client/test/test_client.py::test_filter_added_after", "taxii2client/test/test_client.py::test_filter_combo", "taxii2client/test/test_client.py::test_params_filter_unknown", "taxii2client/test/test_client.py::test_taxii_endpoint_raises_exception", "taxii2client/test/test_client.py::test_valid_content_type_for_connection" ]
2018-04-09 18:02:08+00:00
4,316
oasis-open__cti-taxii-client-32
diff --git a/taxii2client/__init__.py b/taxii2client/__init__.py index 85a7b7f..1fddedb 100644 --- a/taxii2client/__init__.py +++ b/taxii2client/__init__.py @@ -220,23 +220,50 @@ class Status(_TAXIIEndpoint): self.refresh() elapsed = time.time() - start_time - def _populate_fields(self, id, status, total_count, success_count, - failure_count, pending_count, request_timestamp=None, + def _populate_fields(self, id=None, status=None, total_count=None, + success_count=None, failure_count=None, + pending_count=None, request_timestamp=None, successes=None, failures=None, pendings=None): - self.id = id - self.status = status - self.request_timestamp = request_timestamp - self.total_count = total_count - self.success_count = success_count - self.failure_count = failure_count - self.pending_count = pending_count - self.successes = successes or [] - self.failures = failures or [] - self.pendings = pendings or [] + self.id = id # required + self.status = status # required + self.request_timestamp = request_timestamp # optional + self.total_count = total_count # required + self.success_count = success_count # required + self.failure_count = failure_count # required + self.pending_count = pending_count # required + self.successes = successes or [] # optional + self.failures = failures or [] # optional + self.pendings = pendings or [] # optional self._validate_status() def _validate_status(self): + """Validates Status information. Raises errors for required + properties.""" + if not self.id: + msg = "No 'id' in Status for request '{}'" + raise ValidationError(msg.format(self.url)) + + if not self.status: + msg = "No 'status' in Status for request '{}'" + raise ValidationError(msg.format(self.url)) + + if self.total_count is None: + msg = "No 'total_count' in Status for request '{}'" + raise ValidationError(msg.format(self.url)) + + if self.success_count is None: + msg = "No 'success_count' in Status for request '{}'" + raise ValidationError(msg.format(self.url)) + + if self.failure_count is None: + msg = "No 'failure_count' in Status for request '{}'" + raise ValidationError(msg.format(self.url)) + + if self.pending_count is None: + msg = "No 'pending_count' in Status for request '{}'" + raise ValidationError(msg.format(self.url)) + if len(self.successes) != self.success_count: msg = "Found successes={}, but success_count={} in status '{}'" raise ValidationError(msg.format(self.successes, @@ -356,18 +383,34 @@ class Collection(_TAXIIEndpoint): def _populate_fields(self, id=None, title=None, description=None, can_read=None, can_write=None, media_types=None): - if media_types is None: - media_types = [] - self._id = id - self._title = title - self._description = description - self._can_read = can_read - self._can_write = can_write - self._media_types = media_types + self._id = id # required + self._title = title # required + self._description = description # optional + self._can_read = can_read # required + self._can_write = can_write # required + self._media_types = media_types or [] # optional self._validate_collection() def _validate_collection(self): + """Validates Collection information. Raises errors for required + properties.""" + if not self._id: + msg = "No 'id' in Collection for request '{}'" + raise ValidationError(msg.format(self.url)) + + if not self._title: + msg = "No 'title' in Collection for request '{}'" + raise ValidationError(msg.format(self.url)) + + if self._can_read is None: + msg = "No 'can_read' in Collection for request '{}'" + raise ValidationError(msg.format(self.url)) + + if self._can_write is None: + msg = "No 'can_write' in Collection for request '{}'" + raise ValidationError(msg.format(self.url)) + if self._id not in self.url: msg = "The collection '{}' does not match the url for queries '{}'" raise ValidationError(msg.format(self._id, self.url)) @@ -545,6 +588,21 @@ class ApiRoot(_TAXIIEndpoint): if not self._loaded_information: self.refresh_information() + def _validate_api_root(self): + """Validates API Root information. Raises errors for required + properties.""" + if not self._title: + msg = "No 'title' in API Root for request '{}'" + raise ValidationError(msg.format(self.url)) + + if not self._versions: + msg = "No 'versions' in API Root for request '{}'" + raise ValidationError(msg.format(self.url)) + + if self._max_content_length is None: + msg = "No 'max_content_length' in API Root for request '{}'" + raise ValidationError(msg.format(self.url)) + def refresh(self): """Update the API Root's information and list of Collections""" self.refresh_information() @@ -557,11 +615,12 @@ class ApiRoot(_TAXIIEndpoint): """ response = self._conn.get(self.url, accept=MEDIA_TYPE_TAXII_V20) - self._title = response["title"] - self._description = response["description"] - self._versions = response["versions"] - self._max_content_length = response["max_content_length"] + self._title = response.get("title") # required + self._description = response.get("description") # optional + self._versions = response.get("versions", []) # required + self._max_content_length = response.get("max_content_length") # required + self._validate_api_root() self._loaded_information = True def refresh_collections(self): @@ -573,7 +632,7 @@ class ApiRoot(_TAXIIEndpoint): response = self._conn.get(url, accept=MEDIA_TYPE_TAXII_V20) self._collections = [] - for item in response["collections"]: + for item in response.get("collections", []): # optional collection_url = url + item["id"] + "/" collection = Collection(collection_url, conn=self._conn, **item) self._collections.append(collection) @@ -582,8 +641,8 @@ class ApiRoot(_TAXIIEndpoint): def get_status(self, status_id): status_url = self.url + "status/" + status_id + "/" - info = self._conn.get(status_url, accept=MEDIA_TYPE_TAXII_V20) - return Status(status_url, conn=self._conn, **info) + response = self._conn.get(status_url, accept=MEDIA_TYPE_TAXII_V20) + return Status(status_url, conn=self._conn, **response) class Server(_TAXIIEndpoint): @@ -649,13 +708,20 @@ class Server(_TAXIIEndpoint): if not self._loaded: self.refresh() + def _validate_server(self): + """Validates server information. Raises errors for required properties. + """ + if not self._title: + msg = "No 'title' in Server Discovery for request '{}'" + raise ValidationError(msg.format(self.url)) + def refresh(self): response = self._conn.get(self.url, accept=MEDIA_TYPE_TAXII_V20) - self._title = response.get("title") - self._description = response.get("description") - self._contact = response.get("contact") - roots = response.get("api_roots", []) + self._title = response.get("title") # required + self._description = response.get("description") # optional + self._contact = response.get("contact") # optional + roots = response.get("api_roots", []) # optional self._api_roots = [ApiRoot(url, user=self._user, password=self._password, @@ -665,7 +731,8 @@ class Server(_TAXIIEndpoint): # rather than creating a duplicate. The TAXII 2.0 spec says that the # `default` API Root MUST be an item in `api_roots`. root_dict = dict(zip(roots, self._api_roots)) - self._default = root_dict.get(response.get("default")) + self._default = root_dict.get(response.get("default")) # optional + self._validate_server() self._loaded = True
oasis-open/cti-taxii-client
0201af14e578714a297aff795413babc425a2219
diff --git a/taxii2client/test/test_client.py b/taxii2client/test/test_client.py index de2e303..afdb0fe 100644 --- a/taxii2client/test/test_client.py +++ b/taxii2client/test/test_client.py @@ -7,7 +7,7 @@ import six from taxii2client import ( MEDIA_TYPE_STIX_V20, MEDIA_TYPE_TAXII_V20, AccessError, ApiRoot, - Collection, InvalidArgumentsError, Server, TAXIIServiceException, + Collection, InvalidArgumentsError, Server, Status, TAXIIServiceException, ValidationError, _filter_kwargs_to_query_params, _HTTPConnection, _TAXIIEndpoint, get_collection_by_id ) @@ -187,6 +187,46 @@ STATUS_RESPONSE = """{ }""" [email protected] +def status_dict(): + return { + "id": "2d086da7-4bdc-4f91-900e-d77486753710", + "status": "pending", + "request_timestamp": "2016-11-02T12:34:34.12345Z", + "total_count": 4, + "success_count": 1, + "successes": [ + "indicator--c410e480-e42b-47d1-9476-85307c12bcbf" + ], + "failure_count": 1, + "failures": [ + { + "id": "malware--664fa29d-bf65-4f28-a667-bdb76f29ec98", + "message": "Unable to process object" + } + ], + "pending_count": 2, + "pendings": [ + "indicator--252c7c11-daf2-42bd-843b-be65edca9f61", + "relationship--045585ad-a22f-4333-af33-bfd503a683b5" + ] + } + + [email protected] +def collection_dict(): + return { + "id": "e278b87e-0f9b-4c63-a34c-c8f0b3e91acb", + "title": "Writable Collection", + "description": "This collection is a dropbox for submitting indicators", + "can_read": False, + "can_write": True, + "media_types": [ + "application/vnd.oasis.stix+json; version=2.0" + ] + } + + @pytest.fixture def server(): """Default server object for example.com""" @@ -222,6 +262,11 @@ def bad_writable_collection(): return Collection(COLLECTION_URL) +def set_api_root_response(response): + responses.add(responses.GET, API_ROOT_URL, body=response, + status=200, content_type=MEDIA_TYPE_TAXII_V20) + + def set_discovery_response(response): responses.add(responses.GET, DISCOVERY_URL, body=response, status=200, content_type=MEDIA_TYPE_TAXII_V20) @@ -282,6 +327,66 @@ def test_discovery_with_no_default(server): assert server.default is None [email protected] +def test_discovery_with_no_title(server): + response = """{ + "description": "This TAXII Server contains a listing of...", + "contact": "string containing contact information", + "api_roots": [ + "https://example.com/api1/", + "https://example.com/api2/", + "https://example.net/trustgroup1/" + ] + }""" + set_discovery_response(response) + with pytest.raises(ValidationError) as excinfo: + server.refresh() + + assert "No 'title' in Server Discovery for request 'https://example.com/taxii/'" == str(excinfo.value) + + [email protected] +def test_api_root_no_title(api_root): + set_api_root_response("""{ + "description": "A trust group setup for malware researchers", + "versions": ["taxii-2.0"], + "max_content_length": 9765625 + }""") + with pytest.raises(ValidationError) as excinfo: + assert api_root._loaded_information is False + api_root.refresh_information() + + assert "No 'title' in API Root for request 'https://example.com/api1/'" == str(excinfo.value) + + [email protected] +def test_api_root_no_versions(api_root): + set_api_root_response("""{ + "title": "Malware Research Group", + "description": "A trust group setup for malware researchers", + "max_content_length": 9765625 + }""") + with pytest.raises(ValidationError) as excinfo: + assert api_root._loaded_information is False + api_root.refresh_information() + + assert "No 'versions' in API Root for request 'https://example.com/api1/'" == str(excinfo.value) + + [email protected] +def test_api_root_no_max_content_length(api_root): + set_api_root_response("""{ + "title": "Malware Research Group", + "description": "A trust group setup for malware researchers", + "versions": ["taxii-2.0"] + }""") + with pytest.raises(ValidationError) as excinfo: + assert api_root._loaded_information is False + api_root.refresh_information() + + assert "No 'max_content_length' in API Root for request 'https://example.com/api1/'" == str(excinfo.value) + + @responses.activate def test_api_root(api_root): responses.add(responses.GET, API_ROOT_URL, API_ROOT_RESPONSE, @@ -563,3 +668,93 @@ def test_taxii_endpoint_raises_exception(): _TAXIIEndpoint("https://example.com/api1/collections/", conn, "other", "test") assert "A connection and user/password may not both be provided." in str(excinfo.value) + + +def test_status_missing_id_property(status_dict): + with pytest.raises(ValidationError) as excinfo: + status_dict.pop("id") + Status("https://example.com/api1/status/12345678-1234-1234-1234-123456789012/", + user="foo", password="bar", verify=False, **status_dict) + + assert "No 'id' in Status for request 'https://example.com/api1/status/12345678-1234-1234-1234-123456789012/'" == str(excinfo.value) + + +def test_status_missing_status_property(status_dict): + with pytest.raises(ValidationError) as excinfo: + status_dict.pop("status") + Status("https://example.com/api1/status/12345678-1234-1234-1234-123456789012/", + user="foo", password="bar", verify=False, **status_dict) + + assert "No 'status' in Status for request 'https://example.com/api1/status/12345678-1234-1234-1234-123456789012/'" == str(excinfo.value) + + +def test_status_missing_total_count_property(status_dict): + with pytest.raises(ValidationError) as excinfo: + status_dict.pop("total_count") + Status("https://example.com/api1/status/12345678-1234-1234-1234-123456789012/", + user="foo", password="bar", verify=False, **status_dict) + + assert "No 'total_count' in Status for request 'https://example.com/api1/status/12345678-1234-1234-1234-123456789012/'" == str(excinfo.value) + + +def test_status_missing_success_count_property(status_dict): + with pytest.raises(ValidationError) as excinfo: + status_dict.pop("success_count") + Status("https://example.com/api1/status/12345678-1234-1234-1234-123456789012/", + user="foo", password="bar", verify=False, **status_dict) + + assert "No 'success_count' in Status for request 'https://example.com/api1/status/12345678-1234-1234-1234-123456789012/'" == str(excinfo.value) + + +def test_status_missing_failure_count_property(status_dict): + with pytest.raises(ValidationError) as excinfo: + status_dict.pop("failure_count") + Status("https://example.com/api1/status/12345678-1234-1234-1234-123456789012/", + user="foo", password="bar", verify=False, **status_dict) + + assert "No 'failure_count' in Status for request 'https://example.com/api1/status/12345678-1234-1234-1234-123456789012/'" == str(excinfo.value) + + +def test_status_missing_pending_count_property(status_dict): + with pytest.raises(ValidationError) as excinfo: + status_dict.pop("pending_count") + Status("https://example.com/api1/status/12345678-1234-1234-1234-123456789012/", + user="foo", password="bar", verify=False, **status_dict) + + assert "No 'pending_count' in Status for request 'https://example.com/api1/status/12345678-1234-1234-1234-123456789012/'" == str(excinfo.value) + + +def test_collection_missing_id_property(collection_dict): + with pytest.raises(ValidationError) as excinfo: + collection_dict.pop("id") + Collection("https://example.com/api1/collections/91a7b528-80eb-42ed-a74d-c6fbd5a26116/", + user="foo", password="bar", verify=False, **collection_dict) + + assert "No 'id' in Collection for request 'https://example.com/api1/collections/91a7b528-80eb-42ed-a74d-c6fbd5a26116/'" == str(excinfo.value) + + +def test_collection_missing_title_property(collection_dict): + with pytest.raises(ValidationError) as excinfo: + collection_dict.pop("title") + Collection("https://example.com/api1/collections/91a7b528-80eb-42ed-a74d-c6fbd5a26116/", + user="foo", password="bar", verify=False, **collection_dict) + + assert "No 'title' in Collection for request 'https://example.com/api1/collections/91a7b528-80eb-42ed-a74d-c6fbd5a26116/'" == str(excinfo.value) + + +def test_collection_missing_can_read_property(collection_dict): + with pytest.raises(ValidationError) as excinfo: + collection_dict.pop("can_read") + Collection("https://example.com/api1/collections/91a7b528-80eb-42ed-a74d-c6fbd5a26116/", + user="foo", password="bar", verify=False, **collection_dict) + + assert "No 'can_read' in Collection for request 'https://example.com/api1/collections/91a7b528-80eb-42ed-a74d-c6fbd5a26116/'" == str(excinfo.value) + + +def test_collection_missing_can_write_property(collection_dict): + with pytest.raises(ValidationError) as excinfo: + collection_dict.pop("can_write") + Collection("https://example.com/api1/collections/91a7b528-80eb-42ed-a74d-c6fbd5a26116/", + user="foo", password="bar", verify=False, **collection_dict) + + assert "No 'can_write' in Collection for request 'https://example.com/api1/collections/91a7b528-80eb-42ed-a74d-c6fbd5a26116/'" == str(excinfo.value)
Verify correct handling of all optional fields. For example: If the server's API root is without description, the client will throw an exception. But the description is optional according to the spec, I expected there is no error here.
0.0
[ "taxii2client/test/test_client.py::test_discovery_with_no_title", "taxii2client/test/test_client.py::test_api_root_no_title", "taxii2client/test/test_client.py::test_api_root_no_versions", "taxii2client/test/test_client.py::test_api_root_no_max_content_length", "taxii2client/test/test_client.py::test_status_missing_id_property", "taxii2client/test/test_client.py::test_status_missing_status_property", "taxii2client/test/test_client.py::test_status_missing_total_count_property", "taxii2client/test/test_client.py::test_status_missing_success_count_property", "taxii2client/test/test_client.py::test_status_missing_failure_count_property", "taxii2client/test/test_client.py::test_status_missing_pending_count_property", "taxii2client/test/test_client.py::test_collection_missing_id_property", "taxii2client/test/test_client.py::test_collection_missing_title_property", "taxii2client/test/test_client.py::test_collection_missing_can_read_property", "taxii2client/test/test_client.py::test_collection_missing_can_write_property" ]
[ "taxii2client/test/test_client.py::test_server_discovery", "taxii2client/test/test_client.py::test_minimal_discovery_response", "taxii2client/test/test_client.py::test_discovery_with_no_default", "taxii2client/test/test_client.py::test_api_root", "taxii2client/test/test_client.py::test_api_root_collections", "taxii2client/test/test_client.py::test_get_collection_by_id_exists", "taxii2client/test/test_client.py::test_get_collection_by_id_not_present", "taxii2client/test/test_client.py::test_collection", "taxii2client/test/test_client.py::test_collection_unexpected_kwarg", "taxii2client/test/test_client.py::test_get_collection_objects", "taxii2client/test/test_client.py::test_get_object", "taxii2client/test/test_client.py::test_cannot_write_to_readonly_collection", "taxii2client/test/test_client.py::test_add_object_to_collection", "taxii2client/test/test_client.py::test_add_object_to_collection_dict", "taxii2client/test/test_client.py::test_add_object_rases_error_when_collection_id_does_not_match_url", "taxii2client/test/test_client.py::test_cannot_read_from_writeonly_collection", "taxii2client/test/test_client.py::test_get_manifest", "taxii2client/test/test_client.py::test_get_status", "taxii2client/test/test_client.py::test_content_type_valid", "taxii2client/test/test_client.py::test_content_type_invalid", "taxii2client/test/test_client.py::test_url_filter_type", "taxii2client/test/test_client.py::test_filter_id", "taxii2client/test/test_client.py::test_filter_version", "taxii2client/test/test_client.py::test_filter_added_after", "taxii2client/test/test_client.py::test_filter_combo", "taxii2client/test/test_client.py::test_params_filter_unknown", "taxii2client/test/test_client.py::test_taxii_endpoint_raises_exception" ]
2018-04-09 20:08:53+00:00
4,317
oasis-open__cti-taxii-client-45
diff --git a/docs/conf.py b/docs/conf.py index 47930be..70f3419 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -33,7 +33,6 @@ # ones. extensions = [ 'sphinx-prompt', - 'nbsphinx', 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.napoleon', diff --git a/setup.py b/setup.py index 132e987..2ca235c 100644 --- a/setup.py +++ b/setup.py @@ -47,6 +47,7 @@ setup( ], 'docs': [ 'sphinx', + 'sphinx-prompt', ] } ) diff --git a/taxii2client/__init__.py b/taxii2client/__init__.py index e001bb6..36e5929 100644 --- a/taxii2client/__init__.py +++ b/taxii2client/__init__.py @@ -8,6 +8,7 @@ import time import pytz import requests +import requests.structures # is this public API? import six import six.moves.urllib.parse as urlparse @@ -15,6 +16,7 @@ __version__ = '0.3.1' MEDIA_TYPE_STIX_V20 = "application/vnd.oasis.stix+json; version=2.0" MEDIA_TYPE_TAXII_V20 = "application/vnd.oasis.taxii+json; version=2.0" +DEFAULT_USER_AGENT = "taxii2-client/" + __version__ class TAXIIServiceException(Exception): @@ -217,7 +219,8 @@ class Status(_TAXIIEndpoint): def refresh(self, accept=MEDIA_TYPE_TAXII_V20): """Updates Status information""" - response = self.__raw = self._conn.get(self.url, accept=accept) + response = self.__raw = self._conn.get(self.url, + headers={"Accept": accept}) self._populate_fields(**response) def wait_until_final(self, poll_interval=1, timeout=60): @@ -457,7 +460,8 @@ class Collection(_TAXIIEndpoint): def refresh(self, accept=MEDIA_TYPE_TAXII_V20): """Update Collection information""" - response = self.__raw = self._conn.get(self.url, accept=accept) + response = self.__raw = self._conn.get(self.url, + headers={"Accept": accept}) self._populate_fields(**response) self._loaded = True @@ -465,7 +469,7 @@ class Collection(_TAXIIEndpoint): """Implement the ``Get Objects`` endpoint (section 5.3)""" self._verify_can_read() query_params = _filter_kwargs_to_query_params(filter_kwargs) - return self._conn.get(self.objects_url, accept=accept, + return self._conn.get(self.objects_url, headers={"Accept": accept}, params=query_params) def get_object(self, obj_id, version=None, accept=MEDIA_TYPE_STIX_V20): @@ -475,7 +479,7 @@ class Collection(_TAXIIEndpoint): query_params = None if version: query_params = _filter_kwargs_to_query_params({"version": version}) - return self._conn.get(url, accept=accept, + return self._conn.get(url, headers={"Accept": accept}, params=query_params) def add_objects(self, bundle, wait_for_completion=True, poll_interval=1, @@ -552,7 +556,7 @@ class Collection(_TAXIIEndpoint): self._verify_can_read() query_params = _filter_kwargs_to_query_params(filter_kwargs) return self._conn.get(self.url + "manifest/", - accept=accept, + headers={"Accept": accept}, params=query_params) @@ -651,7 +655,8 @@ class ApiRoot(_TAXIIEndpoint): This invokes the ``Get API Root Information`` endpoint. """ - response = self.__raw = self._conn.get(self.url, accept=accept) + response = self.__raw = self._conn.get(self.url, + headers={"Accept": accept}) self._title = response.get("title") # required self._description = response.get("description") # optional @@ -667,7 +672,7 @@ class ApiRoot(_TAXIIEndpoint): This invokes the ``Get Collections`` endpoint. """ url = self.url + "collections/" - response = self._conn.get(url, accept=accept) + response = self._conn.get(url, headers={"Accept": accept}) self._collections = [] for item in response.get("collections", []): # optional @@ -680,7 +685,7 @@ class ApiRoot(_TAXIIEndpoint): def get_status(self, status_id, accept=MEDIA_TYPE_TAXII_V20): status_url = self.url + "status/" + status_id + "/" - response = self._conn.get(status_url, accept=accept) + response = self._conn.get(status_url, headers={"Accept": accept}) return Status(status_url, conn=self._conn, status_info=response) @@ -763,8 +768,7 @@ class Server(_TAXIIEndpoint): def refresh(self): """Update the Server information and list of API Roots""" - response = self.__raw = self._conn.get(self.url, - accept=MEDIA_TYPE_TAXII_V20) + response = self.__raw = self._conn.get(self.url) self._title = response.get("title") # required self._description = response.get("description") # optional @@ -801,17 +805,22 @@ class _HTTPConnection(object): """ - def __init__(self, user=None, password=None, verify=True, proxies=None): + def __init__(self, user=None, password=None, verify=True, proxies=None, + user_agent=DEFAULT_USER_AGENT): """Create a connection session. Args: user (str): username for authentication (optional) password (str): password for authentication (optional) verify (bool): validate the entity credentials. (default: True) - + user_agent (str): A value to use for the User-Agent header in + requests. If not given, use a default value which represents + this library. """ self.session = requests.Session() self.session.verify = verify + # enforce that we always have a connection-default user agent. + self.user_agent = user_agent or DEFAULT_USER_AGENT if user and password: self.session.auth = requests.auth.HTTPBasicAuth(user, password) if proxies: @@ -834,22 +843,27 @@ class _HTTPConnection(object): content_type_tokens[0] == 'application/vnd.oasis.stix+json') ) - def get(self, url, accept, params=None): + def get(self, url, headers=None, params=None): """Perform an HTTP GET, using the saved requests.Session and auth info. + If "Accept" isn't one of the given headers, a default TAXII mime type is + used. Regardless, the response type is checked against the accept + header value, and an exception is raised if they don't match. Args: url (str): URL to retrieve - accept (str): media type to include in the ``Accept:`` header. This - function checks that the ``Content-Type:`` header on the HTTP - response matches this media type. + headers (dict): Any other headers to be added to the request. params: dictionary or bytes to be sent in the query string for the request. (optional) """ - headers = { - "Accept": accept - } - resp = self.session.get(url, headers=headers, params=params) + + merged_headers = self._merge_headers(headers) + + if "Accept" not in merged_headers: + merged_headers["Accept"] = MEDIA_TYPE_TAXII_V20 + accept = merged_headers["Accept"] + + resp = self.session.get(url, headers=merged_headers, params=params) resp.raise_for_status() @@ -866,8 +880,20 @@ class _HTTPConnection(object): URL query parameters, and the given JSON in the request body. The extra query parameters are merged with any which already exist in the URL. + + Args: + url (str): URL to retrieve + headers (dict): Any other headers to be added to the request. + params: dictionary or bytes to be sent in the query string for the + request. (optional) + data: data to post as dictionary, list of tuples, bytes, or + file-like object """ - resp = self.session.post(url, headers=headers, params=params, data=data) + + merged_headers = self._merge_headers(headers) + + resp = self.session.post(url, headers=merged_headers, params=params, + data=data) resp.raise_for_status() return _to_json(resp) @@ -875,6 +901,42 @@ class _HTTPConnection(object): """Closes connections. This object is no longer usable.""" self.session.close() + def _merge_headers(self, call_specific_headers): + """ + Merge headers from different sources together. Headers passed to the + post/get methods have highest priority, then headers associated with + the connection object itself have next priority. + + :param call_specific_headers: A header dict from the get/post call, or + None (the default for those methods). + :return: A key-case-insensitive MutableMapping object which contains + the merged headers. (This doesn't actually return a dict.) + """ + + # A case-insensitive mapping is necessary here so that there is + # predictable behavior. If a plain dict were used, you'd get keys in + # the merged dict which differ only in case. The requests library + # would merge them internally, and it would be unpredictable which key + # is chosen for the final set of headers. Another possible approach + # would be to upper/lower-case everything, but this seemed easier. On + # the other hand, I don't know if CaseInsensitiveDict is public API...? + + # First establish defaults + merged_headers = requests.structures.CaseInsensitiveDict({ + "User-Agent": self.user_agent + }) + + # Then overlay with specifics from post/get methods + if call_specific_headers: + merged_headers.update(call_specific_headers) + + # Special "User-Agent" header check, to ensure one is always sent. + # The call-specific overlay could have null'd out that header. + if not merged_headers.get("User-Agent"): + merged_headers["User-Agent"] = self.user_agent + + return merged_headers + def _to_json(resp): """
oasis-open/cti-taxii-client
e1b5b8fb77582a3dba56cd7ce1930e8b44c640f3
diff --git a/taxii2client/test/test_client.py b/taxii2client/test/test_client.py index 958dc6f..d80b2a3 100644 --- a/taxii2client/test/test_client.py +++ b/taxii2client/test/test_client.py @@ -6,10 +6,10 @@ import responses import six from taxii2client import ( - MEDIA_TYPE_STIX_V20, MEDIA_TYPE_TAXII_V20, AccessError, ApiRoot, - Collection, InvalidArgumentsError, InvalidJSONError, Server, Status, - TAXIIServiceException, ValidationError, _filter_kwargs_to_query_params, - _HTTPConnection, _TAXIIEndpoint + DEFAULT_USER_AGENT, MEDIA_TYPE_STIX_V20, MEDIA_TYPE_TAXII_V20, AccessError, + ApiRoot, Collection, InvalidArgumentsError, InvalidJSONError, Server, + Status, TAXIIServiceException, ValidationError, + _filter_kwargs_to_query_params, _HTTPConnection, _TAXIIEndpoint ) TAXII_SERVER = "example.com" @@ -697,7 +697,8 @@ def test_valid_content_type_for_connection(): content_type=MEDIA_TYPE_TAXII_V20 + "; charset=utf-8") conn = _HTTPConnection(user="foo", password="bar", verify=False) - conn.get("https://example.com/api1/collections/91a7b528-80eb-42ed-a74d-c6fbd5a26116/", MEDIA_TYPE_TAXII_V20, None) + conn.get("https://example.com/api1/collections/91a7b528-80eb-42ed-a74d-c6fbd5a26116/", + headers={"Accept": MEDIA_TYPE_TAXII_V20}) @responses.activate @@ -708,7 +709,8 @@ def test_invalid_content_type_for_connection(): with pytest.raises(TAXIIServiceException) as excinfo: conn = _HTTPConnection(user="foo", password="bar", verify=False) - conn.get("https://example.com/api1/collections/91a7b528-80eb-42ed-a74d-c6fbd5a26116/", MEDIA_TYPE_TAXII_V20 + "; charset=utf-8", None) + conn.get("https://example.com/api1/collections/91a7b528-80eb-42ed-a74d-c6fbd5a26116/", + headers={"Accept": MEDIA_TYPE_TAXII_V20 + "; charset=utf-8"}) assert ("Unexpected Response. Got Content-Type: 'application/vnd.oasis.taxii+json; " "version=2.0' for Accept: 'application/vnd.oasis.taxii+json; version=2.0; " @@ -813,3 +815,58 @@ def test_collection_missing_can_write_property(collection_dict): collection_info=collection_dict) assert "No 'can_write' in Collection for request 'https://example.com/api1/collections/91a7b528-80eb-42ed-a74d-c6fbd5a26116/'" == str(excinfo.value) + + +def test_user_agent_defaulting(): + conn = _HTTPConnection(user_agent="foo/1.0") + headers = conn._merge_headers({}) + + # also test key access is case-insensitive + assert headers["user-agent"] == "foo/1.0" + + +def test_user_agent_overriding(): + conn = _HTTPConnection(user_agent="foo/1.0") + headers = conn._merge_headers({"User-Agent": "bar/2.0"}) + + assert headers["user-agent"] == "bar/2.0" + + +def test_user_agent_enforcing1(): + conn = _HTTPConnection(user_agent=None) + headers = conn._merge_headers({}) + + assert headers["user-agent"] == DEFAULT_USER_AGENT + + +def test_user_agent_enforcing2(): + conn = _HTTPConnection() + headers = conn._merge_headers({"User-Agent": None}) + + assert headers["user-agent"] == DEFAULT_USER_AGENT + + +def test_user_agent_enforcing3(): + conn = _HTTPConnection(user_agent=None) + headers = conn._merge_headers({"User-Agent": None}) + + assert headers["user-agent"] == DEFAULT_USER_AGENT + + +def test_header_merging(): + conn = _HTTPConnection() + headers = conn._merge_headers({"AddedHeader": "addedvalue"}) + + assert headers == { + "user-agent": DEFAULT_USER_AGENT, + "addedheader": "addedvalue" + } + + +def test_header_merge_none(): + conn = _HTTPConnection() + headers = conn._merge_headers(None) + + assert headers == { + "user-agent": DEFAULT_USER_AGENT + }
Allow users to specify the user agent string... ...and/or use a default that is specific to the taxii client.
0.0
[ "taxii2client/test/test_client.py::test_server_discovery", "taxii2client/test/test_client.py::test_bad_json_response", "taxii2client/test/test_client.py::test_minimal_discovery_response", "taxii2client/test/test_client.py::test_discovery_with_no_default", "taxii2client/test/test_client.py::test_discovery_with_no_title", "taxii2client/test/test_client.py::test_api_root_no_title", "taxii2client/test/test_client.py::test_api_root_no_versions", "taxii2client/test/test_client.py::test_api_root_no_max_content_length", "taxii2client/test/test_client.py::test_api_root", "taxii2client/test/test_client.py::test_api_root_collections", "taxii2client/test/test_client.py::test_collection", "taxii2client/test/test_client.py::test_collection_unexpected_kwarg", "taxii2client/test/test_client.py::test_get_collection_objects", "taxii2client/test/test_client.py::test_get_object", "taxii2client/test/test_client.py::test_cannot_write_to_readonly_collection", "taxii2client/test/test_client.py::test_add_object_to_collection", "taxii2client/test/test_client.py::test_add_object_to_collection_dict", "taxii2client/test/test_client.py::test_add_object_rases_error_when_collection_id_does_not_match_url", "taxii2client/test/test_client.py::test_cannot_read_from_writeonly_collection", "taxii2client/test/test_client.py::test_get_manifest", "taxii2client/test/test_client.py::test_get_status", "taxii2client/test/test_client.py::test_status_raw", "taxii2client/test/test_client.py::test_content_type_valid", "taxii2client/test/test_client.py::test_content_type_invalid", "taxii2client/test/test_client.py::test_url_filter_type", "taxii2client/test/test_client.py::test_filter_id", "taxii2client/test/test_client.py::test_filter_version", "taxii2client/test/test_client.py::test_filter_added_after", "taxii2client/test/test_client.py::test_filter_combo", "taxii2client/test/test_client.py::test_params_filter_unknown", "taxii2client/test/test_client.py::test_taxii_endpoint_raises_exception", "taxii2client/test/test_client.py::test_valid_content_type_for_connection", "taxii2client/test/test_client.py::test_invalid_content_type_for_connection", "taxii2client/test/test_client.py::test_status_missing_id_property", "taxii2client/test/test_client.py::test_status_missing_status_property", "taxii2client/test/test_client.py::test_status_missing_total_count_property", "taxii2client/test/test_client.py::test_status_missing_success_count_property", "taxii2client/test/test_client.py::test_status_missing_failure_count_property", "taxii2client/test/test_client.py::test_status_missing_pending_count_property", "taxii2client/test/test_client.py::test_collection_missing_id_property", "taxii2client/test/test_client.py::test_collection_missing_title_property", "taxii2client/test/test_client.py::test_collection_missing_can_read_property", "taxii2client/test/test_client.py::test_collection_missing_can_write_property", "taxii2client/test/test_client.py::test_user_agent_defaulting", "taxii2client/test/test_client.py::test_user_agent_overriding", "taxii2client/test/test_client.py::test_user_agent_enforcing1", "taxii2client/test/test_client.py::test_user_agent_enforcing2", "taxii2client/test/test_client.py::test_user_agent_enforcing3", "taxii2client/test/test_client.py::test_header_merging", "taxii2client/test/test_client.py::test_header_merge_none" ]
[]
2018-08-26 00:26:54+00:00
4,318
oasis-open__cti-taxii-client-47
diff --git a/taxii2client/__init__.py b/taxii2client/__init__.py index 36e5929..5536a20 100644 --- a/taxii2client/__init__.py +++ b/taxii2client/__init__.py @@ -498,7 +498,7 @@ class Collection(_TAXIIEndpoint): expires, or the operation completes. Args: - bundle (str): A STIX bundle with the objects to add. + bundle: A STIX bundle with the objects to add (string, dict, binary) wait_for_completion (bool): Whether to wait for the add operation to complete before returning poll_interval (int): If waiting for completion, how often to poll @@ -528,13 +528,21 @@ class Collection(_TAXIIEndpoint): } if isinstance(bundle, dict): - if six.PY2: - bundle = json.dumps(bundle, encoding="utf-8") - else: - bundle = json.dumps(bundle) + json_text = json.dumps(bundle, ensure_ascii=False) + data = json_text.encode("utf-8") + + elif isinstance(bundle, six.text_type): + data = bundle.encode("utf-8") + + elif isinstance(bundle, six.binary_type): + data = bundle + + else: + raise TypeError("Don't know how to handle type '{}'".format( + type(bundle).__name__)) status_json = self._conn.post(self.objects_url, headers=headers, - data=bundle) + data=data) status_url = urlparse.urljoin( self.url, @@ -875,25 +883,34 @@ class _HTTPConnection(object): return _to_json(resp) - def post(self, url, headers=None, params=None, data=None): + def post(self, url, headers=None, params=None, **kwargs): """Send a JSON POST request with the given request headers, additional URL query parameters, and the given JSON in the request body. The extra query parameters are merged with any which already exist in the - URL. + URL. The 'json' and 'data' parameters may not both be given. Args: url (str): URL to retrieve headers (dict): Any other headers to be added to the request. params: dictionary or bytes to be sent in the query string for the request. (optional) - data: data to post as dictionary, list of tuples, bytes, or - file-like object + json: json to send in the body of the Request. This must be a + JSON-serializable object. (optional) + data: raw request body data. May be a dictionary, list of tuples, + bytes, or file-like object to send in the body of the Request. + (optional) """ - merged_headers = self._merge_headers(headers) + if len(kwargs) > 1: + raise InvalidArgumentsError("Too many extra args ({} > 1)".format( + len(kwargs))) + + if kwargs: + kwarg = next(iter(kwargs)) + if kwarg not in ("json", "data"): + raise InvalidArgumentsError("Invalid kwarg: " + kwarg) - resp = self.session.post(url, headers=merged_headers, params=params, - data=data) + resp = self.session.post(url, headers=headers, params=params, **kwargs) resp.raise_for_status() return _to_json(resp)
oasis-open/cti-taxii-client
9c8130d5bcf793fde749a3b46bcb822168bcec30
diff --git a/taxii2client/test/test_client.py b/taxii2client/test/test_client.py index d80b2a3..0bae132 100644 --- a/taxii2client/test/test_client.py +++ b/taxii2client/test/test_client.py @@ -533,6 +533,34 @@ def test_add_object_to_collection_dict(writable_collection): assert status.pending_count == 0 [email protected] +def test_add_object_to_collection_bin(writable_collection): + responses.add(responses.POST, ADD_WRITABLE_OBJECTS_URL, + ADD_OBJECTS_RESPONSE, status=202, + content_type=MEDIA_TYPE_TAXII_V20) + + bin_bundle = STIX_BUNDLE.encode("utf-8") + + status = writable_collection.add_objects(bin_bundle) + + assert status.status == "complete" + assert status.total_count == 1 + assert status.success_count == 1 + assert len(status.successes) == 1 + assert status.failure_count == 0 + assert status.pending_count == 0 + + [email protected] +def test_add_object_to_collection_badtype(writable_collection): + responses.add(responses.POST, ADD_WRITABLE_OBJECTS_URL, + ADD_OBJECTS_RESPONSE, status=202, + content_type=MEDIA_TYPE_TAXII_V20) + + with pytest.raises(TypeError): + writable_collection.add_objects([1, 2, 3]) + + @responses.activate def test_add_object_rases_error_when_collection_id_does_not_match_url( bad_writable_collection): @@ -817,6 +845,19 @@ def test_collection_missing_can_write_property(collection_dict): assert "No 'can_write' in Collection for request 'https://example.com/api1/collections/91a7b528-80eb-42ed-a74d-c6fbd5a26116/'" == str(excinfo.value) +def test_conn_post_kwarg_errors(): + conn = _HTTPConnection() + + with pytest.raises(InvalidArgumentsError): + conn.post(DISCOVERY_URL, data=1, json=2) + + with pytest.raises(InvalidArgumentsError): + conn.post(DISCOVERY_URL, data=1, foo=2) + + with pytest.raises(InvalidArgumentsError): + conn.post(DISCOVERY_URL, foo=1) + + def test_user_agent_defaulting(): conn = _HTTPConnection(user_agent="foo/1.0") headers = conn._merge_headers({})
Funny JSON handling I first started noticing this while working on the user-agent changes (#45), but this isn't directly related to those changes, so I am making a separate issue for this. One of the things I added (and forgot to mention in the commit message, oops) was to add parameter documentation to _HTTPConnection.post(), which for some reason had been missing. For the "data" parameter, I just copied text from the [Requests documentation](http://docs.python-requests.org/en/master/api/#requests.Session.post), since it's passed directly into Session.post(). Notice that JSON content is not listed as a legal value. That was odd, because aren't the TAXII services all JSON-based? Note also that there is a "json" parameter you can use specifically for JSON. Wouldn't it have made more sense to use that? This got me looking at the JSON handling. The usage of the "data" parameter within taxii2-client is via the Collection.add_objects() method; the actual value is obtained [here](https://github.com/oasis-open/cti-taxii-client/blob/d4fb580379b7ac0ea079cf8becd2348f4e878c9e/taxii2client/__init__.py?#L526-L530): ```python if isinstance(bundle, dict): if six.PY2: bundle = json.dumps(bundle, encoding="utf-8") else: bundle = json.dumps(bundle) ``` (I just picked master branch head commit as of this writing, to refer to; the aforementioned PR hasn't changed this part.) This code snip creates JSON which is subsequently passed via "data" parameter, instead of using the "json" parameter and letting Requests take care of the conversion. There may be some reinvention of the wheel here. What of that "encoding" parameter though? Why is it hard-coded, and why make encoding decisions in the Collection endpoint class anyway? To start with, here's what I think the encoding kwarg actually does: in case there are any binary values in the passed dict, they must be decoded to strings before being encoded as JSON (JSON is a textual format, after all). The encoding argument describes how to do that. I.e. the *en*coding argument is actually about *de*coding. What may have happened is a misunderstanding: that a decision needed to be made here about what to do with high-value codepoints, and the decision was to encode as utf-8. Lending credence to this idea is that the TAXII 2.0 spec actually defines the string type as `The string data type represents a finite-length string of valid characters from the Unicode coded character set [ISO10646] that are encoded in UTF-8.` So the spec actually mentions utf-8. Perhaps the idea was that a json.dumps() call could do double-duty, as a JSON-encode operation followed by a string encode operation. On the other hand, this code is written to behave differently depending on python version, and there is no usage of encoding on python3. If encoding needed to happen for python2, why not python3? On python3 the API changed: there actually is no "encoding" parameter in json.dumps(). Under this misunderstanding, that would mean that the result must remain text, and text is passed to _HTTPConnection.post(), then to Session.post(), which is invalid according to the documentation. So even if the misunderstanding were true, the code is incorrect. Also, the "ensure_ascii" param was left at default (True), which means there can be no high-value codepoints in the resulting JSON anyway. They will all be escaped using the format "\u1234". JSON specs I looked at do seem to recognize this as an escape syntax, but do we need to do that? Why not let them pass? Here's how I think it should work: - If we actually expect people to pass text-as-binary data in their JSON-serializable objects, we should also allow people to tell us how that text was encoded, not hard-code an assumption. - The above bullet is probably not worth worrying about; I can't see why anyone would want to do that. So I don't see any need to specify an encoding there, and have python-version-dependent code. - Do we really intend for people to be able to pass anything they want to TAXII server endpoints? If we want to restrict this to JSON, maybe we should be using the "json" kwarg to Session.post(), and mirror that in _HTTPConnection.post(). If want to allow anything, maybe we should mirror Session.post() and allow either "data=" or "json=" as kwargs. We would only need "json=" in our endpoint classes. (Btw, when using "json=", Requests automatically encodes the result as utf-8, so it would be compliant.) - Don't use funny escape syntax unless you really have to. No point in layering additional escaping which serves no purpose.
0.0
[ "taxii2client/test/test_client.py::test_conn_post_kwarg_errors" ]
[ "taxii2client/test/test_client.py::test_server_discovery", "taxii2client/test/test_client.py::test_bad_json_response", "taxii2client/test/test_client.py::test_minimal_discovery_response", "taxii2client/test/test_client.py::test_discovery_with_no_default", "taxii2client/test/test_client.py::test_discovery_with_no_title", "taxii2client/test/test_client.py::test_api_root_no_title", "taxii2client/test/test_client.py::test_api_root_no_versions", "taxii2client/test/test_client.py::test_api_root_no_max_content_length", "taxii2client/test/test_client.py::test_api_root", "taxii2client/test/test_client.py::test_api_root_collections", "taxii2client/test/test_client.py::test_collection", "taxii2client/test/test_client.py::test_collection_unexpected_kwarg", "taxii2client/test/test_client.py::test_get_collection_objects", "taxii2client/test/test_client.py::test_get_object", "taxii2client/test/test_client.py::test_cannot_write_to_readonly_collection", "taxii2client/test/test_client.py::test_add_object_to_collection", "taxii2client/test/test_client.py::test_add_object_to_collection_dict", "taxii2client/test/test_client.py::test_add_object_to_collection_bin", "taxii2client/test/test_client.py::test_add_object_to_collection_badtype", "taxii2client/test/test_client.py::test_add_object_rases_error_when_collection_id_does_not_match_url", "taxii2client/test/test_client.py::test_cannot_read_from_writeonly_collection", "taxii2client/test/test_client.py::test_get_manifest", "taxii2client/test/test_client.py::test_get_status", "taxii2client/test/test_client.py::test_status_raw", "taxii2client/test/test_client.py::test_content_type_valid", "taxii2client/test/test_client.py::test_content_type_invalid", "taxii2client/test/test_client.py::test_url_filter_type", "taxii2client/test/test_client.py::test_filter_id", "taxii2client/test/test_client.py::test_filter_version", "taxii2client/test/test_client.py::test_filter_added_after", "taxii2client/test/test_client.py::test_filter_combo", "taxii2client/test/test_client.py::test_params_filter_unknown", "taxii2client/test/test_client.py::test_taxii_endpoint_raises_exception", "taxii2client/test/test_client.py::test_valid_content_type_for_connection", "taxii2client/test/test_client.py::test_invalid_content_type_for_connection", "taxii2client/test/test_client.py::test_status_missing_id_property", "taxii2client/test/test_client.py::test_status_missing_status_property", "taxii2client/test/test_client.py::test_status_missing_total_count_property", "taxii2client/test/test_client.py::test_status_missing_success_count_property", "taxii2client/test/test_client.py::test_status_missing_failure_count_property", "taxii2client/test/test_client.py::test_status_missing_pending_count_property", "taxii2client/test/test_client.py::test_collection_missing_id_property", "taxii2client/test/test_client.py::test_collection_missing_title_property", "taxii2client/test/test_client.py::test_collection_missing_can_read_property", "taxii2client/test/test_client.py::test_collection_missing_can_write_property", "taxii2client/test/test_client.py::test_user_agent_defaulting", "taxii2client/test/test_client.py::test_user_agent_overriding", "taxii2client/test/test_client.py::test_user_agent_enforcing1", "taxii2client/test/test_client.py::test_user_agent_enforcing2", "taxii2client/test/test_client.py::test_user_agent_enforcing3", "taxii2client/test/test_client.py::test_header_merging", "taxii2client/test/test_client.py::test_header_merge_none" ]
2018-09-04 20:55:37+00:00
4,319
oasis-open__cti-taxii-client-54
diff --git a/taxii2client/__init__.py b/taxii2client/__init__.py index 8d5c722..548f279 100644 --- a/taxii2client/__init__.py +++ b/taxii2client/__init__.py @@ -217,6 +217,10 @@ class Status(_TAXIIEndpoint): """Get the "raw" status response (parsed JSON).""" return self.__raw + @property + def custom_properties(self): + return self._custom_properties + def refresh(self, accept=MEDIA_TYPE_TAXII_V20): """Updates Status information""" response = self.__raw = self._conn.get(self.url, @@ -244,7 +248,8 @@ class Status(_TAXIIEndpoint): def _populate_fields(self, id=None, status=None, total_count=None, success_count=None, failure_count=None, pending_count=None, request_timestamp=None, - successes=None, failures=None, pendings=None): + successes=None, failures=None, pendings=None, + **kwargs): self.id = id # required self.status = status # required self.request_timestamp = request_timestamp # optional @@ -256,6 +261,9 @@ class Status(_TAXIIEndpoint): self.failures = failures or [] # optional self.pendings = pendings or [] # optional + # Anything not captured by the optional arguments is treated as custom + self._custom_properties = kwargs + self._validate_status() def _validate_status(self): @@ -400,6 +408,11 @@ class Collection(_TAXIIEndpoint): self._ensure_loaded() return self._media_types + @property + def custom_properties(self): + self._ensure_loaded() + return self._custom_properties + @property def objects_url(self): return self.url + "objects/" @@ -411,7 +424,8 @@ class Collection(_TAXIIEndpoint): return self.__raw def _populate_fields(self, id=None, title=None, description=None, - can_read=None, can_write=None, media_types=None): + can_read=None, can_write=None, media_types=None, + **kwargs): self._id = id # required self._title = title # required self._description = description # optional @@ -419,6 +433,9 @@ class Collection(_TAXIIEndpoint): self._can_write = can_write # required self._media_types = media_types or [] # optional + # Anything not captured by the optional arguments is treated as custom + self._custom_properties = kwargs + self._validate_collection() def _validate_collection(self): @@ -628,6 +645,11 @@ class ApiRoot(_TAXIIEndpoint): self._ensure_loaded_information() return self._max_content_length + @property + def custom_properties(self): + self._ensure_loaded_information() + return self._custom_properties + @property def _raw(self): """Get the "raw" API root information response (parsed JSON).""" @@ -653,6 +675,18 @@ class ApiRoot(_TAXIIEndpoint): msg = "No 'max_content_length' in API Root for request '{}'" raise ValidationError(msg.format(self.url)) + def _populate_fields(self, title=None, description=None, versions=None, + max_content_length=None, **kwargs): + self._title = title # required + self._description = description # optional + self._versions = versions or [] # required + self._max_content_length = max_content_length # required + + # Anything not captured by the optional arguments is treated as custom + self._custom_properties = kwargs + + self._validate_api_root() + def refresh(self, accept=MEDIA_TYPE_TAXII_V20): """Update the API Root's information and list of Collections""" self.refresh_information(accept) @@ -665,13 +699,7 @@ class ApiRoot(_TAXIIEndpoint): """ response = self.__raw = self._conn.get(self.url, headers={"Accept": accept}) - - self._title = response.get("title") # required - self._description = response.get("description") # optional - self._versions = response.get("versions", []) # required - self._max_content_length = response.get("max_content_length") # required - - self._validate_api_root() + self._populate_fields(**response) self._loaded_information = True def refresh_collections(self, accept=MEDIA_TYPE_TAXII_V20): @@ -757,6 +785,11 @@ class Server(_TAXIIEndpoint): self._ensure_loaded() return self._api_roots + @property + def custom_properties(self): + self._ensure_loaded() + return self._custom_properties + @property def _raw(self): """Get the "raw" server discovery response (parsed JSON).""" @@ -774,14 +807,12 @@ class Server(_TAXIIEndpoint): msg = "No 'title' in Server Discovery for request '{}'" raise ValidationError(msg.format(self.url)) - def refresh(self): - """Update the Server information and list of API Roots""" - response = self.__raw = self._conn.get(self.url) - - self._title = response.get("title") # required - self._description = response.get("description") # optional - self._contact = response.get("contact") # optional - roots = response.get("api_roots", []) # optional + def _populate_fields(self, title=None, description=None, contact=None, + api_roots=None, default=None, **kwargs): + self._title = title # required + self._description = description # optional + self._contact = contact # optional + roots = api_roots or [] # optional self._api_roots = [ApiRoot(url, user=self._user, password=self._password, @@ -791,9 +822,17 @@ class Server(_TAXIIEndpoint): # rather than creating a duplicate. The TAXII 2.0 spec says that the # `default` API Root MUST be an item in `api_roots`. root_dict = dict(zip(roots, self._api_roots)) - self._default = root_dict.get(response.get("default")) # optional + self._default = root_dict.get(default) # optional + + # Anything not captured by the optional arguments is treated as custom + self._custom_properties = kwargs + self._validate_server() + def refresh(self): + """Update the Server information and list of API Roots""" + response = self.__raw = self._conn.get(self.url) + self._populate_fields(**response) self._loaded = True
oasis-open/cti-taxii-client
6e0ab981b7c613e46ab12b2c85567ef921fb7fa0
diff --git a/taxii2client/test/test_client.py b/taxii2client/test/test_client.py index 0bae132..e363d27 100644 --- a/taxii2client/test/test_client.py +++ b/taxii2client/test/test_client.py @@ -911,3 +911,52 @@ def test_header_merge_none(): assert headers == { "user-agent": DEFAULT_USER_AGENT } + + +def test_collection_with_custom_properties(collection_dict): + collection_dict["type"] = "domain" + col_obj = Collection(url=WRITABLE_COLLECTION_URL, collection_info=collection_dict) + assert len(col_obj.custom_properties) == 1 + assert col_obj.custom_properties["type"] == "domain" + + +def test_status_with_custom_properties(status_dict): + status_dict["x_example_com"] = "some value" + status_obj = Status(url=COLLECTION_URL, status_info=status_dict) + assert len(status_obj.custom_properties) == 1 + assert status_obj.custom_properties["x_example_com"] == "some value" + + [email protected] +def test_api_roots_with_custom_properties(api_root): + response = """{ + "title": "Malware Research Group", + "description": "A trust group setup for malware researchers", + "versions": ["taxii-2.0"], + "max_content_length": 9765625, + "x_example_com_total_items": 1000 + }""" + set_api_root_response(response) + api_root.refresh_information() + assert len(api_root.custom_properties) == 1 + assert api_root.custom_properties["x_example_com_total_items"] == 1000 + + [email protected] +def test_server_with_custom_properties(server): + response = """{ + "title": "Some TAXII Server", + "description": "This TAXII Server contains a listing of...", + "contact": "string containing contact information", + "default": "https://example.com/api2/", + "api_roots": [ + "https://example.com/api1/", + "https://example.com/api2/", + "https://example.net/trustgroup1/" + ], + "x_example_com": "some value" + }""" + set_discovery_response(response) + server.refresh() + assert len(server.custom_properties) == 1 + assert server.custom_properties["x_example_com"] == "some value"
ERROR - _populate_fields() got an unexpected keyword argument 'type' ``` server = Server(url, user=self.conf_api["user"], password=self.conf_api["password"], verify=False) api_root = server.api_roots[0] collections = api_root.collections ``` These code lines return this exceptions: > ERROR - _populate_fields() got an unexpected keyword argument 'type' When I use curl, server returns like this: > {"collections": [{"can_read": true, "can_write": false, "description": "This data collection is for collecting malicious domains", "id": "861ecee6-09af-4cc9-8f80-8c6eac8bb5a4", "media_types": ["application/vnd.oasis.stix+json; version=2.0"], "title": "Indicator Domain Collection", "type": "domain"}]} This error happens when we add a new field to collection `"type": "domain"`. But STIX standards allow us to custom collection fields. Can you fix this? Thank you so much!
0.0
[ "taxii2client/test/test_client.py::test_collection_with_custom_properties", "taxii2client/test/test_client.py::test_status_with_custom_properties", "taxii2client/test/test_client.py::test_api_roots_with_custom_properties", "taxii2client/test/test_client.py::test_server_with_custom_properties" ]
[ "taxii2client/test/test_client.py::test_server_discovery", "taxii2client/test/test_client.py::test_bad_json_response", "taxii2client/test/test_client.py::test_minimal_discovery_response", "taxii2client/test/test_client.py::test_discovery_with_no_default", "taxii2client/test/test_client.py::test_discovery_with_no_title", "taxii2client/test/test_client.py::test_api_root_no_title", "taxii2client/test/test_client.py::test_api_root_no_versions", "taxii2client/test/test_client.py::test_api_root_no_max_content_length", "taxii2client/test/test_client.py::test_api_root", "taxii2client/test/test_client.py::test_api_root_collections", "taxii2client/test/test_client.py::test_collection", "taxii2client/test/test_client.py::test_collection_unexpected_kwarg", "taxii2client/test/test_client.py::test_get_collection_objects", "taxii2client/test/test_client.py::test_get_object", "taxii2client/test/test_client.py::test_cannot_write_to_readonly_collection", "taxii2client/test/test_client.py::test_add_object_to_collection", "taxii2client/test/test_client.py::test_add_object_to_collection_dict", "taxii2client/test/test_client.py::test_add_object_to_collection_bin", "taxii2client/test/test_client.py::test_add_object_to_collection_badtype", "taxii2client/test/test_client.py::test_add_object_rases_error_when_collection_id_does_not_match_url", "taxii2client/test/test_client.py::test_cannot_read_from_writeonly_collection", "taxii2client/test/test_client.py::test_get_manifest", "taxii2client/test/test_client.py::test_get_status", "taxii2client/test/test_client.py::test_status_raw", "taxii2client/test/test_client.py::test_content_type_valid", "taxii2client/test/test_client.py::test_content_type_invalid", "taxii2client/test/test_client.py::test_url_filter_type", "taxii2client/test/test_client.py::test_filter_id", "taxii2client/test/test_client.py::test_filter_version", "taxii2client/test/test_client.py::test_filter_added_after", "taxii2client/test/test_client.py::test_filter_combo", "taxii2client/test/test_client.py::test_params_filter_unknown", "taxii2client/test/test_client.py::test_taxii_endpoint_raises_exception", "taxii2client/test/test_client.py::test_valid_content_type_for_connection", "taxii2client/test/test_client.py::test_invalid_content_type_for_connection", "taxii2client/test/test_client.py::test_status_missing_id_property", "taxii2client/test/test_client.py::test_status_missing_status_property", "taxii2client/test/test_client.py::test_status_missing_total_count_property", "taxii2client/test/test_client.py::test_status_missing_success_count_property", "taxii2client/test/test_client.py::test_status_missing_failure_count_property", "taxii2client/test/test_client.py::test_status_missing_pending_count_property", "taxii2client/test/test_client.py::test_collection_missing_id_property", "taxii2client/test/test_client.py::test_collection_missing_title_property", "taxii2client/test/test_client.py::test_collection_missing_can_read_property", "taxii2client/test/test_client.py::test_collection_missing_can_write_property", "taxii2client/test/test_client.py::test_conn_post_kwarg_errors", "taxii2client/test/test_client.py::test_user_agent_defaulting", "taxii2client/test/test_client.py::test_user_agent_overriding", "taxii2client/test/test_client.py::test_user_agent_enforcing1", "taxii2client/test/test_client.py::test_user_agent_enforcing2", "taxii2client/test/test_client.py::test_user_agent_enforcing3", "taxii2client/test/test_client.py::test_header_merging", "taxii2client/test/test_client.py::test_header_merge_none" ]
2018-11-07 18:54:55+00:00
4,320
oasis-open__cti-taxii-client-55
diff --git a/taxii2client/__init__.py b/taxii2client/__init__.py index 548f279..edd90b5 100644 --- a/taxii2client/__init__.py +++ b/taxii2client/__init__.py @@ -159,7 +159,12 @@ class _TAXIIEndpoint(object): else: self._conn = _HTTPConnection(user, password, verify) - self.url = url + # Add trailing slash to TAXII endpoint if missing + # https://github.com/oasis-open/cti-taxii-client/issues/50 + if url[-1] == "/": + self.url = url + else: + self.url = url + "/" def close(self): self._conn.close()
oasis-open/cti-taxii-client
1070f8f7364824d8aa62d6cf6a77a8d7bf77e5cb
diff --git a/taxii2client/test/test_client.py b/taxii2client/test/test_client.py index e363d27..db2ff84 100644 --- a/taxii2client/test/test_client.py +++ b/taxii2client/test/test_client.py @@ -960,3 +960,15 @@ def test_server_with_custom_properties(server): server.refresh() assert len(server.custom_properties) == 1 assert server.custom_properties["x_example_com"] == "some value" + + [email protected] +def test_collection_missing_trailing_slash(): + set_collection_response() + collection = Collection(COLLECTION_URL[:-1]) + responses.add(responses.GET, GET_OBJECT_URL, GET_OBJECT_RESPONSE, + status=200, content_type="%s; charset=utf-8" % MEDIA_TYPE_STIX_V20) + + response = collection.get_object("indicator--252c7c11-daf2-42bd-843b-be65edca9f61") + indicator = response["objects"][0] + assert indicator["id"] == "indicator--252c7c11-daf2-42bd-843b-be65edca9f61"
Check for trailing slash in URLs ``` >>> collection = Collection('http://localhost:5000/trustgroup1/collections/91a7b528-80eb-42ed-a74d-c6fbd5a26116', user='user1', password='Password1') >>> collection.get_object('indicator--252c7c11-daf2-42bd-843b-be65edca9f61') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/lu/Projects/cti-taxii-client/taxii2client/__init__.py", line 483, in get_object params=query_params) File "/home/lu/Projects/cti-taxii-client/taxii2client/__init__.py", line 876, in get resp.raise_for_status() File "/home/lu/.virtualenvs/cti-taxii-client/lib/python3.6/site-packages/requests/models.py", line 939, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 404 Client Error: NOT FOUND for url: http://localhost:5000/trustgroup1/collections/91a7b528-80eb-42ed-a74d-c6fbd5a26116objects/indicator--252c7c11-daf2-42bd-843b-be65edca9f61/ ``` If I set up the collection with a `/` at the end of the url, it works fine because it's not trying to find a collection called `91a7b528-80eb-42ed-a74d-c6fbd5a26116objects`.
0.0
[ "taxii2client/test/test_client.py::test_collection_missing_trailing_slash" ]
[ "taxii2client/test/test_client.py::test_server_discovery", "taxii2client/test/test_client.py::test_bad_json_response", "taxii2client/test/test_client.py::test_minimal_discovery_response", "taxii2client/test/test_client.py::test_discovery_with_no_default", "taxii2client/test/test_client.py::test_discovery_with_no_title", "taxii2client/test/test_client.py::test_api_root_no_title", "taxii2client/test/test_client.py::test_api_root_no_versions", "taxii2client/test/test_client.py::test_api_root_no_max_content_length", "taxii2client/test/test_client.py::test_api_root", "taxii2client/test/test_client.py::test_api_root_collections", "taxii2client/test/test_client.py::test_collection", "taxii2client/test/test_client.py::test_collection_unexpected_kwarg", "taxii2client/test/test_client.py::test_get_collection_objects", "taxii2client/test/test_client.py::test_get_object", "taxii2client/test/test_client.py::test_cannot_write_to_readonly_collection", "taxii2client/test/test_client.py::test_add_object_to_collection", "taxii2client/test/test_client.py::test_add_object_to_collection_dict", "taxii2client/test/test_client.py::test_add_object_to_collection_bin", "taxii2client/test/test_client.py::test_add_object_to_collection_badtype", "taxii2client/test/test_client.py::test_add_object_rases_error_when_collection_id_does_not_match_url", "taxii2client/test/test_client.py::test_cannot_read_from_writeonly_collection", "taxii2client/test/test_client.py::test_get_manifest", "taxii2client/test/test_client.py::test_get_status", "taxii2client/test/test_client.py::test_status_raw", "taxii2client/test/test_client.py::test_content_type_valid", "taxii2client/test/test_client.py::test_content_type_invalid", "taxii2client/test/test_client.py::test_url_filter_type", "taxii2client/test/test_client.py::test_filter_id", "taxii2client/test/test_client.py::test_filter_version", "taxii2client/test/test_client.py::test_filter_added_after", "taxii2client/test/test_client.py::test_filter_combo", "taxii2client/test/test_client.py::test_params_filter_unknown", "taxii2client/test/test_client.py::test_taxii_endpoint_raises_exception", "taxii2client/test/test_client.py::test_valid_content_type_for_connection", "taxii2client/test/test_client.py::test_invalid_content_type_for_connection", "taxii2client/test/test_client.py::test_status_missing_id_property", "taxii2client/test/test_client.py::test_status_missing_status_property", "taxii2client/test/test_client.py::test_status_missing_total_count_property", "taxii2client/test/test_client.py::test_status_missing_success_count_property", "taxii2client/test/test_client.py::test_status_missing_failure_count_property", "taxii2client/test/test_client.py::test_status_missing_pending_count_property", "taxii2client/test/test_client.py::test_collection_missing_id_property", "taxii2client/test/test_client.py::test_collection_missing_title_property", "taxii2client/test/test_client.py::test_collection_missing_can_read_property", "taxii2client/test/test_client.py::test_collection_missing_can_write_property", "taxii2client/test/test_client.py::test_conn_post_kwarg_errors", "taxii2client/test/test_client.py::test_user_agent_defaulting", "taxii2client/test/test_client.py::test_user_agent_overriding", "taxii2client/test/test_client.py::test_user_agent_enforcing1", "taxii2client/test/test_client.py::test_user_agent_enforcing2", "taxii2client/test/test_client.py::test_user_agent_enforcing3", "taxii2client/test/test_client.py::test_header_merging", "taxii2client/test/test_client.py::test_header_merge_none", "taxii2client/test/test_client.py::test_collection_with_custom_properties", "taxii2client/test/test_client.py::test_status_with_custom_properties", "taxii2client/test/test_client.py::test_api_roots_with_custom_properties", "taxii2client/test/test_client.py::test_server_with_custom_properties" ]
2018-11-08 17:05:50+00:00
4,321
oasis-open__cti-taxii-client-68
diff --git a/taxii2client/common.py b/taxii2client/common.py index cfd9d05..f8765d9 100644 --- a/taxii2client/common.py +++ b/taxii2client/common.py @@ -137,6 +137,15 @@ def _grab_total_items(resp): ), e) +class TokenAuth(requests.auth.AuthBase): + def __init__(self, key): + self.key = key + + def __call__(self, r): + r.headers['Authorization'] = 'Token {}'.format(self.key) + return r + + class _TAXIIEndpoint(object): """Contains some data and functionality common to all TAXII endpoint classes: a URL, connection, and ability to close the connection. It also @@ -145,7 +154,7 @@ class _TAXIIEndpoint(object): """ def __init__(self, url, conn=None, user=None, password=None, verify=True, - proxies=None, version="2.0"): + proxies=None, version="2.0", auth=None): """Create a TAXII endpoint. Args: @@ -158,13 +167,13 @@ class _TAXIIEndpoint(object): version (str): The spec version this connection is meant to follow. """ - if conn and (user or password): - raise InvalidArgumentsError("A connection and user/password may" - " not both be provided.") + if (conn and ((user or password) or auth)) or ((user or password) and auth): + raise InvalidArgumentsError("Only one of a connection, username/password, or auth object may" + " be provided.") elif conn: self._conn = conn else: - self._conn = _HTTPConnection(user, password, verify, proxies, version=version) + self._conn = _HTTPConnection(user, password, verify, proxies, version=version, auth=auth) # Add trailing slash to TAXII endpoint if missing # https://github.com/oasis-open/cti-taxii-client/issues/50 @@ -201,7 +210,7 @@ class _HTTPConnection(object): """ def __init__(self, user=None, password=None, verify=True, proxies=None, - user_agent=DEFAULT_USER_AGENT, version="2.0"): + user_agent=DEFAULT_USER_AGENT, version="2.0", auth=None): """Create a connection session. Args: @@ -219,8 +228,12 @@ class _HTTPConnection(object): self.session.verify = verify # enforce that we always have a connection-default user agent. self.user_agent = user_agent or DEFAULT_USER_AGENT + if user and password: self.session.auth = requests.auth.HTTPBasicAuth(user, password) + elif auth: + self.session.auth = auth + if proxies: self.session.proxies.update(proxies) self.version = version diff --git a/taxii2client/v20/__init__.py b/taxii2client/v20/__init__.py index 1df3a2d..f8421a8 100644 --- a/taxii2client/v20/__init__.py +++ b/taxii2client/v20/__init__.py @@ -62,7 +62,7 @@ class Status(_TAXIIEndpoint): # aren't other endpoints to call on the Status object. def __init__(self, url, conn=None, user=None, password=None, verify=True, - proxies=None, status_info=None): + proxies=None, status_info=None, auth=None): """Create an API root resource endpoint. Args: @@ -79,7 +79,7 @@ class Status(_TAXIIEndpoint): (optional) """ - super(Status, self).__init__(url, conn, user, password, verify, proxies) + super(Status, self).__init__(url, conn, user, password, verify, proxies, auth=auth) self.__raw = None if status_info: self._populate_fields(**status_info) @@ -223,7 +223,7 @@ class Collection(_TAXIIEndpoint): """ def __init__(self, url, conn=None, user=None, password=None, verify=True, - proxies=None, collection_info=None): + proxies=None, collection_info=None, auth=None): """ Initialize a new Collection. Either user/password or conn may be given, but not both. The latter is intended for internal use, when @@ -247,7 +247,7 @@ class Collection(_TAXIIEndpoint): """ - super(Collection, self).__init__(url, conn, user, password, verify, proxies) + super(Collection, self).__init__(url, conn, user, password, verify, proxies, auth=auth) self._loaded = False self.__raw = None @@ -496,7 +496,7 @@ class ApiRoot(_TAXIIEndpoint): """ def __init__(self, url, conn=None, user=None, password=None, verify=True, - proxies=None): + proxies=None, auth=None): """Create an API root resource endpoint. Args: @@ -510,7 +510,7 @@ class ApiRoot(_TAXIIEndpoint): (optional) """ - super(ApiRoot, self).__init__(url, conn, user, password, verify, proxies) + super(ApiRoot, self).__init__(url, conn, user, password, verify, proxies, auth=auth) self._loaded_collections = False self._loaded_information = False @@ -639,7 +639,7 @@ class Server(_TAXIIEndpoint): """ def __init__(self, url, conn=None, user=None, password=None, verify=True, - proxies=None): + proxies=None, auth=None): """Create a server discovery endpoint. Args: @@ -653,7 +653,7 @@ class Server(_TAXIIEndpoint): (optional) """ - super(Server, self).__init__(url, conn, user, password, verify, proxies) + super(Server, self).__init__(url, conn, user, password, verify, proxies, auth=auth) self._user = user self._password = password @@ -661,6 +661,7 @@ class Server(_TAXIIEndpoint): self._proxies = proxies self._loaded = False self.__raw = None + self._auth = auth @property def title(self): @@ -719,7 +720,8 @@ class Server(_TAXIIEndpoint): user=self._user, password=self._password, verify=self._verify, - proxies=self._proxies) + proxies=self._proxies, + auth=self._auth) for url in roots] # If 'default' is one of the existing API Roots, reuse that object # rather than creating a duplicate. The TAXII 2.0 spec says that the diff --git a/taxii2client/v21/__init__.py b/taxii2client/v21/__init__.py index 0be971b..ccc1d7a 100644 --- a/taxii2client/v21/__init__.py +++ b/taxii2client/v21/__init__.py @@ -26,7 +26,7 @@ class Status(_TAXIIEndpoint): # aren't other endpoints to call on the Status object. def __init__(self, url, conn=None, user=None, password=None, verify=True, - proxies=None, status_info=None): + proxies=None, status_info=None, auth=None): """Create an API root resource endpoint. Args: @@ -43,7 +43,7 @@ class Status(_TAXIIEndpoint): (optional) """ - super(Status, self).__init__(url, conn, user, password, verify, proxies, "2.1") + super(Status, self).__init__(url, conn, user, password, verify, proxies, "2.1", auth=auth) self.__raw = None if status_info: self._populate_fields(**status_info) @@ -186,7 +186,7 @@ class Collection(_TAXIIEndpoint): """ def __init__(self, url, conn=None, user=None, password=None, verify=True, - proxies=None, collection_info=None): + proxies=None, collection_info=None, auth=None): """ Initialize a new Collection. Either user/password or conn may be given, but not both. The latter is intended for internal use, when @@ -210,7 +210,7 @@ class Collection(_TAXIIEndpoint): """ - super(Collection, self).__init__(url, conn, user, password, verify, proxies, "2.1") + super(Collection, self).__init__(url, conn, user, password, verify, proxies, "2.1", auth=auth) self._loaded = False self.__raw = None @@ -461,7 +461,7 @@ class ApiRoot(_TAXIIEndpoint): """ def __init__(self, url, conn=None, user=None, password=None, verify=True, - proxies=None): + proxies=None, auth=None): """Create an API root resource endpoint. Args: @@ -475,7 +475,7 @@ class ApiRoot(_TAXIIEndpoint): (optional) """ - super(ApiRoot, self).__init__(url, conn, user, password, verify, proxies, "2.1") + super(ApiRoot, self).__init__(url, conn, user, password, verify, proxies, "2.1", auth=auth) self._loaded_collections = False self._loaded_information = False @@ -604,7 +604,7 @@ class Server(_TAXIIEndpoint): """ def __init__(self, url, conn=None, user=None, password=None, verify=True, - proxies=None): + proxies=None, auth=None): """Create a server discovery endpoint. Args: @@ -618,7 +618,7 @@ class Server(_TAXIIEndpoint): (optional) """ - super(Server, self).__init__(url, conn, user, password, verify, proxies, "2.1") + super(Server, self).__init__(url, conn, user, password, verify, proxies, "2.1", auth=auth) self._user = user self._password = password @@ -626,6 +626,7 @@ class Server(_TAXIIEndpoint): self._proxies = proxies self._loaded = False self.__raw = None + self._auth = auth @property def title(self): @@ -685,7 +686,8 @@ class Server(_TAXIIEndpoint): user=self._user, password=self._password, verify=self._verify, - proxies=self._proxies) + proxies=self._proxies, + auth=self._auth) for url in roots ] # If 'default' is one of the existing API Roots, reuse that object
oasis-open/cti-taxii-client
0a897aeac01969c681432269a7aed6f0693e4f5f
diff --git a/taxii2client/test/test_client_v20.py b/taxii2client/test/test_client_v20.py index c37d286..971a2bb 100644 --- a/taxii2client/test/test_client_v20.py +++ b/taxii2client/test/test_client_v20.py @@ -9,7 +9,7 @@ from taxii2client import ( DEFAULT_USER_AGENT, MEDIA_TYPE_STIX_V20, MEDIA_TYPE_TAXII_V20 ) from taxii2client.common import ( - _filter_kwargs_to_query_params, _HTTPConnection, _TAXIIEndpoint + TokenAuth, _filter_kwargs_to_query_params, _HTTPConnection, _TAXIIEndpoint ) from taxii2client.exceptions import ( AccessError, InvalidArgumentsError, InvalidJSONError, @@ -714,11 +714,28 @@ def test_params_filter_unknown(): def test_taxii_endpoint_raises_exception(): """Test exception is raised when conn and (user or pass) is provided""" conn = _HTTPConnection(user="foo", password="bar", verify=False) + error_str = "Only one of a connection, username/password, or auth object may be provided." + fake_url = "https://example.com/api1/collections/" with pytest.raises(InvalidArgumentsError) as excinfo: - _TAXIIEndpoint("https://example.com/api1/collections/", conn, "other", "test") + _TAXIIEndpoint(fake_url, conn, "other", "test") - assert "A connection and user/password may not both be provided." in str(excinfo.value) + assert error_str in str(excinfo.value) + + with pytest.raises(InvalidArgumentsError) as excinfo: + _TAXIIEndpoint(fake_url, conn, auth=TokenAuth('abcd')) + + assert error_str in str(excinfo.value) + + with pytest.raises(InvalidArgumentsError) as excinfo: + _TAXIIEndpoint(fake_url, user="other", password="test", auth=TokenAuth('abcd')) + + assert error_str in str(excinfo.value) + + with pytest.raises(InvalidArgumentsError) as excinfo: + _TAXIIEndpoint(fake_url, conn, "other", "test", auth=TokenAuth('abcd')) + + assert error_str in str(excinfo.value) @responses.activate diff --git a/taxii2client/test/test_client_v21.py b/taxii2client/test/test_client_v21.py index b61df81..ff1e28e 100644 --- a/taxii2client/test/test_client_v21.py +++ b/taxii2client/test/test_client_v21.py @@ -7,7 +7,7 @@ import six from taxii2client import DEFAULT_USER_AGENT, MEDIA_TYPE_TAXII_V21 from taxii2client.common import ( - _filter_kwargs_to_query_params, _HTTPConnection, _TAXIIEndpoint + TokenAuth, _filter_kwargs_to_query_params, _HTTPConnection, _TAXIIEndpoint ) from taxii2client.exceptions import ( AccessError, InvalidArgumentsError, InvalidJSONError, @@ -733,11 +733,28 @@ def test_params_filter_unknown(): def test_taxii_endpoint_raises_exception(): """Test exception is raised when conn and (user or pass) is provided""" conn = _HTTPConnection(user="foo", password="bar", verify=False) + error_str = "Only one of a connection, username/password, or auth object may be provided." + fake_url = "https://example.com/api1/collections/" with pytest.raises(InvalidArgumentsError) as excinfo: - _TAXIIEndpoint("https://example.com/api1/collections/", conn, "other", "test") + _TAXIIEndpoint(fake_url, conn, "other", "test") - assert "A connection and user/password may not both be provided." in str(excinfo.value) + assert error_str in str(excinfo.value) + + with pytest.raises(InvalidArgumentsError) as excinfo: + _TAXIIEndpoint(fake_url, conn, auth=TokenAuth('abcd')) + + assert error_str in str(excinfo.value) + + with pytest.raises(InvalidArgumentsError) as excinfo: + _TAXIIEndpoint(fake_url, user="other", password="test", auth=TokenAuth('abcd')) + + assert error_str in str(excinfo.value) + + with pytest.raises(InvalidArgumentsError) as excinfo: + _TAXIIEndpoint(fake_url, conn, "other", "test", auth=TokenAuth('abcd')) + + assert error_str in str(excinfo.value) @responses.activate
Question - why does the taxii client not implementing auth using api token? I know of a few taxii servers requiring auth using api keys. Is there any plan to implement auth using this? e.g: `self.my_taxii = Server(url=self.url, verify=self.verify, proxies=self.proxies, token=self.api_key)`
0.0
[ "taxii2client/test/test_client_v20.py::test_server_discovery", "taxii2client/test/test_client_v20.py::test_bad_json_response", "taxii2client/test/test_client_v20.py::test_minimal_discovery_response", "taxii2client/test/test_client_v20.py::test_discovery_with_no_default", "taxii2client/test/test_client_v20.py::test_discovery_with_no_title", "taxii2client/test/test_client_v20.py::test_api_root_no_title", "taxii2client/test/test_client_v20.py::test_api_root_no_versions", "taxii2client/test/test_client_v20.py::test_api_root_no_max_content_length", "taxii2client/test/test_client_v20.py::test_api_root", "taxii2client/test/test_client_v20.py::test_api_root_collections", "taxii2client/test/test_client_v20.py::test_collection", "taxii2client/test/test_client_v20.py::test_collection_unexpected_kwarg", "taxii2client/test/test_client_v20.py::test_get_collection_objects", "taxii2client/test/test_client_v20.py::test_get_object", "taxii2client/test/test_client_v20.py::test_cannot_write_to_readonly_collection", "taxii2client/test/test_client_v20.py::test_add_object_to_collection", "taxii2client/test/test_client_v20.py::test_add_object_to_collection_dict", "taxii2client/test/test_client_v20.py::test_add_object_to_collection_bin", "taxii2client/test/test_client_v20.py::test_add_object_to_collection_badtype", "taxii2client/test/test_client_v20.py::test_add_object_rases_error_when_collection_id_does_not_match_url", "taxii2client/test/test_client_v20.py::test_cannot_read_from_writeonly_collection", "taxii2client/test/test_client_v20.py::test_get_manifest", "taxii2client/test/test_client_v20.py::test_get_status", "taxii2client/test/test_client_v20.py::test_status_raw", "taxii2client/test/test_client_v20.py::test_content_type_valid", "taxii2client/test/test_client_v20.py::test_content_type_invalid", "taxii2client/test/test_client_v20.py::test_url_filter_type", "taxii2client/test/test_client_v20.py::test_filter_id", "taxii2client/test/test_client_v20.py::test_filter_version", "taxii2client/test/test_client_v20.py::test_filter_added_after", "taxii2client/test/test_client_v20.py::test_filter_combo", "taxii2client/test/test_client_v20.py::test_params_filter_unknown", "taxii2client/test/test_client_v20.py::test_taxii_endpoint_raises_exception", "taxii2client/test/test_client_v20.py::test_valid_content_type_for_connection", "taxii2client/test/test_client_v20.py::test_invalid_content_type_for_connection", "taxii2client/test/test_client_v20.py::test_status_missing_id_property", "taxii2client/test/test_client_v20.py::test_status_missing_status_property", "taxii2client/test/test_client_v20.py::test_status_missing_total_count_property", "taxii2client/test/test_client_v20.py::test_status_missing_success_count_property", "taxii2client/test/test_client_v20.py::test_status_missing_failure_count_property", "taxii2client/test/test_client_v20.py::test_status_missing_pending_count_property", "taxii2client/test/test_client_v20.py::test_collection_missing_id_property", "taxii2client/test/test_client_v20.py::test_collection_missing_title_property", "taxii2client/test/test_client_v20.py::test_collection_missing_can_read_property", "taxii2client/test/test_client_v20.py::test_collection_missing_can_write_property", "taxii2client/test/test_client_v20.py::test_conn_post_kwarg_errors", "taxii2client/test/test_client_v20.py::test_user_agent_defaulting", "taxii2client/test/test_client_v20.py::test_user_agent_overriding", "taxii2client/test/test_client_v20.py::test_user_agent_enforcing1", "taxii2client/test/test_client_v20.py::test_user_agent_enforcing2", "taxii2client/test/test_client_v20.py::test_user_agent_enforcing3", "taxii2client/test/test_client_v20.py::test_header_merging", "taxii2client/test/test_client_v20.py::test_header_merge_none", "taxii2client/test/test_client_v20.py::test_collection_with_custom_properties", "taxii2client/test/test_client_v20.py::test_status_with_custom_properties", "taxii2client/test/test_client_v20.py::test_api_roots_with_custom_properties", "taxii2client/test/test_client_v20.py::test_server_with_custom_properties", "taxii2client/test/test_client_v20.py::test_collection_missing_trailing_slash", "taxii2client/test/test_client_v21.py::test_server_discovery", "taxii2client/test/test_client_v21.py::test_bad_json_response", "taxii2client/test/test_client_v21.py::test_minimal_discovery_response", "taxii2client/test/test_client_v21.py::test_discovery_with_no_default", "taxii2client/test/test_client_v21.py::test_discovery_with_no_title", "taxii2client/test/test_client_v21.py::test_api_root_no_title", "taxii2client/test/test_client_v21.py::test_api_root_no_versions", "taxii2client/test/test_client_v21.py::test_api_root_no_max_content_length", "taxii2client/test/test_client_v21.py::test_api_root", "taxii2client/test/test_client_v21.py::test_api_root_collections", "taxii2client/test/test_client_v21.py::test_collection", "taxii2client/test/test_client_v21.py::test_collection_unexpected_kwarg", "taxii2client/test/test_client_v21.py::test_get_collection_objects", "taxii2client/test/test_client_v21.py::test_get_object", "taxii2client/test/test_client_v21.py::test_cannot_write_to_readonly_collection", "taxii2client/test/test_client_v21.py::test_add_object_to_collection", "taxii2client/test/test_client_v21.py::test_add_object_to_collection_dict", "taxii2client/test/test_client_v21.py::test_add_object_to_collection_bin", "taxii2client/test/test_client_v21.py::test_add_object_to_collection_badtype", "taxii2client/test/test_client_v21.py::test_add_object_rases_error_when_collection_id_does_not_match_url", "taxii2client/test/test_client_v21.py::test_cannot_read_from_writeonly_collection", "taxii2client/test/test_client_v21.py::test_get_manifest", "taxii2client/test/test_client_v21.py::test_get_status", "taxii2client/test/test_client_v21.py::test_status_raw", "taxii2client/test/test_client_v21.py::test_content_type_valid", "taxii2client/test/test_client_v21.py::test_content_type_invalid", "taxii2client/test/test_client_v21.py::test_url_filter_type", "taxii2client/test/test_client_v21.py::test_filter_id", "taxii2client/test/test_client_v21.py::test_filter_version", "taxii2client/test/test_client_v21.py::test_filter_added_after", "taxii2client/test/test_client_v21.py::test_filter_combo", "taxii2client/test/test_client_v21.py::test_params_filter_unknown", "taxii2client/test/test_client_v21.py::test_taxii_endpoint_raises_exception", "taxii2client/test/test_client_v21.py::test_valid_content_type_for_connection", "taxii2client/test/test_client_v21.py::test_invalid_content_type_for_connection", "taxii2client/test/test_client_v21.py::test_status_missing_id_property", "taxii2client/test/test_client_v21.py::test_status_missing_status_property", "taxii2client/test/test_client_v21.py::test_status_missing_total_count_property", "taxii2client/test/test_client_v21.py::test_status_missing_success_count_property", "taxii2client/test/test_client_v21.py::test_status_missing_failure_count_property", "taxii2client/test/test_client_v21.py::test_status_missing_pending_count_property", "taxii2client/test/test_client_v21.py::test_collection_missing_id_property", "taxii2client/test/test_client_v21.py::test_collection_missing_title_property", "taxii2client/test/test_client_v21.py::test_collection_missing_can_read_property", "taxii2client/test/test_client_v21.py::test_collection_missing_can_write_property", "taxii2client/test/test_client_v21.py::test_conn_post_kwarg_errors", "taxii2client/test/test_client_v21.py::test_user_agent_defaulting", "taxii2client/test/test_client_v21.py::test_user_agent_overriding", "taxii2client/test/test_client_v21.py::test_user_agent_enforcing1", "taxii2client/test/test_client_v21.py::test_user_agent_enforcing2", "taxii2client/test/test_client_v21.py::test_user_agent_enforcing3", "taxii2client/test/test_client_v21.py::test_header_merging", "taxii2client/test/test_client_v21.py::test_header_merge_none", "taxii2client/test/test_client_v21.py::test_collection_with_custom_properties", "taxii2client/test/test_client_v21.py::test_status_with_custom_properties", "taxii2client/test/test_client_v21.py::test_api_roots_with_custom_properties", "taxii2client/test/test_client_v21.py::test_server_with_custom_properties", "taxii2client/test/test_client_v21.py::test_collection_missing_trailing_slash" ]
[]
2020-05-19 20:36:25+00:00
4,322
oasis-open__cti-taxii-server-44
diff --git a/medallion/backends/memory_backend.py b/medallion/backends/memory_backend.py index 8da67b0..b07ae14 100644 --- a/medallion/backends/memory_backend.py +++ b/medallion/backends/memory_backend.py @@ -163,22 +163,23 @@ class MemoryBackend(Backend): try: for new_obj in objs["objects"]: id_and_version_already_present = False - if new_obj["id"] in collection["objects"]: - current_obj = collection["objects"][new_obj["id"]] - if "modified" in new_obj: - if new_obj["modified"] == current_obj["modified"]: + for obj in collection["objects"]: + id_and_version_already_present = False + + if new_obj['id'] == obj['id']: + if "modified" in new_obj: + if new_obj["modified"] == obj["modified"]: + id_and_version_already_present = True + else: + # There is no modified field, so this object is immutable id_and_version_already_present = True - else: - # There is no modified field, so this object is immutable - id_and_version_already_present = True if not id_and_version_already_present: collection["objects"].append(new_obj) self._update_manifest(new_obj, api_root, collection["id"]) successes.append(new_obj["id"]) succeeded += 1 else: - failures.append({"id": new_obj["id"], - "message": "Unable to process object"}) + failures.append({"id": new_obj["id"], "message": "Unable to process object"}) failed += 1 except Exception as e: raise ProcessingError("While processing supplied content, an error occured", e)
oasis-open/cti-taxii-server
c99f8dcd93ad5f06174fc2767771acd491bedaaa
diff --git a/medallion/test/test_memory_backend.py b/medallion/test/test_memory_backend.py index a23b9f1..7c9f982 100644 --- a/medallion/test/test_memory_backend.py +++ b/medallion/test/test_memory_backend.py @@ -207,6 +207,54 @@ class TestTAXIIServerWithMemoryBackend(unittest.TestCase): assert manifests["objects"][0]["id"] == new_id # ------------- BEGIN: end manifest section ------------- # + def test_add_existing_objects(self): + new_bundle = copy.deepcopy(API_OBJECTS_2) + new_id = "indicator--%s" % uuid.uuid4() + new_bundle["objects"][0]["id"] = new_id + + # ------------- BEGIN: add object section ------------- # + + post_header = copy.deepcopy(self.auth) + post_header["Content-Type"] = MEDIA_TYPE_STIX_V20 + post_header["Accept"] = MEDIA_TYPE_TAXII_V20 + + r_post = self.client.post( + test.ADD_OBJECTS_EP, + data=json.dumps(new_bundle), + headers=post_header + ) + self.assertEqual(r_post.status_code, 202) + self.assertEqual(r_post.content_type, MEDIA_TYPE_TAXII_V20) + + # ------------- END: add object section ------------- # + # ------------- BEGIN: add object again section ------------- # + + r_post = self.client.post( + test.ADD_OBJECTS_EP, + data=json.dumps(new_bundle), + headers=post_header + ) + status_response2 = self.load_json_response(r_post.data) + self.assertEqual(r_post.status_code, 202) + self.assertEqual(status_response2["success_count"], 0) + self.assertEqual(status_response2["failures"][0]["message"], + "Unable to process object") + + # ------------- END: add object again section ------------- # + # ------------- BEGIN: get object section ------------- # + + get_header = copy.deepcopy(self.auth) + get_header["Accept"] = MEDIA_TYPE_STIX_V20 + + r_get = self.client.get( + test.GET_OBJECTS_EP + "?match[id]=%s" % new_id, + headers=get_header + ) + self.assertEqual(r_get.status_code, 200) + objs = self.load_json_response(r_get.data) + self.assertEqual(len(objs["objects"]), 1) + self.assertEqual(objs["objects"][0]["id"], new_id) + def test_client_object_versioning(self): new_id = "indicator--%s" % uuid.uuid4() new_bundle = copy.deepcopy(API_OBJECTS_2)
BUG: checking new object IDs as existing already always fail https://github.com/oasis-open/cti-taxii-server/blob/f6398926d866989201e754dca0fec1e1a041acdf/medallion/backends/memory_backend.py#L166 This line will always fail, you're checking that the ID of the object belongs in the array of objects instead of checking if the ID of the object exists as the ID of _any_ of the objects
0.0
[ "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_add_existing_objects" ]
[]
2018-10-04 01:26:04+00:00
4,323
oauthlib__oauthlib-505
diff --git a/README.rst b/README.rst index eb85ffa..656d72c 100644 --- a/README.rst +++ b/README.rst @@ -56,6 +56,7 @@ The following packages provide OAuth support using OAuthLib. - For Django there is `django-oauth-toolkit`_, which includes `Django REST framework`_ support. - For Flask there is `flask-oauthlib`_ and `Flask-Dance`_. - For Pyramid there is `pyramid-oauthlib`_. +- For Bottle there is `bottle-oauthlib`_. If you have written an OAuthLib package that supports your favorite framework, please open a Pull Request, updating the documentation. @@ -65,6 +66,7 @@ please open a Pull Request, updating the documentation. .. _`Django REST framework`: http://django-rest-framework.org .. _`Flask-Dance`: https://github.com/singingwolfboy/flask-dance .. _`pyramid-oauthlib`: https://github.com/tilgovi/pyramid-oauthlib +.. _`bottle-oauthlib`: https://github.com/thomsonreuters/bottle-oauthlib Using OAuthLib? Please get in touch! ------------------------------------ diff --git a/docs/faq.rst b/docs/faq.rst index 4d896f5..0c61af9 100644 --- a/docs/faq.rst +++ b/docs/faq.rst @@ -65,10 +65,17 @@ How do I use OAuthLib with Google, Twitter and other providers? How do I use OAuthlib as a provider with Django, Flask and other web frameworks? -------------------------------------------------------------------------------- - Providers using Django should seek out `django-oauth-toolkit`_ - and those using Flask `flask-oauthlib`_. For other frameworks, - please get in touch by opening a `GitHub issue`_, on `G+`_ or - on IRC #oauthlib irc.freenode.net. + Providers can be implemented in any web frameworks. However, some of + them have ready-to-use libraries to help integration: + - Django `django-oauth-toolkit`_ + - Flask `flask-oauthlib`_ + - Pyramid `pyramid-oauthlib`_ + - Bottle `bottle-oauthlib`_ + + For other frameworks, please get in touch by opening a `GitHub issue`_, on `G+`_ or + on IRC #oauthlib irc.freenode.net. If you have written an OAuthLib package that + supports your favorite framework, please open a Pull Request to update the docs. + What is the difference between authentication and authorization? ---------------------------------------------------------------- @@ -91,6 +98,8 @@ Some argue OAuth 2 is worse than 1, is that true? .. _`requests-oauthlib`: https://github.com/requests/requests-oauthlib .. _`django-oauth-toolkit`: https://github.com/evonove/django-oauth-toolkit .. _`flask-oauthlib`: https://github.com/lepture/flask-oauthlib +.. _`pyramid-oauthlib`: https://github.com/tilgovi/pyramid-oauthlib +.. _`bottle-oauthlib`: https://github.com/thomsonreuters/bottle-oauthlib .. _`GitHub issue`: https://github.com/idan/oauthlib/issues/new .. _`G+`: https://plus.google.com/communities/101889017375384052571 .. _`difference`: http://www.cyberciti.biz/faq/authentication-vs-authorization/ diff --git a/docs/oauth2/endpoints/endpoints.rst b/docs/oauth2/endpoints/endpoints.rst index 0e70798..9bd1c4e 100644 --- a/docs/oauth2/endpoints/endpoints.rst +++ b/docs/oauth2/endpoints/endpoints.rst @@ -23,7 +23,7 @@ handles user authorization, the token endpoint which provides tokens and the resource endpoint which provides access to protected resources. It is to the endpoints you will feed requests and get back an almost complete response. This process is simplified for you using a decorator such as the django one described -later. +later (but it's applicable to all other web frameworks librairies). The main purpose of the endpoint in OAuthLib is to figure out which grant type or token to dispatch the request to. diff --git a/docs/oauth2/server.rst b/docs/oauth2/server.rst index 9d6b502..9900e36 100644 --- a/docs/oauth2/server.rst +++ b/docs/oauth2/server.rst @@ -6,8 +6,10 @@ OAuthLib is a dependency free library that may be used with any web framework. That said, there are framework specific helper libraries to make your life easier. -- For Django there is `django-oauth-toolkit`_. -- For Flask there is `flask-oauthlib`_. +- Django `django-oauth-toolkit`_ +- Flask `flask-oauthlib`_ +- Pyramid `pyramid-oauthlib`_ +- Bottle `bottle-oauthlib`_ If there is no support for your favourite framework and you are interested in providing it then you have come to the right place. OAuthLib can handle @@ -17,6 +19,8 @@ as well as provide an interface for a backend to store tokens, clients, etc. .. _`django-oauth-toolkit`: https://github.com/evonove/django-oauth-toolkit .. _`flask-oauthlib`: https://github.com/lepture/flask-oauthlib +.. _`pyramid-oauthlib`: https://github.com/tilgovi/pyramid-oauthlib +.. _`bottle-oauthlib`: https://github.com/thomsonreuters/bottle-oauthlib .. contents:: Tutorial Contents :depth: 3 diff --git a/oauthlib/oauth2/rfc6749/clients/web_application.py b/oauthlib/oauth2/rfc6749/clients/web_application.py index c099d99..bc62c8f 100644 --- a/oauthlib/oauth2/rfc6749/clients/web_application.py +++ b/oauthlib/oauth2/rfc6749/clients/web_application.py @@ -125,7 +125,7 @@ class WebApplicationClient(Client): """ code = code or self.code return prepare_token_request('authorization_code', code=code, body=body, - client_id=self.client_id, redirect_uri=redirect_uri, **kwargs) + client_id=client_id, redirect_uri=redirect_uri, **kwargs) def parse_request_uri_response(self, uri, state=None): """Parse the URI query for code and state.
oauthlib/oauthlib
cfb82feb03fcd60b3b66ac09bf1b478cd5f11b7d
diff --git a/tests/oauth2/rfc6749/clients/test_web_application.py b/tests/oauth2/rfc6749/clients/test_web_application.py index 85b247d..0a80c9a 100644 --- a/tests/oauth2/rfc6749/clients/test_web_application.py +++ b/tests/oauth2/rfc6749/clients/test_web_application.py @@ -38,7 +38,7 @@ class WebApplicationClientTest(TestCase): code = "zzzzaaaa" body = "not=empty" - body_code = "not=empty&grant_type=authorization_code&code=%s&client_id=%s" % (code, client_id) + body_code = "not=empty&grant_type=authorization_code&code=%s" % code body_redirect = body_code + "&redirect_uri=http%3A%2F%2Fmy.page.com%2Fcallback" body_kwargs = body_code + "&some=providers&require=extra+arguments"
Client id always included in body of token request I use the WebApplication client and in [`prepare_request_body`](https://github.com/idan/oauthlib/blob/master/oauthlib/oauth2/rfc6749/clients/web_application.py#L88-L89) I noticed the `client_id` parameter is never used. However [`self.client_id`](https://github.com/idan/oauthlib/blob/master/oauthlib/oauth2/rfc6749/clients/web_application.py#L127-L128) is always passed down to `prepare_token_request` and thus always included in the body. An unused parameter doesn't look good but maybe this is intended, I've only quickly read the RFC 6749. If this is the case it should at least be stated in the docstring. The server here (I guess OpenAM) rejects queries when they contain the client_id in the body.
0.0
[ "tests/oauth2/rfc6749/clients/test_web_application.py::WebApplicationClientTest::test_request_body" ]
[ "tests/oauth2/rfc6749/clients/test_web_application.py::WebApplicationClientTest::test_parse_token_response", "tests/oauth2/rfc6749/clients/test_web_application.py::WebApplicationClientTest::test_auth_grant_uri", "tests/oauth2/rfc6749/clients/test_web_application.py::WebApplicationClientTest::test_prepare_authorization_requeset", "tests/oauth2/rfc6749/clients/test_web_application.py::WebApplicationClientTest::test_parse_grant_uri_response" ]
2017-11-28 13:04:47+00:00
4,324
oauthlib__oauthlib-675
diff --git a/oauthlib/oauth2/rfc6749/parameters.py b/oauthlib/oauth2/rfc6749/parameters.py index df724ee..14d4c0d 100644 --- a/oauthlib/oauth2/rfc6749/parameters.py +++ b/oauthlib/oauth2/rfc6749/parameters.py @@ -422,7 +422,10 @@ def parse_token_response(body, scope=None): params['scope'] = scope_to_list(params['scope']) if 'expires_in' in params: - params['expires_at'] = time.time() + int(params['expires_in']) + if params['expires_in'] is None: + params.pop('expires_in') + else: + params['expires_at'] = time.time() + int(params['expires_in']) params = OAuth2Token(params, old_scope=scope) validate_token_parameters(params)
oauthlib/oauthlib
a44e080f64a216f1fc8f155c945ac9a6ff993dd0
diff --git a/tests/oauth2/rfc6749/test_parameters.py b/tests/oauth2/rfc6749/test_parameters.py index 0d293cc..48b7eac 100644 --- a/tests/oauth2/rfc6749/test_parameters.py +++ b/tests/oauth2/rfc6749/test_parameters.py @@ -103,6 +103,15 @@ class ParameterTests(TestCase): ' "expires_in": 3600,' ' "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",' ' "example_parameter": "example_value" }') + json_response_noexpire = ('{ "access_token": "2YotnFZFEjr1zCsicMWpAA",' + ' "token_type": "example",' + ' "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",' + ' "example_parameter": "example_value"}') + json_response_expirenull = ('{ "access_token": "2YotnFZFEjr1zCsicMWpAA",' + ' "token_type": "example",' + ' "expires_in": null,' + ' "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",' + ' "example_parameter": "example_value"}') json_custom_error = '{ "error": "incorrect_client_credentials" }' json_error = '{ "error": "access_denied" }' @@ -136,6 +145,13 @@ class ParameterTests(TestCase): 'example_parameter': 'example_value' } + json_noexpire_dict = { + 'access_token': '2YotnFZFEjr1zCsicMWpAA', + 'token_type': 'example', + 'refresh_token': 'tGzv3JOkF0XG5Qx2TlKWIA', + 'example_parameter': 'example_value' + } + json_notype_dict = { 'access_token': '2YotnFZFEjr1zCsicMWpAA', 'expires_in': 3600, @@ -212,6 +228,8 @@ class ParameterTests(TestCase): self.assertEqual(parse_token_response(self.json_response_noscope, scope=['all', 'the', 'scopes']), self.json_noscope_dict) + self.assertEqual(parse_token_response(self.json_response_noexpire), self.json_noexpire_dict) + self.assertEqual(parse_token_response(self.json_response_expirenull), self.json_noexpire_dict) scope_changes_recorded = [] def record_scope_change(sender, message, old, new):
Null value in expires_in field not handled correctly **Describe the bug** Some OAuth-based services have been discovered to include the `expires_in` field, but set it to `null`. This issue was discovered on our end attempting to authenticate to SurveyMonkey's API. The `oauthlib` library does not handle this case correctly, and will throw an error if it encounters this. **How to reproduce** 1. Create an account with SurveyMonkey 1. Create a sample app to test against 1. Attempt to authenticate using OAuth flow against the sample app 1. Receive the following error: `int() argument must be a string, a bytes-like object or a number, not 'NoneType'` **Expected behavior** Ignore the null `expires_in` field, and continue without throwing an error. **Additional context** The following is an example of a returned payload (access_token hidden for security purposes): `{"access_token":".g.w2***kjP","token_type":"bearer","access_url":"https:\/\/api.surveymonkey.com","expires_in":null}` The following is the stacktrace we receive: ``` Traceback (most recent call last): File "/code/ac_auth/views.py", line 59, in dispatch return super().dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 495, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 455, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 492, in dispatch response = handler(request, *args, **kwargs) File "/code/ac_auth/views.py", line 158, in get request.get_raw_uri(), File "/code/ac_auth/oauth_service.py", line 46, in fetch_access_token timeout=CONNECTION_TIMEOUT, File "/usr/local/lib/python3.7/site-packages/requests_oauthlib/oauth2_session.py", line 307, in fetch_token self._client.parse_request_body_response(r.text, scope=self.scope) File "/usr/local/lib/python3.7/site-packages/oauthlib/oauth2/rfc6749/clients/base.py", line 415, in parse_request_body_response self.token = parse_token_response(body, scope=scope) File "/usr/local/lib/python3.7/site-packages/oauthlib/oauth2/rfc6749/parameters.py", line 422, in parse_token_response params['expires_at'] = time.time() + int(params['expires_in']) TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' ``` We are using `oauthlib` 3.0.1 from pip. - Are you using OAuth1, OAuth2 or OIDC? **OAuth2** - Are you writing client or server side code? **Server-side** - If client, what provider are you connecting to? **N/A** - Are you using a downstream library, such as `requests-oauthlib`, `django-oauth-toolkit`, ...? **requests-oauthlib**
0.0
[ "tests/oauth2/rfc6749/test_parameters.py::ParameterTests::test_json_token_response" ]
[ "tests/oauth2/rfc6749/test_parameters.py::ParameterTests::test_prepare_grant_uri", "tests/oauth2/rfc6749/test_parameters.py::ParameterTests::test_json_token_notype", "tests/oauth2/rfc6749/test_parameters.py::ParameterTests::test_prepare_token_request", "tests/oauth2/rfc6749/test_parameters.py::ParameterTests::test_url_encoded_token_response", "tests/oauth2/rfc6749/test_parameters.py::ParameterTests::test_implicit_token_response", "tests/oauth2/rfc6749/test_parameters.py::ParameterTests::test_grant_response", "tests/oauth2/rfc6749/test_parameters.py::ParameterTests::test_custom_json_error" ]
2019-04-30 16:52:07+00:00
4,325
oauthlib__oauthlib-680
diff --git a/oauthlib/oauth2/rfc6749/parameters.py b/oauthlib/oauth2/rfc6749/parameters.py index 6b9d630..df724ee 100644 --- a/oauthlib/oauth2/rfc6749/parameters.py +++ b/oauthlib/oauth2/rfc6749/parameters.py @@ -264,12 +264,15 @@ def parse_authorization_code_response(uri, state=None): query = urlparse.urlparse(uri).query params = dict(urlparse.parse_qsl(query)) - if not 'code' in params: - raise MissingCodeError("Missing code parameter in response.") - if state and params.get('state', None) != state: raise MismatchingStateError() + if 'error' in params: + raise_from_error(params.get('error'), params) + + if not 'code' in params: + raise MissingCodeError("Missing code parameter in response.") + return params
oauthlib/oauthlib
d2dcb0f5bb247c9e48fa876e3c99ff3298b3a4c0
diff --git a/tests/oauth2/rfc6749/test_parameters.py b/tests/oauth2/rfc6749/test_parameters.py index c42f516..0d293cc 100644 --- a/tests/oauth2/rfc6749/test_parameters.py +++ b/tests/oauth2/rfc6749/test_parameters.py @@ -73,7 +73,8 @@ class ParameterTests(TestCase): error_nocode = 'https://client.example.com/cb?state=xyz' error_nostate = 'https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA' error_wrongstate = 'https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA&state=abc' - error_response = 'https://client.example.com/cb?error=access_denied&state=xyz' + error_denied = 'https://client.example.com/cb?error=access_denied&state=xyz' + error_invalid = 'https://client.example.com/cb?error=invalid_request&state=xyz' implicit_base = 'https://example.com/cb#access_token=2YotnFZFEjr1zCsicMWpAA&scope=abc&' implicit_response = implicit_base + 'state={0}&token_type=example&expires_in=3600'.format(state) @@ -180,8 +181,10 @@ class ParameterTests(TestCase): self.assertRaises(MissingCodeError, parse_authorization_code_response, self.error_nocode) - self.assertRaises(MissingCodeError, parse_authorization_code_response, - self.error_response) + self.assertRaises(AccessDeniedError, parse_authorization_code_response, + self.error_denied) + self.assertRaises(InvalidRequestFatalError, parse_authorization_code_response, + self.error_invalid) self.assertRaises(MismatchingStateError, parse_authorization_code_response, self.error_nostate, state=self.state) self.assertRaises(MismatchingStateError, parse_authorization_code_response,
`parse_authorization_code_response` has no error checking Over at https://github.com/gratipay/gratipay.com/issues/2870 we're finding that [`parse_authorization_code_response`](https://github.com/idan/oauthlib/blob/04631866c058defb480462db1ec13cb7f88780a9/oauthlib/oauth2/rfc6749/parameters.py#L179-L229) sometimes receives an error response that it's [not prepared to handle](https://github.com/idan/oauthlib/blob/04631866c058defb480462db1ec13cb7f88780a9/oauthlib/oauth2/rfc6749/parameters.py#L221-L223). Here's a couple examples of the querystrings we're seeing from different providers: ``` Google: error=access_denied&state=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Facebook: error=access_denied&error_code=200&error_description=Permissions+error&error_reason=user_denied&state=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ``` Should a check for `error` be added, with a call to [`raise_from_error`](https://github.com/idan/oauthlib/blob/04631866c058defb480462db1ec13cb7f88780a9/oauthlib/oauth2/rfc6749/errors.py#L249-L259) (but cf. #2869)?
0.0
[ "tests/oauth2/rfc6749/test_parameters.py::ParameterTests::test_grant_response" ]
[ "tests/oauth2/rfc6749/test_parameters.py::ParameterTests::test_json_token_notype", "tests/oauth2/rfc6749/test_parameters.py::ParameterTests::test_json_token_response", "tests/oauth2/rfc6749/test_parameters.py::ParameterTests::test_custom_json_error", "tests/oauth2/rfc6749/test_parameters.py::ParameterTests::test_url_encoded_token_response", "tests/oauth2/rfc6749/test_parameters.py::ParameterTests::test_prepare_grant_uri", "tests/oauth2/rfc6749/test_parameters.py::ParameterTests::test_implicit_token_response", "tests/oauth2/rfc6749/test_parameters.py::ParameterTests::test_prepare_token_request" ]
2019-06-06 04:16:41+00:00
4,326
oauthlib__oauthlib-752
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 79f241d..21c9159 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -7,6 +7,9 @@ OAuth2.0 Provider - Bugfixes * #753: Fix acceptance of valid IPv6 addresses in URI validation +OAuth2.0 Provider - Features + * #751: OIDC add support of refreshing ID Tokens + OAuth2.0 Client - Bugfixes * #730: Base OAuth2 Client now has a consistent way of managing the `scope`: it consistently @@ -25,6 +28,8 @@ OAuth2.0 Provider - Bugfixes * #746: OpenID Connect Hybrid - fix nonce not passed to add_id_token * #756: Different prompt values are now handled according to spec (e.g. prompt=none) * #759: OpenID Connect - fix Authorization: Basic parsing + * #751: The RefreshTokenGrant modifiers now take the same arguments as the + AuthorizationCodeGrant modifiers (`token`, `token_handler`, `request`). General * #716: improved skeleton validator for public vs private client diff --git a/docs/oauth2/oidc/refresh_token.rst b/docs/oauth2/oidc/refresh_token.rst new file mode 100644 index 0000000..01d2d7f --- /dev/null +++ b/docs/oauth2/oidc/refresh_token.rst @@ -0,0 +1,6 @@ +OpenID Authorization Code +------------------------- + +.. autoclass:: oauthlib.openid.connect.core.grant_types.RefreshTokenGrant + :members: + :inherited-members: diff --git a/oauthlib/oauth2/rfc6749/grant_types/refresh_token.py b/oauthlib/oauth2/rfc6749/grant_types/refresh_token.py index 8698a3d..f801de4 100644 --- a/oauthlib/oauth2/rfc6749/grant_types/refresh_token.py +++ b/oauthlib/oauth2/rfc6749/grant_types/refresh_token.py @@ -63,7 +63,7 @@ class RefreshTokenGrant(GrantTypeBase): refresh_token=self.issue_new_refresh_tokens) for modifier in self._token_modifiers: - token = modifier(token) + token = modifier(token, token_handler, request) self.request_validator.save_token(token, request) diff --git a/oauthlib/openid/connect/core/grant_types/__init__.py b/oauthlib/openid/connect/core/grant_types/__init__.py index 887a585..8dad5f6 100644 --- a/oauthlib/openid/connect/core/grant_types/__init__.py +++ b/oauthlib/openid/connect/core/grant_types/__init__.py @@ -10,3 +10,4 @@ from .dispatchers import ( ) from .hybrid import HybridGrant from .implicit import ImplicitGrant +from .refresh_token import RefreshTokenGrant diff --git a/oauthlib/openid/connect/core/grant_types/refresh_token.py b/oauthlib/openid/connect/core/grant_types/refresh_token.py new file mode 100644 index 0000000..43e4499 --- /dev/null +++ b/oauthlib/openid/connect/core/grant_types/refresh_token.py @@ -0,0 +1,34 @@ +""" +oauthlib.openid.connect.core.grant_types +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +""" +import logging + +from oauthlib.oauth2.rfc6749.grant_types.refresh_token import ( + RefreshTokenGrant as OAuth2RefreshTokenGrant, +) + +from .base import GrantTypeBase + +log = logging.getLogger(__name__) + + +class RefreshTokenGrant(GrantTypeBase): + + def __init__(self, request_validator=None, **kwargs): + self.proxy_target = OAuth2RefreshTokenGrant( + request_validator=request_validator, **kwargs) + self.register_token_modifier(self.add_id_token) + + def add_id_token(self, token, token_handler, request): + """ + Construct an initial version of id_token, and let the + request_validator sign or encrypt it. + + The authorization_code version of this method is used to + retrieve the nonce accordingly to the code storage. + """ + if not self.request_validator.refresh_id_token(request): + return token + + return super().add_id_token(token, token_handler, request) diff --git a/oauthlib/openid/connect/core/request_validator.py b/oauthlib/openid/connect/core/request_validator.py index e8f334b..47c4cd9 100644 --- a/oauthlib/openid/connect/core/request_validator.py +++ b/oauthlib/openid/connect/core/request_validator.py @@ -306,3 +306,15 @@ class RequestValidator(OAuth2RequestValidator): Method is used by: UserInfoEndpoint """ + + def refresh_id_token(self, request): + """Whether the id token should be refreshed. Default, True + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: True or False + + Method is used by: + RefreshTokenGrant + """ + return True
oauthlib/oauthlib
4fddf07313aed766b633a6ca400bca67980017ad
diff --git a/tests/openid/connect/core/grant_types/test_refresh_token.py b/tests/openid/connect/core/grant_types/test_refresh_token.py new file mode 100644 index 0000000..8126e1b --- /dev/null +++ b/tests/openid/connect/core/grant_types/test_refresh_token.py @@ -0,0 +1,105 @@ +import json +from unittest import mock + +from oauthlib.common import Request +from oauthlib.oauth2.rfc6749.tokens import BearerToken +from oauthlib.openid.connect.core.grant_types import RefreshTokenGrant + +from tests.oauth2.rfc6749.grant_types.test_refresh_token import ( + RefreshTokenGrantTest, +) +from tests.unittest import TestCase + + +def get_id_token_mock(token, token_handler, request): + return "MOCKED_TOKEN" + + +class OpenIDRefreshTokenInterferenceTest(RefreshTokenGrantTest): + """Test that OpenID don't interfere with normal OAuth 2 flows.""" + + def setUp(self): + super().setUp() + self.auth = RefreshTokenGrant(request_validator=self.mock_validator) + + +class OpenIDRefreshTokenTest(TestCase): + + def setUp(self): + self.request = Request('http://a.b/path') + self.request.grant_type = 'refresh_token' + self.request.refresh_token = 'lsdkfhj230' + self.request.scope = ('hello', 'openid') + self.mock_validator = mock.MagicMock() + + self.mock_validator = mock.MagicMock() + self.mock_validator.authenticate_client.side_effect = self.set_client + self.mock_validator.get_id_token.side_effect = get_id_token_mock + self.auth = RefreshTokenGrant(request_validator=self.mock_validator) + + def set_client(self, request): + request.client = mock.MagicMock() + request.client.client_id = 'mocked' + return True + + def test_refresh_id_token(self): + self.mock_validator.get_original_scopes.return_value = [ + 'hello', 'openid' + ] + bearer = BearerToken(self.mock_validator) + + headers, body, status_code = self.auth.create_token_response( + self.request, bearer + ) + + token = json.loads(body) + self.assertEqual(self.mock_validator.save_token.call_count, 1) + self.assertIn('access_token', token) + self.assertIn('refresh_token', token) + self.assertIn('id_token', token) + self.assertIn('token_type', token) + self.assertIn('expires_in', token) + self.assertEqual(token['scope'], 'hello openid') + self.mock_validator.refresh_id_token.assert_called_once_with( + self.request + ) + + def test_refresh_id_token_false(self): + self.mock_validator.refresh_id_token.return_value = False + self.mock_validator.get_original_scopes.return_value = [ + 'hello', 'openid' + ] + bearer = BearerToken(self.mock_validator) + + headers, body, status_code = self.auth.create_token_response( + self.request, bearer + ) + + token = json.loads(body) + self.assertEqual(self.mock_validator.save_token.call_count, 1) + self.assertIn('access_token', token) + self.assertIn('refresh_token', token) + self.assertIn('token_type', token) + self.assertIn('expires_in', token) + self.assertEqual(token['scope'], 'hello openid') + self.assertNotIn('id_token', token) + self.mock_validator.refresh_id_token.assert_called_once_with( + self.request + ) + + def test_refresh_token_without_openid_scope(self): + self.request.scope = "hello" + bearer = BearerToken(self.mock_validator) + + headers, body, status_code = self.auth.create_token_response( + self.request, bearer + ) + + token = json.loads(body) + self.assertEqual(self.mock_validator.save_token.call_count, 1) + self.assertIn('access_token', token) + self.assertIn('refresh_token', token) + self.assertIn('token_type', token) + self.assertIn('expires_in', token) + self.assertNotIn('id_token', token) + self.assertEqual(token['scope'], 'hello')
Refresh id tokens **Describe the feature** It is not possible with the current implementation to issue ID tokens on refresh. **Additional context** The refresh token modifiers (https://github.com/oauthlib/oauthlib/blob/master/oauthlib/oauth2/rfc6749/grant_types/refresh_token.py#L66) take only 1 argument while the authorization code modifiers take 3 (https://github.com/oauthlib/oauthlib/blob/master/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py#L308). The modifier function `add_id_token` used to add id tokens in the OIDC token response is not compatible with the refresh token's modifier interface. I see no reason to have that behavior. If there are no objections I can go ahead and create a PR that will harmonize the modifier arguments and add ID tokens to the refresh token responses for OIDC out of the box.
0.0
[ "tests/openid/connect/core/grant_types/test_refresh_token.py::RefreshTokenGrantTest::test_authenticate_client_id", "tests/openid/connect/core/grant_types/test_refresh_token.py::RefreshTokenGrantTest::test_authentication_required", "tests/openid/connect/core/grant_types/test_refresh_token.py::RefreshTokenGrantTest::test_create_token_inherit_scope", "tests/openid/connect/core/grant_types/test_refresh_token.py::RefreshTokenGrantTest::test_create_token_response", "tests/openid/connect/core/grant_types/test_refresh_token.py::RefreshTokenGrantTest::test_create_token_within_original_scope", "tests/openid/connect/core/grant_types/test_refresh_token.py::RefreshTokenGrantTest::test_custom_auth_validators_unsupported", "tests/openid/connect/core/grant_types/test_refresh_token.py::RefreshTokenGrantTest::test_custom_token_validators", "tests/openid/connect/core/grant_types/test_refresh_token.py::RefreshTokenGrantTest::test_invalid_client", "tests/openid/connect/core/grant_types/test_refresh_token.py::RefreshTokenGrantTest::test_invalid_grant_type", "tests/openid/connect/core/grant_types/test_refresh_token.py::RefreshTokenGrantTest::test_invalid_refresh_token", "tests/openid/connect/core/grant_types/test_refresh_token.py::RefreshTokenGrantTest::test_invalid_scope", "tests/openid/connect/core/grant_types/test_refresh_token.py::RefreshTokenGrantTest::test_invalid_scope_original_scopes_empty", "tests/openid/connect/core/grant_types/test_refresh_token.py::RefreshTokenGrantTest::test_invalid_token", "tests/openid/connect/core/grant_types/test_refresh_token.py::RefreshTokenGrantTest::test_valid_token_request", "tests/openid/connect/core/grant_types/test_refresh_token.py::OpenIDRefreshTokenInterferenceTest::test_authenticate_client_id", "tests/openid/connect/core/grant_types/test_refresh_token.py::OpenIDRefreshTokenInterferenceTest::test_authentication_required", "tests/openid/connect/core/grant_types/test_refresh_token.py::OpenIDRefreshTokenInterferenceTest::test_create_token_inherit_scope", "tests/openid/connect/core/grant_types/test_refresh_token.py::OpenIDRefreshTokenInterferenceTest::test_create_token_response", "tests/openid/connect/core/grant_types/test_refresh_token.py::OpenIDRefreshTokenInterferenceTest::test_create_token_within_original_scope", "tests/openid/connect/core/grant_types/test_refresh_token.py::OpenIDRefreshTokenInterferenceTest::test_custom_auth_validators_unsupported", "tests/openid/connect/core/grant_types/test_refresh_token.py::OpenIDRefreshTokenInterferenceTest::test_custom_token_validators", "tests/openid/connect/core/grant_types/test_refresh_token.py::OpenIDRefreshTokenInterferenceTest::test_invalid_client", "tests/openid/connect/core/grant_types/test_refresh_token.py::OpenIDRefreshTokenInterferenceTest::test_invalid_grant_type", "tests/openid/connect/core/grant_types/test_refresh_token.py::OpenIDRefreshTokenInterferenceTest::test_invalid_refresh_token", "tests/openid/connect/core/grant_types/test_refresh_token.py::OpenIDRefreshTokenInterferenceTest::test_invalid_scope", "tests/openid/connect/core/grant_types/test_refresh_token.py::OpenIDRefreshTokenInterferenceTest::test_invalid_scope_original_scopes_empty", "tests/openid/connect/core/grant_types/test_refresh_token.py::OpenIDRefreshTokenInterferenceTest::test_invalid_token", "tests/openid/connect/core/grant_types/test_refresh_token.py::OpenIDRefreshTokenInterferenceTest::test_valid_token_request", "tests/openid/connect/core/grant_types/test_refresh_token.py::OpenIDRefreshTokenTest::test_refresh_id_token", "tests/openid/connect/core/grant_types/test_refresh_token.py::OpenIDRefreshTokenTest::test_refresh_id_token_false", "tests/openid/connect/core/grant_types/test_refresh_token.py::OpenIDRefreshTokenTest::test_refresh_token_without_openid_scope" ]
[]
2021-03-22 14:43:45+00:00
4,327
oauthlib__oauthlib-771
diff --git a/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py b/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py index bf42d88..97aeca9 100644 --- a/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py +++ b/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py @@ -272,6 +272,8 @@ class AuthorizationCodeGrant(GrantTypeBase): grant = self.create_authorization_code(request) for modifier in self._code_modifiers: grant = modifier(grant, token_handler, request) + if 'access_token' in grant: + self.request_validator.save_token(grant, request) log.debug('Saving grant %r for %r.', grant, request) self.request_validator.save_authorization_code( request.client_id, grant, request)
oauthlib/oauthlib
555e3b06022c32e420b3bc0709c66988e91b7670
diff --git a/tests/oauth2/rfc6749/grant_types/test_authorization_code.py b/tests/oauth2/rfc6749/grant_types/test_authorization_code.py index 20a2416..dec5323 100644 --- a/tests/oauth2/rfc6749/grant_types/test_authorization_code.py +++ b/tests/oauth2/rfc6749/grant_types/test_authorization_code.py @@ -324,3 +324,18 @@ class AuthorizationCodeGrantTest(TestCase): authorization_code.code_challenge_method_s256("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk", "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM") ) + + def test_code_modifier_called(self): + bearer = BearerToken(self.mock_validator) + code_modifier = mock.MagicMock(wraps=lambda grant, *a: grant) + self.auth.register_code_modifier(code_modifier) + self.auth.create_authorization_response(self.request, bearer) + code_modifier.assert_called_once() + + def test_hybrid_token_save(self): + bearer = BearerToken(self.mock_validator) + self.auth.register_code_modifier( + lambda grant, *a: dict(list(grant.items()) + [('access_token', 1)]) + ) + self.auth.create_authorization_response(self.request, bearer) + self.mock_validator.save_token.assert_called_once()
OIDC request_type "code token" does not save access token I was experimenting with `django-oauth-toolkit` and noticed when setting a request type of `code token` the returned access token was not valid because it was not saved into the database. Looking into the issue I believe that during the hybrid flow for `code`, after the token is generated there is a missing call to `request_validator.save_token(code, request)`. That is, the following code: https://github.com/oauthlib/oauthlib/blob/d54965b86ce4ede956db70baff0b3d5e9182a007/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py#L272-L279 After `oauth2.rfc6749.grant_types.base.GrantTypeBase.add_token` is called as a modifier there is no corresponding call to `request_validator.save_token`. That is, I would have expected (based on examining the implicit flow) to see something like the following present: ```python if 'access_token' in grant: self.request_validator.save_token(grant, request) ``` Alternatively, if `save_authorization_code` is expected to make this check then this is an issue for the `django-oauth-toolkit` project. ### Version ```plaintext $ pip3 freeze | grep oauth django-oauth-toolkit==1.5.0 oauthlib==3.1.0 ```
0.0
[ "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_hybrid_token_save" ]
[ "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_authenticate_client", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_authenticate_client_id", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_authentication_required", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_client_id_missing", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_code_modifier_called", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_correct_code_challenge_method_plain", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_correct_code_challenge_method_s256", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_authorization_grant", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_authorization_grant_no_scopes", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_authorization_grant_state", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_authorization_response", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_token_response", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_token_response_without_refresh_token", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_custom_auth_validators", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_custom_token_validators", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_invalid_grant", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_invalid_grant_type", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_invalid_redirect_uri", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_invalid_request", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_invalid_request_duplicates", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_challenge_missing", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_default_method", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_optional_verifier_missing_challenge_valid", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_optional_verifier_valid_challenge_missing", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_required_verifier_invalid_challenge_valid_method_valid", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_required_verifier_missing_challenge_missing", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_required_verifier_missing_challenge_valid", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_required_verifier_valid_challenge_missing", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_required_verifier_valid_challenge_valid_method_valid", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_required_verifier_valid_challenge_valid_method_wrong", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_verifier_missing", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_verifier_valid_challenge_valid_method_missing", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_wrong_method", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_wrong_code_challenge_method_plain", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_wrong_code_challenge_method_s256" ]
2021-08-18 09:02:04+00:00
4,328
oauthlib__oauthlib-790
diff --git a/docs/installation.rst b/docs/installation.rst index 0e00e39..61428ce 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -118,7 +118,7 @@ Install from GitHub ------------------- Alternatively, install it directly from the source repository on -GitHub. This is the "bleading edge" version, but it may be useful for +GitHub. This is the "bleeding edge" version, but it may be useful for accessing bug fixes and/or new features that have not been released. Standard install diff --git a/oauthlib/oauth2/rfc6749/endpoints/metadata.py b/oauthlib/oauth2/rfc6749/endpoints/metadata.py index 81ee1de..d43a824 100644 --- a/oauthlib/oauth2/rfc6749/endpoints/metadata.py +++ b/oauthlib/oauth2/rfc6749/endpoints/metadata.py @@ -54,7 +54,8 @@ class MetadataEndpoint(BaseEndpoint): """Create metadata response """ headers = { - 'Content-Type': 'application/json' + 'Content-Type': 'application/json', + 'Access-Control-Allow-Origin': '*', } return headers, json.dumps(self.claims), 200 diff --git a/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py b/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py index 97aeca9..b799823 100644 --- a/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py +++ b/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py @@ -10,6 +10,7 @@ import logging from oauthlib import common from .. import errors +from ..utils import is_secure_transport from .base import GrantTypeBase log = logging.getLogger(__name__) @@ -312,6 +313,7 @@ class AuthorizationCodeGrant(GrantTypeBase): self.request_validator.save_token(token, request) self.request_validator.invalidate_authorization_code( request.client_id, request.code, request) + headers.update(self._create_cors_headers(request)) return headers, json.dumps(token), 200 def validate_authorization_request(self, request): @@ -545,3 +547,20 @@ class AuthorizationCodeGrant(GrantTypeBase): if challenge_method in self._code_challenge_methods: return self._code_challenge_methods[challenge_method](verifier, challenge) raise NotImplementedError('Unknown challenge_method %s' % challenge_method) + + def _create_cors_headers(self, request): + """If CORS is allowed, create the appropriate headers.""" + if 'origin' not in request.headers: + return {} + + origin = request.headers['origin'] + if not is_secure_transport(origin): + log.debug('Origin "%s" is not HTTPS, CORS not allowed.', origin) + return {} + elif not self.request_validator.is_origin_allowed( + request.client_id, origin, request): + log.debug('Invalid origin "%s", CORS not allowed.', origin) + return {} + else: + log.debug('Valid origin "%s", injecting CORS headers.', origin) + return {'Access-Control-Allow-Origin': origin} diff --git a/oauthlib/oauth2/rfc6749/request_validator.py b/oauthlib/oauth2/rfc6749/request_validator.py index 817d594..610a708 100644 --- a/oauthlib/oauth2/rfc6749/request_validator.py +++ b/oauthlib/oauth2/rfc6749/request_validator.py @@ -649,3 +649,28 @@ class RequestValidator: """ raise NotImplementedError('Subclasses must implement this method.') + + def is_origin_allowed(self, client_id, origin, request, *args, **kwargs): + """Indicate if the given origin is allowed to access the token endpoint + via Cross-Origin Resource Sharing (CORS). CORS is used by browser-based + clients, such as Single-Page Applications, to perform the Authorization + Code Grant. + + (Note: If performing Authorization Code Grant via a public client such + as a browser, you should use PKCE as well.) + + If this method returns true, the appropriate CORS headers will be added + to the response. By default this method always returns False, meaning + CORS is disabled. + + :param client_id: Unicode client identifier. + :param redirect_uri: Unicode origin. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: bool + + Method is used by: + - Authorization Code Grant + + """ + return False
oauthlib/oauthlib
f6710113fdba6efe3710efdc2e26a08398509cb2
diff --git a/tests/oauth2/rfc6749/endpoints/test_metadata.py b/tests/oauth2/rfc6749/endpoints/test_metadata.py index 681119a..d93f849 100644 --- a/tests/oauth2/rfc6749/endpoints/test_metadata.py +++ b/tests/oauth2/rfc6749/endpoints/test_metadata.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- from oauthlib.oauth2 import MetadataEndpoint, Server, TokenEndpoint +import json from tests.unittest import TestCase @@ -37,6 +38,20 @@ class MetadataEndpointTest(TestCase): self.maxDiff = None self.assertEqual(openid_claims, oauth2_claims) + def test_create_metadata_response(self): + endpoint = TokenEndpoint(None, None, grant_types={"password": None}) + metadata = MetadataEndpoint([endpoint], { + "issuer": 'https://foo.bar', + "token_endpoint": "https://foo.bar/token" + }) + headers, body, status = metadata.create_metadata_response('/', 'GET') + assert headers == { + 'Content-Type': 'application/json', + 'Access-Control-Allow-Origin': '*', + } + claims = json.loads(body) + assert claims['issuer'] == 'https://foo.bar' + def test_token_endpoint(self): endpoint = TokenEndpoint(None, None, grant_types={"password": None}) metadata = MetadataEndpoint([endpoint], { diff --git a/tests/oauth2/rfc6749/grant_types/test_authorization_code.py b/tests/oauth2/rfc6749/grant_types/test_authorization_code.py index dec5323..77e1a81 100644 --- a/tests/oauth2/rfc6749/grant_types/test_authorization_code.py +++ b/tests/oauth2/rfc6749/grant_types/test_authorization_code.py @@ -28,6 +28,7 @@ class AuthorizationCodeGrantTest(TestCase): self.mock_validator = mock.MagicMock() self.mock_validator.is_pkce_required.return_value = False self.mock_validator.get_code_challenge.return_value = None + self.mock_validator.is_origin_allowed.return_value = False self.mock_validator.authenticate_client.side_effect = self.set_client self.auth = AuthorizationCodeGrant(request_validator=self.mock_validator) @@ -339,3 +340,43 @@ class AuthorizationCodeGrantTest(TestCase): ) self.auth.create_authorization_response(self.request, bearer) self.mock_validator.save_token.assert_called_once() + + # CORS + + def test_create_cors_headers(self): + bearer = BearerToken(self.mock_validator) + self.request.headers['origin'] = 'https://foo.bar' + self.mock_validator.is_origin_allowed.return_value = True + + headers = self.auth.create_token_response(self.request, bearer)[0] + self.assertEqual( + headers['Access-Control-Allow-Origin'], 'https://foo.bar' + ) + self.mock_validator.is_origin_allowed.assert_called_once_with( + 'abcdef', 'https://foo.bar', self.request + ) + + def test_create_cors_headers_no_origin(self): + bearer = BearerToken(self.mock_validator) + headers = self.auth.create_token_response(self.request, bearer)[0] + self.assertNotIn('Access-Control-Allow-Origin', headers) + self.mock_validator.is_origin_allowed.assert_not_called() + + def test_create_cors_headers_insecure_origin(self): + bearer = BearerToken(self.mock_validator) + self.request.headers['origin'] = 'http://foo.bar' + + headers = self.auth.create_token_response(self.request, bearer)[0] + self.assertNotIn('Access-Control-Allow-Origin', headers) + self.mock_validator.is_origin_allowed.assert_not_called() + + def test_create_cors_headers_invalid_origin(self): + bearer = BearerToken(self.mock_validator) + self.request.headers['origin'] = 'https://foo.bar' + self.mock_validator.is_origin_allowed.return_value = False + + headers = self.auth.create_token_response(self.request, bearer)[0] + self.assertNotIn('Access-Control-Allow-Origin', headers) + self.mock_validator.is_origin_allowed.assert_called_once_with( + 'abcdef', 'https://foo.bar', self.request + ) diff --git a/tests/oauth2/rfc6749/test_request_validator.py b/tests/oauth2/rfc6749/test_request_validator.py index 9688b5a..7a8d06b 100644 --- a/tests/oauth2/rfc6749/test_request_validator.py +++ b/tests/oauth2/rfc6749/test_request_validator.py @@ -46,3 +46,6 @@ class RequestValidatorTest(TestCase): self.assertRaises(NotImplementedError, v.validate_user, 'username', 'password', 'client', 'request') self.assertTrue(v.client_authentication_required('r')) + self.assertFalse( + v.is_origin_allowed('client_id', 'https://foo.bar', 'r') + )
CORS for metadata endpoint **Describe the feature** Return CORS headers for RFC6749 metadata endpoints. This will allow SPAs to fetch the metadata. **Additional context** The metadata endpoint is public and has no side effects, so should be safe to expose to all origins (`*`). I'm willing to submit a PR for this if I get a green light.
0.0
[ "tests/oauth2/rfc6749/endpoints/test_metadata.py::MetadataEndpointTest::test_create_metadata_response", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_cors_headers", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_cors_headers_invalid_origin", "tests/oauth2/rfc6749/test_request_validator.py::RequestValidatorTest::test_method_contracts" ]
[ "tests/oauth2/rfc6749/endpoints/test_metadata.py::MetadataEndpointTest::test_mandatory_fields", "tests/oauth2/rfc6749/endpoints/test_metadata.py::MetadataEndpointTest::test_openid_oauth2_preconfigured", "tests/oauth2/rfc6749/endpoints/test_metadata.py::MetadataEndpointTest::test_server_metadata", "tests/oauth2/rfc6749/endpoints/test_metadata.py::MetadataEndpointTest::test_token_endpoint", "tests/oauth2/rfc6749/endpoints/test_metadata.py::MetadataEndpointTest::test_token_endpoint_overridden", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_authenticate_client", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_authenticate_client_id", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_authentication_required", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_client_id_missing", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_code_modifier_called", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_correct_code_challenge_method_plain", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_correct_code_challenge_method_s256", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_authorization_grant", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_authorization_grant_no_scopes", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_authorization_grant_state", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_authorization_response", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_cors_headers_insecure_origin", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_cors_headers_no_origin", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_token_response", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_token_response_without_refresh_token", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_custom_auth_validators", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_custom_token_validators", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_hybrid_token_save", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_invalid_grant", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_invalid_grant_type", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_invalid_redirect_uri", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_invalid_request", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_invalid_request_duplicates", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_challenge_missing", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_default_method", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_optional_verifier_missing_challenge_valid", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_optional_verifier_valid_challenge_missing", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_required_verifier_invalid_challenge_valid_method_valid", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_required_verifier_missing_challenge_missing", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_required_verifier_missing_challenge_valid", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_required_verifier_valid_challenge_missing", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_required_verifier_valid_challenge_valid_method_valid", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_required_verifier_valid_challenge_valid_method_wrong", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_verifier_missing", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_verifier_valid_challenge_valid_method_missing", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_wrong_method", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_wrong_code_challenge_method_plain", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_wrong_code_challenge_method_s256" ]
2021-11-17 07:45:02+00:00
4,329
oauthlib__oauthlib-791
diff --git a/docs/installation.rst b/docs/installation.rst index 0e00e39..61428ce 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -118,7 +118,7 @@ Install from GitHub ------------------- Alternatively, install it directly from the source repository on -GitHub. This is the "bleading edge" version, but it may be useful for +GitHub. This is the "bleeding edge" version, but it may be useful for accessing bug fixes and/or new features that have not been released. Standard install diff --git a/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py b/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py index 97aeca9..b799823 100644 --- a/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py +++ b/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py @@ -10,6 +10,7 @@ import logging from oauthlib import common from .. import errors +from ..utils import is_secure_transport from .base import GrantTypeBase log = logging.getLogger(__name__) @@ -312,6 +313,7 @@ class AuthorizationCodeGrant(GrantTypeBase): self.request_validator.save_token(token, request) self.request_validator.invalidate_authorization_code( request.client_id, request.code, request) + headers.update(self._create_cors_headers(request)) return headers, json.dumps(token), 200 def validate_authorization_request(self, request): @@ -545,3 +547,20 @@ class AuthorizationCodeGrant(GrantTypeBase): if challenge_method in self._code_challenge_methods: return self._code_challenge_methods[challenge_method](verifier, challenge) raise NotImplementedError('Unknown challenge_method %s' % challenge_method) + + def _create_cors_headers(self, request): + """If CORS is allowed, create the appropriate headers.""" + if 'origin' not in request.headers: + return {} + + origin = request.headers['origin'] + if not is_secure_transport(origin): + log.debug('Origin "%s" is not HTTPS, CORS not allowed.', origin) + return {} + elif not self.request_validator.is_origin_allowed( + request.client_id, origin, request): + log.debug('Invalid origin "%s", CORS not allowed.', origin) + return {} + else: + log.debug('Valid origin "%s", injecting CORS headers.', origin) + return {'Access-Control-Allow-Origin': origin} diff --git a/oauthlib/oauth2/rfc6749/request_validator.py b/oauthlib/oauth2/rfc6749/request_validator.py index 817d594..610a708 100644 --- a/oauthlib/oauth2/rfc6749/request_validator.py +++ b/oauthlib/oauth2/rfc6749/request_validator.py @@ -649,3 +649,28 @@ class RequestValidator: """ raise NotImplementedError('Subclasses must implement this method.') + + def is_origin_allowed(self, client_id, origin, request, *args, **kwargs): + """Indicate if the given origin is allowed to access the token endpoint + via Cross-Origin Resource Sharing (CORS). CORS is used by browser-based + clients, such as Single-Page Applications, to perform the Authorization + Code Grant. + + (Note: If performing Authorization Code Grant via a public client such + as a browser, you should use PKCE as well.) + + If this method returns true, the appropriate CORS headers will be added + to the response. By default this method always returns False, meaning + CORS is disabled. + + :param client_id: Unicode client identifier. + :param redirect_uri: Unicode origin. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: bool + + Method is used by: + - Authorization Code Grant + + """ + return False
oauthlib/oauthlib
f6710113fdba6efe3710efdc2e26a08398509cb2
diff --git a/tests/oauth2/rfc6749/grant_types/test_authorization_code.py b/tests/oauth2/rfc6749/grant_types/test_authorization_code.py index dec5323..77e1a81 100644 --- a/tests/oauth2/rfc6749/grant_types/test_authorization_code.py +++ b/tests/oauth2/rfc6749/grant_types/test_authorization_code.py @@ -28,6 +28,7 @@ class AuthorizationCodeGrantTest(TestCase): self.mock_validator = mock.MagicMock() self.mock_validator.is_pkce_required.return_value = False self.mock_validator.get_code_challenge.return_value = None + self.mock_validator.is_origin_allowed.return_value = False self.mock_validator.authenticate_client.side_effect = self.set_client self.auth = AuthorizationCodeGrant(request_validator=self.mock_validator) @@ -339,3 +340,43 @@ class AuthorizationCodeGrantTest(TestCase): ) self.auth.create_authorization_response(self.request, bearer) self.mock_validator.save_token.assert_called_once() + + # CORS + + def test_create_cors_headers(self): + bearer = BearerToken(self.mock_validator) + self.request.headers['origin'] = 'https://foo.bar' + self.mock_validator.is_origin_allowed.return_value = True + + headers = self.auth.create_token_response(self.request, bearer)[0] + self.assertEqual( + headers['Access-Control-Allow-Origin'], 'https://foo.bar' + ) + self.mock_validator.is_origin_allowed.assert_called_once_with( + 'abcdef', 'https://foo.bar', self.request + ) + + def test_create_cors_headers_no_origin(self): + bearer = BearerToken(self.mock_validator) + headers = self.auth.create_token_response(self.request, bearer)[0] + self.assertNotIn('Access-Control-Allow-Origin', headers) + self.mock_validator.is_origin_allowed.assert_not_called() + + def test_create_cors_headers_insecure_origin(self): + bearer = BearerToken(self.mock_validator) + self.request.headers['origin'] = 'http://foo.bar' + + headers = self.auth.create_token_response(self.request, bearer)[0] + self.assertNotIn('Access-Control-Allow-Origin', headers) + self.mock_validator.is_origin_allowed.assert_not_called() + + def test_create_cors_headers_invalid_origin(self): + bearer = BearerToken(self.mock_validator) + self.request.headers['origin'] = 'https://foo.bar' + self.mock_validator.is_origin_allowed.return_value = False + + headers = self.auth.create_token_response(self.request, bearer)[0] + self.assertNotIn('Access-Control-Allow-Origin', headers) + self.mock_validator.is_origin_allowed.assert_called_once_with( + 'abcdef', 'https://foo.bar', self.request + ) diff --git a/tests/oauth2/rfc6749/test_request_validator.py b/tests/oauth2/rfc6749/test_request_validator.py index 9688b5a..7a8d06b 100644 --- a/tests/oauth2/rfc6749/test_request_validator.py +++ b/tests/oauth2/rfc6749/test_request_validator.py @@ -46,3 +46,6 @@ class RequestValidatorTest(TestCase): self.assertRaises(NotImplementedError, v.validate_user, 'username', 'password', 'client', 'request') self.assertTrue(v.client_authentication_required('r')) + self.assertFalse( + v.is_origin_allowed('client_id', 'https://foo.bar', 'r') + )
CORS for token endpoint **Describe the feature** Return CORS headers for RFC6749 token endpoint. This will allow SPAs perform an Authentication Code Grant. Although I cannot think of any reason why it would be problematic to expose to all origins (`*`), for safety we should restrict to a per-client origin list. We could add a method (`get_allowed_origins`?) to the request validator. By default this will return `None`, which will disable CORS for the endpoint. This way CORS will be only be active if explicitly enable. **Additional context** CORS is necessary to perform Authentication Code Grant w/ PKCE on an SPA, and as PKCE was specifically developed to increase security for public clients (including SPAs) it should be supported by OAuthlib. I'm willing to submit a PR for this if given a green light.
0.0
[ "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_cors_headers", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_cors_headers_invalid_origin", "tests/oauth2/rfc6749/test_request_validator.py::RequestValidatorTest::test_method_contracts" ]
[ "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_authenticate_client", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_authenticate_client_id", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_authentication_required", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_client_id_missing", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_code_modifier_called", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_correct_code_challenge_method_plain", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_correct_code_challenge_method_s256", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_authorization_grant", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_authorization_grant_no_scopes", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_authorization_grant_state", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_authorization_response", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_cors_headers_insecure_origin", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_cors_headers_no_origin", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_token_response", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_create_token_response_without_refresh_token", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_custom_auth_validators", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_custom_token_validators", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_hybrid_token_save", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_invalid_grant", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_invalid_grant_type", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_invalid_redirect_uri", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_invalid_request", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_invalid_request_duplicates", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_challenge_missing", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_default_method", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_optional_verifier_missing_challenge_valid", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_optional_verifier_valid_challenge_missing", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_required_verifier_invalid_challenge_valid_method_valid", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_required_verifier_missing_challenge_missing", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_required_verifier_missing_challenge_valid", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_required_verifier_valid_challenge_missing", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_required_verifier_valid_challenge_valid_method_valid", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_required_verifier_valid_challenge_valid_method_wrong", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_verifier_missing", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_verifier_valid_challenge_valid_method_missing", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_pkce_wrong_method", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_wrong_code_challenge_method_plain", "tests/oauth2/rfc6749/grant_types/test_authorization_code.py::AuthorizationCodeGrantTest::test_wrong_code_challenge_method_s256" ]
2021-11-17 07:48:35+00:00
4,330